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.

162 lines
4.8 KiB

  1. from flask import request, render_template, flash, redirect, \
  2. url_for, Blueprint, g
  3. from flask_login import current_user, login_user, \
  4. logout_user, login_required
  5. from ldap3 import MODIFY_REPLACE
  6. from ldap3.core.exceptions import LDAPBindError
  7. from accounts import login_manager, db
  8. from accounts.auth.models import User, LoginForm, get_ldap_connection
  9. from email_validator import validate_email, EmailNotValidError
  10. auth = Blueprint('auth', __name__)
  11. @login_manager.user_loader
  12. def load_user(id):
  13. return User.query.get(int(id))
  14. @auth.before_request
  15. def get_current_user():
  16. g.user = current_user
  17. @auth.route('/')
  18. @login_required
  19. def home():
  20. return render_template('profile.j2', user = current_user.get_user_dict())
  21. @auth.route('/update/email', methods=['POST'])
  22. @login_required
  23. def update_email():
  24. if request.method == 'POST':
  25. email = request.form['email']
  26. dn = request.form['dn']
  27. if email != None and len(email) > 0:
  28. try:
  29. # Validate.
  30. valid = validate_email(email)
  31. # Update with the normalized form.
  32. conn = get_ldap_connection()
  33. conn.modify(dn, {'mail': [(MODIFY_REPLACE, [valid.email])]})
  34. return 'Success'
  35. except EmailNotValidError as e:
  36. # email is not valid, exception message is human-readable
  37. print(str(e))
  38. return 'Invalid email address'
  39. return 'Email cannot be empty'
  40. @auth.route('/update/name', methods=['POST'])
  41. @login_required
  42. def update_name():
  43. if request.method == 'POST':
  44. firstName = request.form['firstName']
  45. lastName = request.form['lastName']
  46. dn = request.form['dn']
  47. if (firstName != None and len(firstName) > 0) and (lastName != None and len(lastName) > 0):
  48. conn = get_ldap_connection()
  49. conn.modify(dn, {'givenName': [(MODIFY_REPLACE, [firstName])],
  50. 'sn': [(MODIFY_REPLACE, [lastName])]})
  51. return 'Success'
  52. return 'Name cannot be empty'
  53. @auth.route('/update/username', methods=['POST'])
  54. @login_required
  55. def update_username():
  56. if request.method == 'POST':
  57. userName = request.form['userName']
  58. dn = request.form['dn']
  59. if userName != None and len(userName) > 0:
  60. conn = get_ldap_connection()
  61. conn.modify(dn, {'uid': [(MODIFY_REPLACE, [userName])]})
  62. return 'Success'
  63. return 'Username cannot be empty'
  64. @auth.route('/update/password', methods=['POST'])
  65. @login_required
  66. def update_password():
  67. if request.method == 'POST':
  68. currentPassword = request.form['currentPassword']
  69. newPassword = request.form['newPassword']
  70. confirmPassword = request.form['confirmPassword']
  71. dn = request.form['dn']
  72. if currentPassword == '':
  73. return 'Please enter your current password'
  74. if newPassword == '':
  75. return 'Please enter a new password'
  76. if confirmPassword == '':
  77. return 'Please confirm your new password'
  78. if newPassword != confirmPassword:
  79. return 'Could not confirm new password, please make sure you typed it correctly'
  80. try:
  81. User.try_login(current_user.username, currentPassword)
  82. except LDAPBindError:
  83. return 'Current password is incorrect'
  84. conn = get_ldap_connection()
  85. conn.extend.standard.modify_password(user=dn, new_password=newPassword)
  86. return 'Success'
  87. return 'Error'
  88. @auth.route('/login', methods=['GET', 'POST'])
  89. def login():
  90. if current_user.is_authenticated:
  91. flash('You are already logged in.')
  92. return redirect(url_for('auth.home'))
  93. form = LoginForm(request.form)
  94. if request.method == 'POST' and form.validate():
  95. username = request.form.get('username')
  96. password = request.form.get('password')
  97. try:
  98. User.try_login(username, password)
  99. except LDAPBindError:
  100. flash(
  101. 'Invalid username or password. Please try again.',
  102. 'danger')
  103. return render_template('login.j2', form=form)
  104. user = User.query.filter(User.username == username).first()
  105. print(user)
  106. if user is None:
  107. user = User(username)
  108. db.session.add(user)
  109. user.authenticated = True
  110. db.session.commit()
  111. login_user(user, remember=form.remember_me.data)
  112. print('You have successfully logged in.')
  113. return redirect(url_for('auth.home'))
  114. if form.errors:
  115. flash(form.errors, 'danger')
  116. return render_template('login.j2', form=form)
  117. @auth.route('/logout')
  118. @login_required
  119. def logout():
  120. user = current_user
  121. user.authenticated = False
  122. db.session.add(user)
  123. db.session.commit()
  124. logout_user()
  125. return redirect(url_for('auth.home'))