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.

159 lines
5.1 KiB

4 years ago
  1. import ldap as l
  2. from ldap3 import Server, Connection, ALL, MODIFY_REPLACE
  3. from flask import Flask, g, request, session, redirect, url_for, render_template
  4. from flask_simpleldap import LDAP
  5. from flask_bootstrap import Bootstrap
  6. from email_validator import validate_email, EmailNotValidError
  7. import os
  8. app = Flask(__name__)
  9. Bootstrap(app)
  10. app.secret_key = 'asdf'
  11. app.debug = True
  12. # Base
  13. app.config['LDAP_REALM_NAME'] = 'OpenLDAP Authentication'
  14. app.config['LDAP_HOST'] = os.environ.get('LDAP_HOST')
  15. app.config['LDAP_BASE_DN'] = os.environ.get('LDAP_BASE_DN')
  16. app.config['LDAP_USERNAME'] = os.environ.get('LDAP_USERNAME')
  17. app.config['LDAP_PASSWORD'] = os.environ.get('LDAP_PASSWORD')
  18. # OpenLDAP
  19. app.config['LDAP_OBJECTS_DN'] = 'dn'
  20. app.config['LDAP_OPENLDAP'] = True
  21. app.config['LDAP_USER_OBJECT_FILTER'] = '(&(objectclass=posixAccount)(uid=%s))'
  22. ldap = LDAP(app)
  23. server = Server(app.config['LDAP_HOST'])
  24. conn = Connection(server, app.config['LDAP_USERNAME'], app.config['LDAP_PASSWORD'], auto_bind=True)
  25. @app.before_request
  26. def before_request():
  27. g.user = None
  28. if 'user_id' in session:
  29. # This is where you'd query your database to get the user info.
  30. g.user = {}
  31. @app.route('/')
  32. @ldap.login_required
  33. def index():
  34. user_dict = ldap.get_object_details(session['user_id'])
  35. if 'user_id' in session:
  36. user = {'dn': 'cn={},cn=usergroup,ou=users,dc=technicalincompetence,dc=club'.format(user_dict['cn'][0].decode('ascii')),
  37. 'firstName': user_dict['givenName'][0].decode('ascii'),
  38. 'lastName': user_dict['sn'][0].decode('ascii'),
  39. 'email': user_dict['mail'][0].decode('ascii'),
  40. 'userName': user_dict['uid'][0].decode('ascii'),
  41. }
  42. return render_template('profile.j2', user = user)
  43. @app.route('/login', methods=['GET', 'POST'])
  44. def login():
  45. if g.user:
  46. return redirect(url_for('index'))
  47. if request.method == 'POST':
  48. user = request.form['user']
  49. passwd = request.form['passwd']
  50. test = ldap.bind_user(user, passwd)
  51. if test is None or passwd == '':
  52. return render_template('login.j2', error='Invalid credentials')
  53. else:
  54. session['user_id'] = request.form['user']
  55. session['passwd'] = request.form['passwd']
  56. return redirect('/')
  57. return render_template('login.j2')
  58. @ldap.login_required
  59. @app.route('/update/email', methods=['POST'])
  60. def update_email():
  61. if request.method == 'POST':
  62. email = request.form['email']
  63. dn = request.form['dn']
  64. if email != None and len(email) > 0:
  65. try:
  66. # Validate.
  67. valid = validate_email(email)
  68. # Update with the normalized form.
  69. conn.modify(dn, {'mail': [(MODIFY_REPLACE, [valid.email])]})
  70. return 'Success'
  71. except EmailNotValidError as e:
  72. # email is not valid, exception message is human-readable
  73. print(str(e))
  74. return 'Invalid email address'
  75. return 'Email cannot be empty'
  76. @ldap.login_required
  77. @app.route('/update/name', methods=['POST'])
  78. def update_name():
  79. if request.method == 'POST':
  80. firstName = request.form['firstName']
  81. lastName = request.form['lastName']
  82. dn = request.form['dn']
  83. if (firstName != None and len(firstName) > 0) and (lastName != None and len(lastName) > 0):
  84. conn.modify(dn, {'givenName': [(MODIFY_REPLACE, [firstName])],
  85. 'sn': [(MODIFY_REPLACE, [lastName])]})
  86. return 'Success'
  87. return 'Name cannot be empty'
  88. @ldap.login_required
  89. @app.route('/update/username', methods=['POST'])
  90. def update_username():
  91. if request.method == 'POST':
  92. userName = request.form['userName']
  93. dn = request.form['dn']
  94. if userName != None and len(userName) > 0:
  95. conn.modify(dn, {'uid': [(MODIFY_REPLACE, [userName])]})
  96. return 'Success'
  97. return 'Username cannot be empty'
  98. @ldap.login_required
  99. @app.route('/update/password', methods=['POST'])
  100. def update_password():
  101. if request.method == 'POST':
  102. currentPassword = request.form['currentPassword']
  103. newPassword = request.form['newPassword']
  104. confirmPassword = request.form['confirmPassword']
  105. dn = request.form['dn']
  106. if currentPassword == '':
  107. return 'Please enter your current password'
  108. if newPassword == '':
  109. return 'Please enter a new password'
  110. if confirmPassword == '':
  111. return 'Please confirm your new password'
  112. if newPassword != confirmPassword:
  113. return 'Could not confirm new password, please make sure you typed it correctly'
  114. test = ldap.bind_user(session['user_id'], currentPassword)
  115. if test is None:
  116. return 'Current password is incorrect'
  117. else:
  118. conn.extend.standard.modify_password(user=dn, new_password=newPassword)
  119. return 'Success'
  120. return 'Error'
  121. @app.route('/logout')
  122. def logout():
  123. session.pop('user_id', None)
  124. return redirect(url_for('index'))
  125. if __name__ == '__main__':
  126. app.run()