pycrossauth 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crossauth_backend/__init__.py +59 -0
- crossauth_backend/auth.py +132 -0
- crossauth_backend/common/__init__.py +2 -0
- crossauth_backend/common/error.py +498 -0
- crossauth_backend/common/interfaces.py +287 -0
- crossauth_backend/common/jwt.py +41 -0
- crossauth_backend/common/logger.py +202 -0
- crossauth_backend/cookieauth.py +575 -0
- crossauth_backend/crypto.py +457 -0
- crossauth_backend/oauth/__init__.py +2 -0
- crossauth_backend/oauth/client.py +1063 -0
- crossauth_backend/oauth/clientmanager.py +157 -0
- crossauth_backend/oauth/resserver.py +34 -0
- crossauth_backend/oauth/tokenconsumer.py +412 -0
- crossauth_backend/oauth/wellknown.py +108 -0
- crossauth_backend/session.py +450 -0
- crossauth_backend/storage.py +626 -0
- crossauth_backend/storageimpl/__init__.py +2 -0
- crossauth_backend/storageimpl/inmemorystorage.py +132 -0
- crossauth_backend/storageimpl/sqlalchemystorage.py +294 -0
- crossauth_backend/utils.py +150 -0
- crossauth_fastapi/__init__.py +23 -0
- crossauth_fastapi/fastapioauthclient.py +2185 -0
- crossauth_fastapi/fastapiresserver.py +300 -0
- crossauth_fastapi/fastapiserver.py +437 -0
- crossauth_fastapi/fastapiserverbase.py +62 -0
- crossauth_fastapi/fastapisession.py +654 -0
- crossauth_fastapi/fastapisessionadapter.py +94 -0
- pycrossauth-0.0.2.dist-info/LICENSE +203 -0
- pycrossauth-0.0.2.dist-info/METADATA +257 -0
- pycrossauth-0.0.2.dist-info/NOTICE +5 -0
- pycrossauth-0.0.2.dist-info/RECORD +34 -0
- pycrossauth-0.0.2.dist-info/WHEEL +5 -0
- pycrossauth-0.0.2.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Copyright (c) 2024 Matthew Baker. All rights reserved. Licenced under the Apache Licence 2.0. See LICENSE file
|
|
2
|
+
from jwcrypto.jwk import JWK
|
|
3
|
+
from typing import Literal, TypedDict, NotRequired, Required
|
|
4
|
+
|
|
5
|
+
from crossauth_backend.common.interfaces import User
|
|
6
|
+
|
|
7
|
+
type TokenEndpointAuthMethod = Literal["client_secret_post", "client_secret_basic", "client_secret_jwt", "private_key_jwt"]
|
|
8
|
+
type ResponseMode = Literal["query", "fragment"]
|
|
9
|
+
type GrantType = Literal["authorization_code", "implicit", "client_credentials", "password", "refresh_token", "http://auth0.com/oauth/grant-type/mfa-otp", "http://auth0.com/oauth/grant-type/mfa-oob", "urn:ietf:params:oauth:grant-type:device_code"]
|
|
10
|
+
type SubjectType = Literal["pairwise", "public"]
|
|
11
|
+
type ClaimType = Literal["normal", "aggregated", "distributed"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OpenIdConfiguration(TypedDict):
|
|
15
|
+
"""This class encapsulate the data returned by the `oidc-configuration`
|
|
16
|
+
well-known endpoint. For further details, see the OpenID Connect
|
|
17
|
+
specification.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
issuer : str
|
|
21
|
+
authorization_endpoint: str
|
|
22
|
+
token_endpoint: str
|
|
23
|
+
userinfo_endpoint : NotRequired[str]
|
|
24
|
+
jwks_uri : str
|
|
25
|
+
registration_endpoint : NotRequired[str]
|
|
26
|
+
scopes_supported : NotRequired[list[str]]
|
|
27
|
+
response_types_supported: list[str]
|
|
28
|
+
response_modes_supported: list[ResponseMode]
|
|
29
|
+
grant_types_supported : list[GrantType]
|
|
30
|
+
check_session_iframe : NotRequired[str]
|
|
31
|
+
end_session_endpoint : NotRequired[str]
|
|
32
|
+
acr_values_supported: NotRequired[list[str]]
|
|
33
|
+
subject_types_supported: list[SubjectType]
|
|
34
|
+
id_token_signing_alg_values_supported: list[str]
|
|
35
|
+
id_token_encryption_alg_values_supported : NotRequired[list[str]]
|
|
36
|
+
id_token_encryption_enc_values_supported : NotRequired[list[str]]
|
|
37
|
+
userinfo_signing_alg_values_supported : NotRequired[list[str]]
|
|
38
|
+
userinfo_encryption_alg_values_supported : NotRequired[list[str]]
|
|
39
|
+
userinfo_encryption_enc_values_supported : NotRequired[list[str]]
|
|
40
|
+
request_object_signing_alg_values_supported : NotRequired[list[str]]
|
|
41
|
+
request_object_encryption_alg_values_supported : NotRequired[list[str]]
|
|
42
|
+
request_object_encryption_enc_values_supported : NotRequired[list[str]]
|
|
43
|
+
token_endpoint_auth_methods_supported: NotRequired[list[TokenEndpointAuthMethod]]
|
|
44
|
+
token_endpoint_auth_signing_alg_values_supported : NotRequired[list[str]]
|
|
45
|
+
display_values_supported : NotRequired[list[str]]
|
|
46
|
+
claim_types_supported : NotRequired[list[ClaimType]]
|
|
47
|
+
claims_supported : NotRequired[list[str]]
|
|
48
|
+
service_documentation : NotRequired[str]
|
|
49
|
+
claims_locales_supported : NotRequired[list[str]]
|
|
50
|
+
ui_locales_supported : NotRequired[list[str]]
|
|
51
|
+
claims_parameter_supported : NotRequired[bool]
|
|
52
|
+
request_parameter_supported : NotRequired[bool]
|
|
53
|
+
request_uri_parameter_supported : NotRequired[bool]
|
|
54
|
+
require_request_uri_registration : NotRequired[bool]
|
|
55
|
+
op_policy_uri : NotRequired[str]
|
|
56
|
+
op_tos_uri : NotRequired[str]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Jwks(TypedDict):
|
|
60
|
+
keys: list[JWK]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
DEFAULT_OIDCCONFIG : OpenIdConfiguration = {
|
|
64
|
+
'issuer': "",
|
|
65
|
+
'authorization_endpoint': "",
|
|
66
|
+
'token_endpoint': "",
|
|
67
|
+
'jwks_uri' : "",
|
|
68
|
+
'response_types_supported': [],
|
|
69
|
+
'subject_types_supported' : [],
|
|
70
|
+
'response_modes_supported': ["query", "fragment"],
|
|
71
|
+
'grant_types_supported' : ["authorization_code", "implicit"],
|
|
72
|
+
'id_token_signing_alg_values_supported': [],
|
|
73
|
+
'claim_types_supported' : ["normal"],
|
|
74
|
+
'claims_parameter_supported' : False,
|
|
75
|
+
'request_parameter_supported' : False,
|
|
76
|
+
'request_uri_parameter_supported' : True,
|
|
77
|
+
'require_request_uri_registration' : False,
|
|
78
|
+
}
|
|
79
|
+
"""
|
|
80
|
+
This is the detault configuration for
|
|
81
|
+
:class: OAuthAuthorizationServer.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
class TokenBodyType(TypedDict, total=False):
|
|
85
|
+
grant_type : Required[str]
|
|
86
|
+
client_id : Required[str]
|
|
87
|
+
scope : str
|
|
88
|
+
code : str
|
|
89
|
+
client_secret : str
|
|
90
|
+
code_verifier : str
|
|
91
|
+
refresh_token : str
|
|
92
|
+
username : str
|
|
93
|
+
password : str
|
|
94
|
+
mfa_token : str
|
|
95
|
+
oobCode : str
|
|
96
|
+
binding_code: str
|
|
97
|
+
otp : str
|
|
98
|
+
device_code : str
|
|
99
|
+
|
|
100
|
+
class AuthorizeQueryType(TypedDict, total=False):
|
|
101
|
+
response_type : Required[str]
|
|
102
|
+
client_id : str
|
|
103
|
+
redirect_uri : str
|
|
104
|
+
scope : str
|
|
105
|
+
state : str
|
|
106
|
+
code_challenge : str
|
|
107
|
+
code_challenge_method : str
|
|
108
|
+
user : User
|
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
from crossauth_backend.storage import UserStorage, KeyStorage, KeyDataEntry
|
|
2
|
+
from crossauth_backend.cookieauth import DoubleSubmitCsrfTokenOptions, DoubleSubmitCsrfToken
|
|
3
|
+
from crossauth_backend.cookieauth import SessionCookieOptions, SessionCookie, Cookie
|
|
4
|
+
from crossauth_backend.crypto import Crypto
|
|
5
|
+
from crossauth_backend.utils import set_parameter, ParamType
|
|
6
|
+
from crossauth_backend.common.error import CrossauthError, ErrorCode
|
|
7
|
+
from crossauth_backend.common.logger import CrossauthLogger, j
|
|
8
|
+
from crossauth_backend.common.interfaces import User, UserSecrets
|
|
9
|
+
from crossauth_backend.auth import Authenticator, AuthenticationParameters
|
|
10
|
+
from typing import TypedDict, List, Mapping, NamedTuple, Any, Dict
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
import json
|
|
13
|
+
|
|
14
|
+
class SessionManagerOptions(TypedDict, total=False):
|
|
15
|
+
"""
|
|
16
|
+
Options for SessionManager
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
user_storage: UserStorage
|
|
20
|
+
"""
|
|
21
|
+
If user login is enabled, you must provide the object where users
|
|
22
|
+
are stored.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
double_submit_cookie_options : DoubleSubmitCsrfTokenOptions
|
|
26
|
+
"""Options for csrf cookie manager"""
|
|
27
|
+
|
|
28
|
+
session_cookie_options : SessionCookieOptions
|
|
29
|
+
"""options for session cookie manager """
|
|
30
|
+
|
|
31
|
+
enable_email_verification : bool
|
|
32
|
+
"""
|
|
33
|
+
If true, users will have to verify their email address before account is created or when changing their email address.
|
|
34
|
+
See class description for details. Default True
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
enable_password_reset : bool
|
|
38
|
+
"""
|
|
39
|
+
If true, allow password reset by email token.
|
|
40
|
+
See class description for details. Default True
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
secret : str
|
|
44
|
+
"""Server secret. Needed for emailing tokens and for csrf tokens"""
|
|
45
|
+
|
|
46
|
+
email_token_storage : KeyStorage
|
|
47
|
+
"""
|
|
48
|
+
Store for password reset and email verification tokens. If not passed, the same store as
|
|
49
|
+
for sessions is used.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
site_url : str
|
|
53
|
+
"""
|
|
54
|
+
Base URL for the site.
|
|
55
|
+
|
|
56
|
+
This is used when constructing URLs, eg for sending password reset
|
|
57
|
+
tokens.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
allowed_factor2 : List[str]
|
|
61
|
+
"""
|
|
62
|
+
Set of 2FA factor names a user is allowed to set.
|
|
63
|
+
|
|
64
|
+
The name corresponds to the key you give when adding authenticators.
|
|
65
|
+
See `authenticators` in SessionManager.constructor.
|
|
66
|
+
"""
|
|
67
|
+
class AnonymousSession(NamedTuple):
|
|
68
|
+
session_cookie: Cookie
|
|
69
|
+
csrf_cookie: Cookie
|
|
70
|
+
csrf_form_or_header_value: str
|
|
71
|
+
|
|
72
|
+
class Csrf(NamedTuple):
|
|
73
|
+
csrf_cookie: Cookie
|
|
74
|
+
csrf_form_or_header_value: str
|
|
75
|
+
|
|
76
|
+
class SessionManager:
|
|
77
|
+
"""
|
|
78
|
+
Class for managing sessions.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def user_storage(self):
|
|
83
|
+
return self._user_storage
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def key_storage(self):
|
|
87
|
+
return self._key_storage
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def email_token_storage(self):
|
|
91
|
+
return self._email_token_storage
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def csrf_tokens(self):
|
|
95
|
+
return self._csrf_tokens
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def session(self):
|
|
99
|
+
return self._session
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def authenticators(self):
|
|
103
|
+
return self._authenticators
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def allowed_factor2(self):
|
|
107
|
+
return self._allowed_factor2
|
|
108
|
+
|
|
109
|
+
def __init__(self, key_storage : KeyStorage, authenticators : Mapping[str, Authenticator] , options : SessionManagerOptions = {}):
|
|
110
|
+
"""
|
|
111
|
+
Constructor
|
|
112
|
+
:param crossauth_backend.KeyStorage key_storage: the :class:`KeyStorage` instance to use, eg :class:`PrismaKeyStorage`.
|
|
113
|
+
:param Mapping[str, Authenticator] authenticators: authenticators used to validate users, eg :class:`LocalPasswordAuthenticatorOptions`.
|
|
114
|
+
:param SessionManagerOptions options: optional parameters for authentication. See :class:`SessionManagerOptions`.
|
|
115
|
+
|
|
116
|
+
"""
|
|
117
|
+
self._user_storage = options.get('userStorage', None)
|
|
118
|
+
self._key_storage = key_storage
|
|
119
|
+
self._email_token_storage : KeyStorage | None = None
|
|
120
|
+
self._authenticators = authenticators
|
|
121
|
+
for authentication_name in self._authenticators:
|
|
122
|
+
self._authenticators[authentication_name].factor_name = authentication_name
|
|
123
|
+
|
|
124
|
+
soptions : SessionCookieOptions = {}
|
|
125
|
+
if "secret" in options:
|
|
126
|
+
soptions["secret"] = options["secret"]
|
|
127
|
+
if ("session_cookie_options" in options):
|
|
128
|
+
soptions = {**soptions, **options["session_cookie_options"]}
|
|
129
|
+
self._session = SessionCookie(self._key_storage, soptions)
|
|
130
|
+
coptions : DoubleSubmitCsrfTokenOptions = {}
|
|
131
|
+
if "secret" in options:
|
|
132
|
+
coptions["secret"] = options["secret"]
|
|
133
|
+
if ("double_submit_cookie_options" in options):
|
|
134
|
+
coptions = {**coptions, **options["double_submit_cookie_options"]}
|
|
135
|
+
self._csrf_tokens = DoubleSubmitCsrfToken(coptions)
|
|
136
|
+
|
|
137
|
+
self._allowed_factor2 : List[str] = []
|
|
138
|
+
self.__enable_email_verification : bool = False
|
|
139
|
+
self.__enable_password_reset : bool = False
|
|
140
|
+
self.__token_emailer = None
|
|
141
|
+
|
|
142
|
+
set_parameter("allowed_factor2", ParamType.JsonArray, self, options, "ALLOWED_FACTOR2", protected=True)
|
|
143
|
+
set_parameter("enable_email_verification", ParamType.Boolean, self, options, "ENABLE_EMAIL_VERIFICATION")
|
|
144
|
+
set_parameter("enable_password_reset", ParamType.Boolean, self, options, "ENABLE_PASSWORD_RESET")
|
|
145
|
+
self._email_token_storage = self._key_storage
|
|
146
|
+
if self._user_storage and (self.__enable_email_verification or self.__enable_password_reset):
|
|
147
|
+
raise CrossauthError(ErrorCode.NotImplemented, "email verification is not supported in this version")
|
|
148
|
+
|
|
149
|
+
async def login(self, username : str, params : AuthenticationParameters, extra_fields : Mapping[str,Any]|None=None, persist : bool=False, user : User|None=None, bypass_2fa : bool=False):
|
|
150
|
+
""" Not implemented """
|
|
151
|
+
raise CrossauthError(ErrorCode.NotImplemented, "login not implemented in this version")
|
|
152
|
+
|
|
153
|
+
async def create_anonymous_session(self, extra_fields: Mapping[str,Any]|None=None) -> AnonymousSession:
|
|
154
|
+
if extra_fields is None:
|
|
155
|
+
extra_fields = {}
|
|
156
|
+
key = await self._session.create_session_key(None, extra_fields)
|
|
157
|
+
session_cookie = self._session.make_cookie(key, False)
|
|
158
|
+
csrf_data = await self.create_csrf_token()
|
|
159
|
+
return AnonymousSession(session_cookie, csrf_data.csrf_cookie, csrf_data.csrf_form_or_header_value)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
async def logout(self, session_id : str):
|
|
163
|
+
""" Not implemented """
|
|
164
|
+
key = await self._session.get_session_key(session_id)
|
|
165
|
+
return await self._key_storage.delete_key(SessionCookie.hash_session_id(key["value"]))
|
|
166
|
+
|
|
167
|
+
async def logout_from_all(self, userid : str|int, except_id : str|None=None):
|
|
168
|
+
""" Not implemented """
|
|
169
|
+
return await self._session.delete_all_for_user(userid, except_id)
|
|
170
|
+
|
|
171
|
+
async def user_for_session_id(self, session_id : str):
|
|
172
|
+
""" Not implemented """
|
|
173
|
+
return await self._session.get_user_for_session_id(session_id)
|
|
174
|
+
|
|
175
|
+
async def data_string_for_session_id(self, session_id : str) -> str|None:
|
|
176
|
+
"""
|
|
177
|
+
Returns the data object for a session key, or undefined, as a JSON string
|
|
178
|
+
(which is how it is stored in the session table)
|
|
179
|
+
|
|
180
|
+
If the user is undefined, or the key has expired, returns undefined.
|
|
181
|
+
|
|
182
|
+
:param str session_id: the session id to look up in session storage
|
|
183
|
+
|
|
184
|
+
:return: a string from the data field
|
|
185
|
+
|
|
186
|
+
:raise :class:`crossauth_backend.CrossauthError`: with
|
|
187
|
+
:class:`ErrorCode` of `Connection`, `InvalidSessionId`
|
|
188
|
+
`UserNotExist` or `Expired`.
|
|
189
|
+
"""
|
|
190
|
+
try:
|
|
191
|
+
key_data = await self._session.get_user_for_session_id(session_id)
|
|
192
|
+
return key_data.key["data"] if "data" in key_data.key else None
|
|
193
|
+
except Exception as e:
|
|
194
|
+
ce = CrossauthError.as_crossauth_error(e)
|
|
195
|
+
if ce.code == ErrorCode.Expired:
|
|
196
|
+
return None
|
|
197
|
+
raise ce
|
|
198
|
+
|
|
199
|
+
async def data_for_session_id(self, session_id : str) -> Dict[str,Any]|None:
|
|
200
|
+
"""
|
|
201
|
+
Returns the data object for a session id, or undefined, as an object.
|
|
202
|
+
|
|
203
|
+
If the user is undefined, or the key has expired, returns undefined.
|
|
204
|
+
|
|
205
|
+
:param str session_id: the session key to look up in session storage
|
|
206
|
+
|
|
207
|
+
:return: a string from the data field
|
|
208
|
+
|
|
209
|
+
:raise :class:`crossauth_backend.CrossauthError`: with
|
|
210
|
+
:class:`ErrorCode` of `Connection`, `InvalidSessionId`
|
|
211
|
+
`UserNotExist` or `Expired`.
|
|
212
|
+
"""
|
|
213
|
+
str_data = await self.data_string_for_session_id(session_id)
|
|
214
|
+
if not str_data:
|
|
215
|
+
return None
|
|
216
|
+
return json.loads(str_data)
|
|
217
|
+
|
|
218
|
+
async def create_csrf_token(self) -> Csrf:
|
|
219
|
+
"""
|
|
220
|
+
Creates and returns a signed CSRF token based on the session ID
|
|
221
|
+
|
|
222
|
+
:return: a CSRF cookie and value to put in the form or CSRF header
|
|
223
|
+
"""
|
|
224
|
+
csrf_token = self._csrf_tokens.create_csrf_token()
|
|
225
|
+
csrf_form_or_header_value = self._csrf_tokens.make_csrf_form_or_header_token(csrf_token)
|
|
226
|
+
csrf_cookie = self._csrf_tokens.make_csrf_cookie(csrf_token)
|
|
227
|
+
return Csrf(csrf_cookie,csrf_form_or_header_value)
|
|
228
|
+
|
|
229
|
+
async def create_csrf_form_or_header_value(self, csrf_cookie_value: str):
|
|
230
|
+
"""
|
|
231
|
+
Validates the signature on the CSRF cookie value and returns a
|
|
232
|
+
value that can be put in the form or CSRF header value.
|
|
233
|
+
|
|
234
|
+
:param str csrf_cookie_value: the value from the CSRF cookie
|
|
235
|
+
|
|
236
|
+
:return: the value to put in the form or CSRF header
|
|
237
|
+
"""
|
|
238
|
+
csrf_token = self._csrf_tokens.unsign_cookie(csrf_cookie_value)
|
|
239
|
+
return self._csrf_tokens.make_csrf_form_or_header_token(csrf_token)
|
|
240
|
+
|
|
241
|
+
def get_session_id(self, session_cookie_value: str):
|
|
242
|
+
"""
|
|
243
|
+
Returns the session ID from the signed session cookie value
|
|
244
|
+
|
|
245
|
+
:param str session_cookie_value: value from the session ID cookie
|
|
246
|
+
|
|
247
|
+
:return: the usigned cookie value.
|
|
248
|
+
|
|
249
|
+
:raises :class:`crossauth_backend.CrossauthError` with `InvalidKey`
|
|
250
|
+
if the signature is invalid.
|
|
251
|
+
"""
|
|
252
|
+
return self._session.unsign_cookie(session_cookie_value)
|
|
253
|
+
|
|
254
|
+
def validate_double_submit_csrf_token(self, csrf_cookie_value : str, csrf_form_or_header_value: str):
|
|
255
|
+
"""
|
|
256
|
+
Throws :class:`crossauth_backend.CrossauthError` with
|
|
257
|
+
`InvalidKey` if the passed CSRF token is not valid for the given
|
|
258
|
+
session ID. Otherwise returns without error
|
|
259
|
+
|
|
260
|
+
:param strcsrf_cookie_value: the CSRF cookie value
|
|
261
|
+
:param str csrf_form_or_header_value: the value from the form field or
|
|
262
|
+
CSRF header
|
|
263
|
+
"""
|
|
264
|
+
if not csrf_cookie_value or not csrf_form_or_header_value:
|
|
265
|
+
raise CrossauthError(ErrorCode.InvalidCsrf, "CSRF missing from either cookie or form/header value")
|
|
266
|
+
self._csrf_tokens.validate_double_submit_csrf_token(csrf_cookie_value, csrf_form_or_header_value)
|
|
267
|
+
|
|
268
|
+
def validate_csrf_cookie(self, csrf_cookie_value : str):
|
|
269
|
+
"""
|
|
270
|
+
Throws :class:`crossauth_backend.CrossauthError` with `InvalidKey` if
|
|
271
|
+
the passed CSRF cookie value is not valid (ie invalid signature)
|
|
272
|
+
:param str csrf_cookie_value: the CSRF cookie value
|
|
273
|
+
|
|
274
|
+
"""
|
|
275
|
+
self._csrf_tokens.validate_csrf_cookie(csrf_cookie_value)
|
|
276
|
+
|
|
277
|
+
async def update_session_activity(self, session_id : str):
|
|
278
|
+
"""
|
|
279
|
+
If session_idle_timeout is set, update the last activcity time in key
|
|
280
|
+
storage to current time.
|
|
281
|
+
|
|
282
|
+
:param str session_id: the session Id to update.
|
|
283
|
+
|
|
284
|
+
"""
|
|
285
|
+
key_data = await self._session.get_session_key(session_id)
|
|
286
|
+
if self._session.idle_timeout > 0:
|
|
287
|
+
await self._session.update_session_key({
|
|
288
|
+
'value': key_data['value'],
|
|
289
|
+
'lastactive': datetime.now(),
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
async def update_session_data(self, session_id: str, name: str, value: Mapping[str, Any]) -> None:
|
|
293
|
+
"""
|
|
294
|
+
Update a field in the session data.
|
|
295
|
+
|
|
296
|
+
The `data` field in the session entry is assumed to be a JSON string.
|
|
297
|
+
The field with the given name is updated or set if not already set.
|
|
298
|
+
:param str session_id: the session Id to update.
|
|
299
|
+
:param str name: of the field.
|
|
300
|
+
:param Mapping[str, Any] value: new value to store
|
|
301
|
+
|
|
302
|
+
"""
|
|
303
|
+
hashed_session_key = self._session.hash_session_id(session_id)
|
|
304
|
+
CrossauthLogger.logger().debug(j({"msg": f"Updating session data value{name}", "hashedSessionCookie": Crypto.hash(session_id)}))
|
|
305
|
+
await self._key_storage.update_data(hashed_session_key, name, value)
|
|
306
|
+
|
|
307
|
+
async def update_many_session_data(self, session_id: str, data_array: List[KeyDataEntry]) -> None:
|
|
308
|
+
"""
|
|
309
|
+
Update field sin the session data.
|
|
310
|
+
|
|
311
|
+
The `data` field in the session entry is assumed to be a JSON string.
|
|
312
|
+
The field with the given name is updated or set if not already set.
|
|
313
|
+
:param str session_id: the session Id to update.
|
|
314
|
+
:param List[crossauth_backend.KeyDataEntry] data_array: names and values.
|
|
315
|
+
|
|
316
|
+
"""
|
|
317
|
+
hashed_session_key = self._session.hash_session_id(session_id)
|
|
318
|
+
CrossauthLogger.logger().debug(j({"msg": f"Updating session data", "hashedSessionCookie": Crypto.hash(session_id)}))
|
|
319
|
+
await self._key_storage.update_many_data(hashed_session_key, data_array)
|
|
320
|
+
|
|
321
|
+
async def delete_session_data(self, session_id: str, name: str) -> None:
|
|
322
|
+
"""
|
|
323
|
+
Deletes a field from the session data.
|
|
324
|
+
|
|
325
|
+
The `data` field in the session entry is assumed to be a JSON string.
|
|
326
|
+
The field with the given name is updated or set if not already set.
|
|
327
|
+
:param str session_id; the session Id to update.
|
|
328
|
+
|
|
329
|
+
"""
|
|
330
|
+
hashed_session_key = self._session.hash_session_id(session_id)
|
|
331
|
+
CrossauthLogger.logger().debug(j({"msg": f"Updating session data value{name}", "hashedSessionCookie": Crypto.hash(session_id)}))
|
|
332
|
+
await self._key_storage.delete_data(hashed_session_key, name)
|
|
333
|
+
|
|
334
|
+
async def delete_session(self, session_id: str) -> None:
|
|
335
|
+
"""
|
|
336
|
+
Deletes the given session ID from the key storage (not the cookie)
|
|
337
|
+
|
|
338
|
+
:param str session_id: the session Id to delete
|
|
339
|
+
|
|
340
|
+
"""
|
|
341
|
+
return await self._key_storage.delete_key(self._session.hash_session_id(session_id))
|
|
342
|
+
|
|
343
|
+
async def create_user(self, user: User, params: UserSecrets, repeat_params: UserSecrets|None = None, skip_email_verification: bool = False, empty_password: bool = False) -> User:
|
|
344
|
+
""" Not implemented """
|
|
345
|
+
if not self._user_storage:
|
|
346
|
+
raise Exception("Cannot call createUser if no user storage provided")
|
|
347
|
+
|
|
348
|
+
if user['factor1'] not in self._authenticators:
|
|
349
|
+
raise Exception("Authenticator cannot create users")
|
|
350
|
+
|
|
351
|
+
if self._authenticators[user['factor1']].skip_email_verification_on_signup():
|
|
352
|
+
skip_email_verification = True
|
|
353
|
+
|
|
354
|
+
secrets = await self._authenticators[user['factor1']].create_persistent_secrets(user['username'], params, repeat_params) if not empty_password else None
|
|
355
|
+
new_user = await self._user_storage.create_user(user, secrets) if not empty_password else await self._user_storage.create_user(user)
|
|
356
|
+
|
|
357
|
+
if not skip_email_verification and self.__enable_email_verification and self.__token_emailer:
|
|
358
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Email verification is not supported in this version")
|
|
359
|
+
#await self.token_emailer.send_email_verification_token(new_user['id'], None)
|
|
360
|
+
|
|
361
|
+
return new_user
|
|
362
|
+
|
|
363
|
+
async def delete_user_by_username(self, username: str) -> None:
|
|
364
|
+
""" Not implemented """
|
|
365
|
+
if not self._user_storage:
|
|
366
|
+
raise Exception("Cannot call deleteUser if no user storage provided")
|
|
367
|
+
self._user_storage.delete_user_by_username(username)
|
|
368
|
+
|
|
369
|
+
async def initiate_two_factor_signup(self, user: User, params: UserSecrets, session_id: str, repeat_params: UserSecrets|None):
|
|
370
|
+
""" Not implemented """
|
|
371
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Factor2 not implemented in this version")
|
|
372
|
+
|
|
373
|
+
async def initiate_two_factor_setup(self, user: User, new_factor2: str|None, session_id: str) -> Mapping[str, Any]:
|
|
374
|
+
""" Not implemented """
|
|
375
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Factor2 not implemented in this version")
|
|
376
|
+
|
|
377
|
+
async def repeat_two_factor_signup(self, session_id: str) -> Mapping[str, Any]:
|
|
378
|
+
""" Not implemented """
|
|
379
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
380
|
+
|
|
381
|
+
async def complete_two_factor_setup(self, params: AuthenticationParameters, session_id: str) -> User:
|
|
382
|
+
""" Not implemented """
|
|
383
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
384
|
+
|
|
385
|
+
async def initiate_two_factor_login(self, user: User) -> Mapping[str, Any]:
|
|
386
|
+
""" Not implemented """
|
|
387
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
388
|
+
|
|
389
|
+
async def initiate_two_factor_page_visit(self, user: User, session_id: str, request_body: Mapping[str, Any], url: str|None=None, content_type: str|None = None):
|
|
390
|
+
""" Not implemented """
|
|
391
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
392
|
+
|
|
393
|
+
async def complete_two_factor_page_visit(self, params : AuthenticationParameters, session_id : str):
|
|
394
|
+
""" Not implemented """
|
|
395
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
396
|
+
|
|
397
|
+
async def cancel_two_factor_page_visit(self, session_id : str):
|
|
398
|
+
""" Not implemented """
|
|
399
|
+
raise CrossauthError(ErrorCode.NotImplemented, "2FA is not implemented in this version")
|
|
400
|
+
|
|
401
|
+
async def complete_two_factor_login(self, params : AuthenticationParameters, session_id : str, extra_fields:Mapping[str, Any]|None=None, persist:bool=False):
|
|
402
|
+
""" Not implemented """
|
|
403
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Login is not implemented in this version")
|
|
404
|
+
|
|
405
|
+
async def request_password_reset(self, email : str):
|
|
406
|
+
""" Not implemented """
|
|
407
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Password reset is not implemented in this version")
|
|
408
|
+
|
|
409
|
+
async def apply_email_verification_token(self, token : str):
|
|
410
|
+
""" Not implemented """
|
|
411
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Email verification is not implemented in this version")
|
|
412
|
+
|
|
413
|
+
async def user_for_password_reset_token(self, token : str):
|
|
414
|
+
""" Not implemented """
|
|
415
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Password reset is not implemented in this version")
|
|
416
|
+
|
|
417
|
+
async def update_user(self, current_user : User, new_user : User, skip_email_verification:bool=False, as_admin:bool=False):
|
|
418
|
+
""" Not implemented """
|
|
419
|
+
raise CrossauthError(ErrorCode.NotImplemented, "User update is not implemented in this version")
|
|
420
|
+
|
|
421
|
+
async def reset_secret(self, token : str, factor_number:int, params:AuthenticationParameters, repeat_params:AuthenticationParameters|None=None):
|
|
422
|
+
""" Not implemented """
|
|
423
|
+
raise CrossauthError(ErrorCode.NotImplemented, "Password reset is not implemented in this version")
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@property
|
|
427
|
+
def session_cookie_name(self):
|
|
428
|
+
""" Returns the name used for session ID cookies. """
|
|
429
|
+
return self._session.cookie_name
|
|
430
|
+
|
|
431
|
+
@property
|
|
432
|
+
def session_cookie_path(self):
|
|
433
|
+
""" Returns the name used for session ID cookies """
|
|
434
|
+
return self._session.path
|
|
435
|
+
|
|
436
|
+
@property
|
|
437
|
+
def csrf_cookie_name(self):
|
|
438
|
+
""" Returns the name used for CSRF token cookies. """
|
|
439
|
+
return self._csrf_tokens.cookie_name
|
|
440
|
+
|
|
441
|
+
@property
|
|
442
|
+
def csrf_cookie_path(self):
|
|
443
|
+
""" Returns the name used for CSRF token cookies. """
|
|
444
|
+
return self._csrf_tokens.path
|
|
445
|
+
|
|
446
|
+
@property
|
|
447
|
+
def csrf_header_name(self):
|
|
448
|
+
""" Returns the name used for CSRF token cookies """
|
|
449
|
+
return self._csrf_tokens.header_name
|
|
450
|
+
|