67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
from flask import current_app
|
|
from app.models.user_model import User
|
|
from app.services.db_service import db
|
|
from app.services.ldap_service import LDAPService
|
|
|
|
class UserService:
|
|
|
|
@staticmethod
|
|
def register_user(name, email, password):
|
|
if User.query.filter_by(email=email).first():
|
|
return None
|
|
|
|
user = User(name=name, email=email, auth_source="local")
|
|
user.set_password(password)
|
|
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
return user
|
|
|
|
@staticmethod
|
|
def validate_login(identifier, password):
|
|
"""
|
|
identifier = whatever was typed in the login form. Can be an email
|
|
(local users) or an LDAP username, depending on USE_LDAP_AUTH.
|
|
"""
|
|
if current_app.config.get("USE_LDAP_AUTH"):
|
|
ldap_user = UserService._validate_ldap_login(identifier, password)
|
|
if ldap_user:
|
|
return ldap_user
|
|
return None
|
|
user = User.query.filter_by(email=identifier).first()
|
|
if user and user.check_password(password):
|
|
return user
|
|
return None
|
|
|
|
@staticmethod
|
|
def _validate_ldap_login(username, password):
|
|
ldap_info = LDAPService.authenticate(username, password)
|
|
if not ldap_info:
|
|
return None
|
|
return UserService._get_or_create_ldap_user(ldap_info)
|
|
|
|
@staticmethod
|
|
def _get_or_create_ldap_user(ldap_info):
|
|
"""
|
|
LDAP is the source of truth for the password. We still keep a row in
|
|
our local `users` table (no password) so the rest of the app - which
|
|
expects a User with an id - keeps working unchanged.
|
|
"""
|
|
user = User.query.filter_by(email=ldap_info["email"]).first()
|
|
if user is None:
|
|
user = User(
|
|
name=ldap_info["name"],
|
|
email=ldap_info["email"],
|
|
auth_source="ldap",
|
|
)
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
elif user.name != ldap_info["name"]:
|
|
user.name = ldap_info["name"]
|
|
db.session.commit()
|
|
return user
|
|
|
|
@staticmethod
|
|
def get_all_users():
|
|
return User.query.all()
|