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.

72 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. password = db.Column(db.String(128))
  17. authenticated = db.Column(db.Boolean, default=False)
  18. def __init__(self, username, password):
  19. self.username = username
  20. self.password = password
  21. @staticmethod
  22. def try_login(username, password):
  23. conn = get_ldap_connection()
  24. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % username, attributes=['*'])
  25. if len(conn.entries) > 0:
  26. Connection(app.config['LDAP_HOST'], conn.entries[0].entry_dn, password, auto_bind=True)
  27. return
  28. raise LDAPBindError
  29. def is_authenticated(self):
  30. return self.authenticated
  31. def is_active(self):
  32. return True
  33. def is_anonymous(self):
  34. return False
  35. def get_id(self):
  36. return self.id
  37. def get_user_dict(self):
  38. user = {'dn': '',
  39. 'firstName': '',
  40. 'lastName': '',
  41. 'email': '',
  42. 'userName': self.username,
  43. }
  44. conn = get_ldap_connection()
  45. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % self.username, attributes=['*'])
  46. user['dn'] = conn.entries[0].entry_dn
  47. user['firstName'] = conn.entries[0].givenName.value
  48. user['lastName'] = conn.entries[0].sn.value
  49. user['email'] = conn.entries[0].mail.value
  50. return user
  51. class LoginForm(FlaskForm):
  52. username = StringField('Username', validators=[DataRequired()])
  53. password = PasswordField('Password', validators=[DataRequired()])
  54. remember_me = BooleanField('Remember Me')
  55. submit = SubmitField('Sign In')