canaille-globuzma/canaille/models.py

293 lines
8 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 ldap
import uuid
2020-08-14 11:18:08 +00:00
from authlib.common.encoding import json_loads, json_dumps
from authlib.oauth2.rfc6749 import (
ClientMixin,
TokenMixin,
AuthorizationCodeMixin,
2020-08-20 12:30:42 +00:00
util,
2020-08-14 11:18:08 +00:00
)
2020-08-19 14:20:57 +00:00
from flask import current_app, session
from .ldaputils import LDAPObject
2020-08-14 11:18:08 +00:00
class User(LDAPObject):
2020-08-14 11:18:08 +00:00
id = "cn"
2020-08-19 14:20:57 +00:00
admin = False
2020-11-02 11:13:03 +00:00
moderator = False
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:
filter = current_app.config["LDAP"].get("USER_FILTER").format(login=login)
2020-08-19 14:20:57 +00:00
user = super().get(dn, filter, conn)
2020-10-21 15:15:33 +00:00
2020-08-19 14:20:57 +00:00
admin_filter = current_app.config["LDAP"].get("ADMIN_FILTER")
2020-11-02 11:13:03 +00:00
moderator_filter = current_app.config["LDAP"].get("USER_ADMIN_FILTER")
2020-08-19 14:20:57 +00:00
if (
admin_filter
and user
2020-08-26 13:37:15 +00:00
and user.dn
2020-08-19 14:20:57 +00:00
and conn.search_s(user.dn, ldap.SCOPE_SUBTREE, admin_filter)
):
user.admin = True
2020-11-02 11:13:03 +00:00
user.moderator = True
elif (
moderator_filter
and user
and user.dn
and conn.search_s(user.dn, ldap.SCOPE_SUBTREE, moderator_filter)
):
user.moderator = True
2020-08-19 14:20:57 +00:00
return user
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):
session["user_dn"] = self.dn
def logout(self):
try:
del session["user_dn"]
except KeyError:
pass
2020-08-14 11:18:08 +00:00
def check_password(self, password):
conn = ldap.initialize(current_app.config["LDAP"]["URI"])
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"),
)
except ldap.LDAPError:
return False
return True
2020-08-17 15:49:49 +00:00
@property
def name(self):
return self.cn[0]
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):
return datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
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,
)
@property
def client_metadata(self):
if "client_metadata" in self.__dict__:
return self.__dict__["client_metadata"]
if self._client_metadata:
data = json_loads(self._client_metadata)
self.__dict__["client_metadata"] = data
return data
return {}
def set_client_metadata(self, value):
self._client_metadata = json_dumps(value)
@property
def redirect_uris(self):
return self.client_metadata.get("redirect_uris", [])
@property
def token_endpoint_auth_method(self):
return self.client_metadata.get(
"token_endpoint_auth_method", "client_secret_basic"
)
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):
return datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
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 (
datetime.datetime.strptime(self.oauthAuthorizationDate, "%Y%m%d%H%M%SZ")
+ 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):
2020-08-17 16:49:05 +00:00
auth_time = datetime.datetime.strptime(
self.oauthAuthorizationDate, "%Y%m%d%H%M%SZ"
)
2020-08-26 09:03:26 +00:00
return int((auth_time - datetime.datetime(1970, 1, 1)).total_seconds())
2020-08-17 16:02:38 +00:00
2020-08-24 12:44:32 +00:00
@property
def code_challenge(self):
return self.oauthCodeChallenge
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):
return datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
2020-08-27 08:50:50 +00:00
@property
def expire_date(self):
return datetime.datetime.strptime(
self.oauthIssueDate, "%Y%m%d%H%M%SZ"
) + datetime.timedelta(seconds=int(self.oauthTokenLifetime))
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):
issue_date = datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
2020-08-26 09:03:26 +00:00
return int((issue_date - 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):
2020-08-16 18:16:57 +00:00
issue_date = datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
2020-08-14 11:18:08 +00:00
issue_timestamp = (issue_date - 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 (
datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
+ 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):
return datetime.datetime.strptime(self.oauthIssueDate, "%Y%m%d%H%M%SZ")
@property
def revokation_date(self):
return datetime.datetime.strptime(self.oauthRevokationDate, "%Y%m%d%H%M%SZ")
def revoke(self):
self.oauthRevokationDate = datetime.datetime.now().strftime("%Y%m%d%H%M%SZ")
self.save()
tokens = Token.filter(
oauthClient=self.oauthClient,
oauthSubject=self.oauthSubject,
)
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()