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.

70 lines
2.2 KiB

  1. from ldap3 import Server, Connection
  2. from flask_wtf import FlaskForm
  3. from flask_login import UserMixin
  4. from ldap3.core.exceptions import LDAPBindError
  5. from wtforms import StringField, PasswordField, BooleanField, SubmitField
  6. from wtforms.validators import DataRequired
  7. from accounts import app, db
  8. def get_ldap_connection():
  9. server = Server(app.config['LDAP_HOST'])
  10. conn = Connection(server, app.config['LDAP_USERNAME'], app.config['LDAP_PASSWORD'], auto_bind=True)
  11. return conn
  12. class User(db.Model):
  13. __tablename__ = 'user'
  14. id = db.Column(db.Integer, primary_key=True)
  15. username = db.Column(db.String(100))
  16. authenticated = db.Column(db.Boolean, default=False)
  17. def __init__(self, username):
  18. self.username = username
  19. @staticmethod
  20. def try_login(username, password):
  21. conn = get_ldap_connection()
  22. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % username, attributes=['*'])
  23. if len(conn.entries) > 0:
  24. Connection(app.config['LDAP_HOST'], conn.entries[0].entry_dn, password, auto_bind=True)
  25. return
  26. raise LDAPBindError
  27. def is_authenticated(self):
  28. return self.authenticated
  29. def is_active(self):
  30. return True
  31. def is_anonymous(self):
  32. return False
  33. def get_id(self):
  34. return self.id
  35. def get_user_dict(self):
  36. user = {'dn': '',
  37. 'firstName': '',
  38. 'lastName': '',
  39. 'email': '',
  40. 'userName': self.username,
  41. }
  42. conn = get_ldap_connection()
  43. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % self.username, attributes=['*'])
  44. user['dn'] = conn.entries[0].entry_dn
  45. user['firstName'] = conn.entries[0].givenName.value
  46. user['lastName'] = conn.entries[0].sn.value
  47. user['email'] = conn.entries[0].mail.value
  48. return user
  49. class LoginForm(FlaskForm):
  50. username = StringField('Username', validators=[DataRequired()])
  51. password = PasswordField('Password', validators=[DataRequired()])
  52. remember_me = BooleanField('Remember Me')
  53. submit = SubmitField('Sign In')