canaille-globuzma/canaille/models.py

405 lines
11 KiB
Python
Raw Normal View History

2020-08-14 11:18:08 +00:00
import datetime
2020-09-17 08:00:39 +00:00
import uuid
2021-12-20 22:57:27 +00:00
import ldap.filter
from authlib.oauth2.rfc6749 import AuthorizationCodeMixin
from authlib.oauth2.rfc6749 import ClientMixin
from authlib.oauth2.rfc6749 import TokenMixin
from authlib.oauth2.rfc6749 import util
from flask import current_app
from flask import session
from .ldaputils import LDAPObject
2020-08-14 11:18:08 +00:00
class User(LDAPObject):
2021-12-03 17:37:25 +00:00
DEFAULT_OBJECT_CLASS = "inetOrgPerson"
DEFAULT_FILTER = "(|(uid={login})(mail={login}))"
DEFAULT_ID_ATTRIBUTE = "cn"
2021-12-02 17:23:14 +00:00
def __init__(self, *args, **kwargs):
self.read = set()
self.write = set()
self.permissions = set()
2021-12-03 15:49:19 +00:00
self._groups = None
2021-12-02 17:23:14 +00:00
super().__init__(*args, **kwargs)
2020-08-19 14:20:57 +00:00
@classmethod
2020-10-21 15:15:33 +00:00
def get(cls, login=None, dn=None, filter=None, conn=None):
2020-08-19 14:20:57 +00:00
conn = conn or cls.ldap()
2020-10-21 15:15:33 +00:00
if login:
2021-12-06 14:40:30 +00:00
filter = (
current_app.config["LDAP"]
2021-12-03 17:37:25 +00:00
.get("USER_FILTER", User.DEFAULT_FILTER)
2021-12-06 14:40:30 +00:00
.format(login=ldap.filter.escape_filter_chars(login))
)
2020-10-21 15:15:33 +00:00
2020-08-19 14:20:57 +00:00
user = super().get(dn, filter, conn)
2021-06-03 13:00:11 +00:00
if user:
2021-12-02 17:23:14 +00:00
user.load_permissions(conn)
2021-06-03 13:00:11 +00:00
2020-08-19 14:20:57 +00:00
return user
2021-06-03 13:00:11 +00:00
def load_groups(self, conn=None):
try:
2021-12-03 17:37:25 +00:00
group_filter = (
current_app.config["LDAP"]
.get("GROUP_USER_FILTER", Group.DEFAULT_USER_FILTER)
.format(user=self)
)
2021-12-06 14:40:30 +00:00
escaped_group_filter = ldap.filter.escape_filter_chars(group_filter)
self._groups = Group.filter(filter=escaped_group_filter, conn=conn)
except KeyError:
pass
2021-06-03 13:00:11 +00:00
2020-08-20 08:45:33 +00:00
@classmethod
2020-08-21 08:23:39 +00:00
def authenticate(cls, login, password, signin=False):
2020-10-21 15:15:33 +00:00
user = User.get(login)
2020-08-20 08:45:33 +00:00
if not user or not user.check_password(password):
return None
2020-08-19 14:20:57 +00:00
2020-08-21 08:23:39 +00:00
if signin:
user.login()
2020-08-20 08:45:33 +00:00
return user
2020-08-14 11:18:08 +00:00
2020-08-21 08:23:39 +00:00
def login(self):
try:
2020-12-29 08:31:46 +00:00
previous = (
session["user_dn"]
if isinstance(session["user_dn"], list)
else [session["user_dn"]]
)
session["user_dn"] = previous + [self.dn]
except KeyError:
session["user_dn"] = [self.dn]
2020-08-21 08:23:39 +00:00
2020-12-29 08:31:46 +00:00
@classmethod
2020-08-21 08:23:39 +00:00
def logout(self):
try:
2020-12-29 08:31:46 +00:00
if isinstance(session["user_dn"], list):
session["user_dn"].pop()
else:
del session["user_dn"]
except (IndexError, KeyError):
2020-08-21 08:23:39 +00:00
pass
def has_password(self):
return bool(self.userPassword)
2020-08-14 11:18:08 +00:00
def check_password(self, password):
conn = ldap.initialize(current_app.config["LDAP"]["URI"])
if current_app.config["LDAP"].get("TIMEOUT"):
conn.set_option(
ldap.OPT_NETWORK_TIMEOUT, current_app.config["LDAP"]["TIMEOUT"]
)
try:
conn.simple_bind_s(self.dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
finally:
conn.unbind_s()
2020-08-14 11:18:08 +00:00
2020-10-21 08:26:31 +00:00
def set_password(self, password, conn=None):
conn = conn or self.ldap()
try:
conn.passwd_s(
self.dn,
None,
password.encode("utf-8"),
2020-10-21 08:26:31 +00:00
)
except ldap.LDAPError:
return False
return True
2020-08-17 15:49:49 +00:00
@property
def name(self):
return self.cn[0]
2021-06-03 13:00:11 +00:00
@property
def groups(self):
2021-12-03 15:49:19 +00:00
if self._groups is None:
self.load_groups()
2021-06-03 13:00:11 +00:00
return self._groups
def set_groups(self, values, conn=None):
before = self._groups
after = [
v if isinstance(v, Group) else Group.get(dn=v, conn=conn) for v in values
]
to_add = set(after) - set(before)
to_del = set(before) - set(after)
for group in to_add:
group.add_member(self, conn=conn)
for group in to_del:
group.remove_member(self, conn=conn)
self._groups = after
2021-12-02 17:23:14 +00:00
def load_permissions(self, conn=None):
conn = conn or self.ldap()
for access_group_name, details in current_app.config["ACL"].items():
if not details.get("FILTER") or (
self.dn
and conn.search_s(self.dn, ldap.SCOPE_SUBTREE, details["FILTER"])
):
self.permissions |= set(details.get("PERMISSIONS", []))
self.read |= set(details.get("READ", []))
self.write |= set(details.get("WRITE", []))
2021-12-08 17:06:50 +00:00
def can_read(self, field):
return field in self.read | self.write
def can_writec(self, field):
return field in self.write
2021-12-06 23:07:32 +00:00
@property
def can_use_oidc(self):
return "use_oidc" in self.permissions
2021-12-02 17:23:14 +00:00
@property
def can_manage_users(self):
return "manage_users" in self.permissions
@property
def can_manage_groups(self):
return "manage_groups" in self.permissions
@property
def can_manage_oidc(self):
return "manage_oidc" in self.permissions
@property
def can_delete_account(self):
return "delete_account" in self.permissions
@property
def can_impersonate_users(self):
return "impersonate_users" in self.permissions
2021-06-03 13:00:11 +00:00
class Group(LDAPObject):
2021-12-03 17:37:25 +00:00
DEFAULT_OBJECT_CLASS = "groupOfNames"
DEFAULT_ID_ATTRIBUTE = "cn"
DEFAULT_NAME_ATTRIBUTE = "cn"
DEFAULT_USER_FILTER = "member={user.dn}"
2021-06-03 13:00:11 +00:00
@classmethod
def available_groups(cls, conn=None):
conn = conn or cls.ldap()
try:
2021-12-03 17:37:25 +00:00
attribute = current_app.config["LDAP"].get(
"GROUP_NAME_ATTRIBUTE", Group.DEFAULT_NAME_ATTRIBUTE
)
object_class = current_app.config["LDAP"].get(
"GROUP_CLASS", Group.DEFAULT_OBJECT_CLASS
)
except KeyError:
return []
groups = cls.filter(objectClass=object_class, conn=conn)
2021-12-08 14:01:35 +00:00
Group.ldap_object_attributes(conn=conn)
2021-06-03 13:00:11 +00:00
return [(group[attribute][0], group.dn) for group in groups]
2021-07-01 16:21:20 +00:00
@property
def name(self):
2021-12-03 17:37:25 +00:00
attribute = current_app.config["LDAP"].get(
"GROUP_NAME_ATTRIBUTE", Group.DEFAULT_NAME_ATTRIBUTE
)
2021-07-01 16:21:20 +00:00
return self[attribute][0]
2021-06-03 13:00:11 +00:00
def get_members(self, conn=None):
return [
User.get(dn=user_dn, conn=conn)
for user_dn in self.member
if User.get(dn=user_dn, conn=conn)
]
2021-06-03 13:00:11 +00:00
def add_member(self, user, conn=None):
self.member = self.member + [user.dn]
self.save(conn=conn)
def remove_member(self, user, conn=None):
self.member = [m for m in self.member if m != user.dn]
self.save(conn=conn)
2020-08-14 11:18:08 +00:00
class Client(LDAPObject, ClientMixin):
2020-09-24 13:20:36 +00:00
object_class = ["oauthClient"]
2020-09-03 15:19:41 +00:00
base = "ou=clients,ou=oauth"
2020-08-14 11:18:08 +00:00
id = "oauthClientID"
2020-08-17 13:49:48 +00:00
@property
def issue_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthIssueDate
2020-08-17 13:49:48 +00:00
2021-10-20 10:05:08 +00:00
@property
def preconsent(self):
2021-12-08 14:53:20 +00:00
return self.oauthPreconsent
2021-10-20 10:05:08 +00:00
2020-08-14 11:18:08 +00:00
def get_client_id(self):
2020-08-16 18:16:57 +00:00
return self.oauthClientID
2020-08-14 11:18:08 +00:00
def get_default_redirect_uri(self):
2020-08-17 15:49:49 +00:00
return self.oauthRedirectURIs[0]
2020-08-14 11:18:08 +00:00
def get_allowed_scope(self, scope):
2020-08-20 12:30:42 +00:00
return util.list_to_scope(self.oauthScope)
2020-08-14 11:18:08 +00:00
def check_redirect_uri(self, redirect_uri):
2020-08-17 15:49:49 +00:00
return redirect_uri in self.oauthRedirectURIs
2020-08-14 11:18:08 +00:00
def has_client_secret(self):
2020-08-17 07:45:35 +00:00
return bool(self.oauthClientSecret)
2020-08-14 11:18:08 +00:00
def check_client_secret(self, client_secret):
2020-08-16 18:16:57 +00:00
return client_secret == self.oauthClientSecret
2020-08-14 11:18:08 +00:00
def check_token_endpoint_auth_method(self, method):
2020-08-16 18:16:57 +00:00
return method == self.oauthTokenEndpointAuthMethod
2020-08-14 11:18:08 +00:00
def check_response_type(self, response_type):
2020-08-21 08:06:53 +00:00
return all(r in self.oauthResponseType for r in response_type.split(" "))
2020-08-14 11:18:08 +00:00
def check_grant_type(self, grant_type):
return grant_type in self.oauthGrantType
2020-08-14 13:26:14 +00:00
@property
def client_info(self):
return dict(
client_id=self.client_id,
client_secret=self.client_secret,
client_id_issued_at=self.client_id_issued_at,
client_secret_expires_at=self.client_secret_expires_at,
)
2020-08-14 11:18:08 +00:00
class AuthorizationCode(LDAPObject, AuthorizationCodeMixin):
2020-09-24 13:20:36 +00:00
object_class = ["oauthAuthorizationCode"]
2020-09-03 15:19:41 +00:00
base = "ou=authorizations,ou=oauth"
2020-08-14 13:26:14 +00:00
id = "oauthCode"
2020-08-14 11:18:08 +00:00
2020-08-26 14:27:08 +00:00
@property
def issue_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthIssueDate
2020-08-26 14:27:08 +00:00
2020-08-14 11:18:08 +00:00
def get_redirect_uri(self):
2020-08-17 15:49:49 +00:00
return self.oauthRedirectURI
2020-08-14 11:18:08 +00:00
def get_scope(self):
2020-08-17 16:02:38 +00:00
return self.oauthScope
2020-08-14 11:18:08 +00:00
2020-08-17 16:02:38 +00:00
def get_nonce(self):
return self.oauthNonce
2020-08-14 13:26:14 +00:00
2020-08-17 16:49:05 +00:00
def is_expired(self):
return (
2021-12-08 14:53:20 +00:00
self.oauthAuthorizationDate
2020-08-17 16:49:05 +00:00
+ datetime.timedelta(seconds=int(self.oauthAuthorizationLifetime))
< datetime.datetime.now()
)
2020-08-14 13:26:14 +00:00
2020-08-17 16:02:38 +00:00
def get_auth_time(self):
2021-12-08 14:53:20 +00:00
return int(
(
self.oauthAuthorizationDate - datetime.datetime(1970, 1, 1)
).total_seconds()
2020-08-17 16:49:05 +00:00
)
2020-08-17 16:02:38 +00:00
2020-08-14 11:18:08 +00:00
class Token(LDAPObject, TokenMixin):
2020-09-24 13:20:36 +00:00
object_class = ["oauthToken"]
2020-09-03 15:19:41 +00:00
base = "ou=tokens,ou=oauth"
2020-08-16 17:39:14 +00:00
id = "oauthAccessToken"
2020-08-14 11:18:08 +00:00
2020-08-26 14:27:08 +00:00
@property
def issue_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthIssueDate
2020-08-26 14:27:08 +00:00
2020-08-27 08:50:50 +00:00
@property
def expire_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthIssueDate + datetime.timedelta(
seconds=int(self.oauthTokenLifetime)
)
2020-08-27 08:50:50 +00:00
2020-08-24 13:38:11 +00:00
@property
def revoked(self):
2020-09-17 09:10:12 +00:00
return bool(self.oauthRevokationDate)
2020-08-24 13:38:11 +00:00
2020-08-14 11:18:08 +00:00
def get_client_id(self):
return Client.get(self.oauthClient).oauthClientID
2020-08-14 11:18:08 +00:00
def get_scope(self):
2020-08-16 17:39:14 +00:00
return " ".join(self.oauthScope)
2020-08-14 11:18:08 +00:00
def get_expires_in(self):
2020-08-16 18:16:57 +00:00
return int(self.oauthTokenLifetime)
2020-08-14 11:18:08 +00:00
2020-08-24 12:44:32 +00:00
def get_issued_at(self):
2021-12-08 14:53:20 +00:00
return int(
(self.oauthIssueDate - datetime.datetime(1970, 1, 1)).total_seconds()
)
2020-08-24 12:44:32 +00:00
2020-08-14 11:18:08 +00:00
def get_expires_at(self):
2021-12-08 14:53:20 +00:00
issue_timestamp = (
self.oauthIssueDate - datetime.datetime(1970, 1, 1)
).total_seconds()
2020-08-26 09:03:26 +00:00
return int(issue_timestamp) + int(self.oauthTokenLifetime)
2020-08-14 13:26:14 +00:00
def is_refresh_token_active(self):
2020-09-17 09:10:12 +00:00
if self.oauthRevokationDate:
2020-08-24 13:38:11 +00:00
return False
2020-08-27 08:50:50 +00:00
return self.expire_date >= datetime.datetime.now()
2020-09-17 08:00:39 +00:00
def is_expired(self):
return (
2021-12-08 14:53:20 +00:00
self.oauthIssueDate
+ datetime.timedelta(seconds=int(self.oauthTokenLifetime))
< datetime.datetime.now()
)
2020-09-17 08:00:39 +00:00
class Consent(LDAPObject):
2020-09-24 13:20:36 +00:00
object_class = ["oauthConsent"]
2020-09-17 08:00:39 +00:00
base = "ou=consents,ou=oauth"
id = "cn"
def __init__(self, *args, **kwargs):
if "cn" not in kwargs:
kwargs["cn"] = str(uuid.uuid4())
super().__init__(*args, **kwargs)
2020-09-17 10:01:21 +00:00
@property
def issue_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthIssueDate
2020-09-17 10:01:21 +00:00
@property
def revokation_date(self):
2021-12-08 14:53:20 +00:00
return self.oauthRevokationDate
2020-09-17 10:01:21 +00:00
def revoke(self):
2021-12-08 14:53:20 +00:00
self.oauthRevokationDate = datetime.datetime.now()
2020-09-17 10:01:21 +00:00
self.save()
tokens = Token.filter(
oauthClient=self.oauthClient,
oauthSubject=self.oauthSubject,
2020-09-17 10:01:21 +00:00
)
for t in tokens:
if t.revoked or any(
scope not in t.oauthScope[0] for scope in self.oauthScope
):
continue
t.oauthRevokationDate = self.oauthRevokationDate
t.save()