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.

73 lines
2.3 KiB

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