LILiK login and user managment web interface
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
4.0 KiB

8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. #!/usr/bin/env python3
  2. import lilikusers
  3. import logging
  4. from logging.handlers import RotatingFileHandler
  5. import json
  6. from flask import Flask, jsonify
  7. from flask import request, Response, redirect, url_for
  8. from functools import wraps
  9. app = Flask(__name__)
  10. logfmt = logging.Formatter('time=%(asctime)s level=%(levelname)s app=%(name) msg=%(message)s')
  11. logrotate = RotatingFileHandler(
  12. '/var/log/login/server',
  13. backupCount=10,
  14. )
  15. logrotate.setFormatter(logfmt)
  16. logrotate.setLevel(logging.DEBUG)
  17. app.logger.addHandler(logrotate)
  18. lilik_ldap = lilikusers.LILiK_LDAP()
  19. def check_auth(user_name, password):
  20. """
  21. This function is called to check if a username /
  22. password combination is valid.
  23. """
  24. if lilik_ldap.login(user_name, password):
  25. return lilik_ldap.get_user(user_name)
  26. app.logger.warning('Invalid login for <{}>'.format(user_name))
  27. raise ValueError
  28. def authenticate():
  29. """Sends a 401 response that enables basic auth"""
  30. app.logger.debug('Request http basic auth')
  31. return Response(
  32. 'Could not verify your access level for that URL.\n'
  33. 'You have to login with proper credentials\n', 401)
  34. def admin_required():
  35. """Sends a 401 response that enables basic auth"""
  36. app.logger.debug('Request admin level')
  37. return Response(
  38. 'Could not verify your access level for that URL.\n'
  39. 'You have to login with admin rights\n', 401)
  40. def requires_auth(f):
  41. @wraps(f)
  42. def decorated(*args, **kwargs):
  43. auth = request.authorization
  44. if not auth:
  45. return authenticate()
  46. try:
  47. user = check_auth(auth.username, auth.password)
  48. except ValueError:
  49. app.logger.warning('Authentication failed for <{}>'.format(auth.username))
  50. return authenticate()
  51. return f(user, *args, **kwargs)
  52. return decorated
  53. def requires_admin_auth(f):
  54. @wraps(f)
  55. def decorated(user, *args, **kwargs):
  56. if not user.services['admin']:
  57. app.logger.warning('Admin privilege required for user <{}>'.format(user.uid))
  58. return admin_required()
  59. return f(user, *args, **kwargs)
  60. return decorated
  61. def requires_same_user_or_admin_auth(f):
  62. @wraps(f)
  63. def decorated(user, user_name, *args, **kwargs):
  64. if not user.services['admin'] and user.uid != user_name:
  65. app.logger.warning('Admin privilege required for user <{}>'.format(user.uid))
  66. return admin_required()
  67. return f(user, user_name, *args, **kwargs)
  68. return decorated
  69. @app.route('/api/users', methods=['GET'])
  70. @requires_auth
  71. @requires_admin_auth
  72. def get_users(user):
  73. ''' return the list of users'''
  74. return jsonify(lilik_ldap.get_users())
  75. @app.route('/api/users/<user_name>', methods=['GET'])
  76. @requires_auth
  77. @requires_same_user_or_admin_auth
  78. def get_user(user, user_name):
  79. ''' return the list of users'''
  80. return jsonify(lilik_ldap.get_user(user_name).to_dict())
  81. @app.route('/api/users/<user_name>', methods=['PUT'])
  82. @requires_auth
  83. @requires_same_user_or_admin_auth
  84. def update_user(user, user_name):
  85. new_lilik_user = request.get_json()
  86. app.logger.info('User <{}> editing user <{}>'.format(user.uid, user_name))
  87. user_to_edit = lilik_ldap.get_user(user_name)
  88. diff = user_to_edit.diff(new_lilik_user)
  89. is_permitted_self_changes = diff.changed() <= set(['cn']) and diff.removed() == set() and diff.added() <= set(['userPassword'])
  90. if user.services['admin'] or is_permitted_self_changes:
  91. user_to_edit.update(new_lilik_user)
  92. return jsonify(lilik_ldap.get_user(user_name).to_dict())
  93. @app.route('/api/users', methods=['POST'])
  94. @requires_auth
  95. @requires_admin_auth
  96. def new_user(user):
  97. app.logger.info('User <{}> create a new user'.format(user.uid))
  98. new_lilik_user = request.get_json()
  99. app.logger.info(lilik_ldap.new_user(new_lilik_user))
  100. return jsonify(lilik_ldap.get_user(new_lilik_user['uid']).to_dict())
  101. @app.route('/')
  102. def home():
  103. return redirect(url_for('static', filename='index.html'))
  104. if __name__ == '__main__':
  105. app.run(debug=True)