sanic-security 1.16.12__py3-none-any.whl → 1.17.1__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.
@@ -1,248 +1,253 @@
1
- import functools
2
- from contextlib import suppress
3
-
4
- from sanic.log import logger
5
- from sanic.request import Request
6
-
7
- from sanic_security.exceptions import (
8
- JWTDecodeError,
9
- NotFoundError,
10
- MaxedOutChallengeError,
11
- DeactivatedError,
12
- )
13
- from sanic_security.models import (
14
- Account,
15
- TwoStepSession,
16
- CaptchaSession,
17
- )
18
- from sanic_security.utils import get_ip
19
-
20
- """
21
- Copyright (c) 2020-present Nicholas Aidan Stewart
22
-
23
- Permission is hereby granted, free of charge, to any person obtaining a copy
24
- of this software and associated documentation files (the "Software"), to deal
25
- in the Software without restriction, including without limitation the rights
26
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27
- copies of the Software, and to permit persons to whom the Software is
28
- furnished to do so, subject to the following conditions:
29
-
30
- The above copyright notice and this permission notice shall be included in all
31
- copies or substantial portions of the Software.
32
-
33
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39
- SOFTWARE.
40
- """
41
-
42
-
43
- async def request_two_step_verification(
44
- request: Request, account: Account = None
45
- ) -> TwoStepSession:
46
- """
47
- Creates a two-step session and deactivates the client's current two-step session if found.
48
-
49
- Args:
50
- request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): email.
51
- account (Account): The account being associated with the new verification session. If None, an account is retrieved via the email in the request form-data or an existing two-step session.
52
-
53
- Raises:
54
- NotFoundError
55
-
56
- Returns:
57
- two_step_session
58
- """
59
- with suppress(NotFoundError, JWTDecodeError):
60
- two_step_session = await TwoStepSession.decode(request)
61
- if two_step_session.active:
62
- await two_step_session.deactivate()
63
- if not account:
64
- account = two_step_session.bearer
65
- if request.form.get("email") or not account:
66
- account = await Account.get_via_email(request.form.get("email"))
67
- two_step_session = await TwoStepSession.new(request, account)
68
- request.ctx.session = two_step_session
69
- return two_step_session
70
-
71
-
72
- async def two_step_verification(request: Request) -> TwoStepSession:
73
- """
74
- Validates a two-step verification attempt.
75
-
76
- Args:
77
- request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): code.
78
-
79
- Raises:
80
- NotFoundError
81
- JWTDecodeError
82
- DeletedError
83
- ExpiredError
84
- DeactivatedError
85
- UnverifiedError
86
- DisabledError
87
- ChallengeError
88
- MaxedOutChallengeError
89
-
90
- Returns:
91
- two_step_session
92
- """
93
- two_step_session = await TwoStepSession.decode(request)
94
- two_step_session.validate()
95
- two_step_session.bearer.validate()
96
- try:
97
- await two_step_session.check_code(request.form.get("code"))
98
- except MaxedOutChallengeError as e:
99
- logger.warning(
100
- f"Client {get_ip(request)} has exceeded maximum two-step session {two_step_session.id} challenge attempts."
101
- )
102
- raise e
103
- logger.info(
104
- f"Client {get_ip(request)} has completed two-step session {two_step_session.id} challenge."
105
- )
106
- return two_step_session
107
-
108
-
109
- def requires_two_step_verification(arg=None):
110
- """
111
- Validates a two-step verification attempt.
112
-
113
- Example:
114
- This method is not called directly and instead used as a decorator:
115
-
116
- @app.post("api/verification/attempt")
117
- @requires_two_step_verification
118
- async def on_verified(request):
119
- response = json("Two-step verification attempt successful!", two_step_session.json())
120
- return response
121
-
122
- Raises:
123
- NotFoundError
124
- JWTDecodeError
125
- DeletedError
126
- ExpiredError
127
- DeactivatedError
128
- UnverifiedError
129
- DisabledError
130
- ChallengeError
131
- MaxedOutChallengeError
132
- """
133
-
134
- def decorator(func):
135
- @functools.wraps(func)
136
- async def wrapper(request, *args, **kwargs):
137
- await two_step_verification(request)
138
- return await func(request, *args, **kwargs)
139
-
140
- return wrapper
141
-
142
- return decorator(arg) if callable(arg) else decorator
143
-
144
-
145
- async def verify_account(request: Request) -> TwoStepSession:
146
- """
147
- Verifies the client's account via two-step session code.
148
-
149
- Args:
150
- request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): code.
151
-
152
- Raises:
153
- NotFoundError
154
- JWTDecodeError
155
- DeletedError
156
- ExpiredError
157
- DeactivatedError
158
- ChallengeError
159
- MaxedOutChallengeError
160
-
161
- Returns:
162
- two_step_session
163
- """
164
- two_step_session = await TwoStepSession.decode(request)
165
- if two_step_session.bearer.verified:
166
- raise DeactivatedError("Account already verified.", 403)
167
- two_step_session.validate()
168
- try:
169
- await two_step_session.check_code(request.form.get("code"))
170
- except MaxedOutChallengeError as e:
171
- logger.warning(
172
- f"Client {get_ip(request)} has exceeded maximum two-step session {two_step_session.id} challenge attempts "
173
- "during account verification."
174
- )
175
- raise e
176
- two_step_session.bearer.verified = True
177
- await two_step_session.bearer.save(update_fields=["verified"])
178
- logger.info(
179
- f"Client {get_ip(request)} has verified account {two_step_session.bearer.id}."
180
- )
181
- return two_step_session
182
-
183
-
184
- async def captcha(request: Request) -> CaptchaSession:
185
- """
186
- Validates a captcha challenge attempt.
187
-
188
- Args:
189
- request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): captcha.
190
-
191
- Raises:
192
- DeletedError
193
- ExpiredError
194
- DeactivatedError
195
- JWTDecodeError
196
- NotFoundError
197
- ChallengeError
198
- MaxedOutChallengeError
199
-
200
- Returns:
201
- captcha_session
202
- """
203
- captcha_session = await CaptchaSession.decode(request)
204
- captcha_session.validate()
205
- try:
206
- await captcha_session.check_code(request.form.get("captcha"))
207
- except MaxedOutChallengeError as e:
208
- logger.warning(
209
- f"Client {get_ip(request)} has exceeded maximum captcha session {captcha_session.id} challenge attempts."
210
- )
211
- raise e
212
- logger.info(
213
- f"Client {get_ip(request)} has completed captcha session {captcha_session.id} challenge."
214
- )
215
- return captcha_session
216
-
217
-
218
- def requires_captcha(arg=None):
219
- """
220
- Validates a captcha challenge attempt.
221
-
222
- Example:
223
- This method is not called directly and instead used as a decorator:
224
-
225
- @app.post("api/captcha/attempt")
226
- @requires_captcha
227
- async def on_captcha_attempt(request):
228
- return json("Captcha attempt successful!", captcha_session.json())
229
-
230
- Raises:
231
- DeletedError
232
- ExpiredError
233
- DeactivatedError
234
- JWTDecodeError
235
- NotFoundError
236
- ChallengeError
237
- MaxedOutChallengeError
238
- """
239
-
240
- def decorator(func):
241
- @functools.wraps(func)
242
- async def wrapper(request, *args, **kwargs):
243
- await captcha(request)
244
- return await func(request, *args, **kwargs)
245
-
246
- return wrapper
247
-
248
- return decorator(arg) if callable(arg) else decorator
1
+ import functools
2
+ from contextlib import suppress
3
+
4
+ from sanic.log import logger
5
+ from sanic.request import Request
6
+
7
+ from sanic_security.exceptions import (
8
+ JWTDecodeError,
9
+ NotFoundError,
10
+ MaxedOutChallengeError,
11
+ DeactivatedError,
12
+ )
13
+ from sanic_security.models import (
14
+ Account,
15
+ TwoStepSession,
16
+ CaptchaSession,
17
+ )
18
+ from sanic_security.utils import get_ip
19
+
20
+ """
21
+ Copyright (c) 2020-present Nicholas Aidan Stewart
22
+
23
+ Permission is hereby granted, free of charge, to any person obtaining a copy
24
+ of this software and associated documentation files (the "Software"), to deal
25
+ in the Software without restriction, including without limitation the rights
26
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27
+ copies of the Software, and to permit persons to whom the Software is
28
+ furnished to do so, subject to the following conditions:
29
+
30
+ The above copyright notice and this permission notice shall be included in all
31
+ copies or substantial portions of the Software.
32
+
33
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39
+ SOFTWARE.
40
+ """
41
+
42
+
43
+ async def request_two_step_verification(
44
+ request: Request, account: Account = None, tag: str = "2sv"
45
+ ) -> TwoStepSession:
46
+ """
47
+ Creates a two-step session and deactivates the client's current two-step session if found.
48
+
49
+ Args:
50
+ request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): email.
51
+ account (Account): The account being associated with the new verification session. If None, an account is retrieved via the email in the request form-data or an existing two-step session.
52
+ tag (str): Label used to distinguish verification for specific purposes.
53
+
54
+ Raises:
55
+ NotFoundError
56
+
57
+ Returns:
58
+ two_step_session
59
+ """
60
+ with suppress(NotFoundError, JWTDecodeError):
61
+ two_step_session = await TwoStepSession.decode(request)
62
+ if two_step_session.active:
63
+ await two_step_session.deactivate()
64
+ if not account:
65
+ account = two_step_session.bearer
66
+ if request.form.get("email") or not account:
67
+ account = await Account.get_via_email(request.form.get("email"))
68
+ two_step_session = await TwoStepSession.new(request, account, tag=tag)
69
+ request.ctx.session = two_step_session
70
+ return two_step_session
71
+
72
+
73
+ async def two_step_verification(request: Request, tag: str = "2sv") -> TwoStepSession:
74
+ """
75
+ Validates a two-step verification attempt.
76
+
77
+ Args:
78
+ request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): code.
79
+ tag (str): Label used to distinguish verification for specific purposes.
80
+
81
+ Raises:
82
+ NotFoundError
83
+ JWTDecodeError
84
+ DeletedError
85
+ ExpiredError
86
+ DeactivatedError
87
+ UnverifiedError
88
+ DisabledError
89
+ ChallengeError
90
+ MaxedOutChallengeError
91
+
92
+ Returns:
93
+ two_step_session
94
+ """
95
+ two_step_session = await TwoStepSession.decode(request, tag=tag)
96
+ two_step_session.validate()
97
+ two_step_session.bearer.validate()
98
+ try:
99
+ await two_step_session.check_code(request.form.get("code"))
100
+ except MaxedOutChallengeError as e:
101
+ logger.warning(
102
+ f"Client {get_ip(request)} has exceeded maximum two-step session {two_step_session.id} challenge attempts."
103
+ )
104
+ raise e
105
+ logger.info(
106
+ f"Client {get_ip(request)} has completed two-step session {two_step_session.id} challenge."
107
+ )
108
+ return two_step_session
109
+
110
+
111
+ def requires_two_step_verification(func=None, *, tag="2sv"):
112
+ """
113
+ Validates a two-step verification attempt.
114
+
115
+ Args:
116
+ tag (str): Label used to distinguish verification for specific purposes.
117
+
118
+ Example:
119
+ This method is not called directly and instead used as a decorator:
120
+
121
+ @app.post("api/verification/attempt")
122
+ @requires_two_step_verification
123
+ async def on_verified(request):
124
+ response = json("Two-step verification attempt successful!", two_step_session.json())
125
+ return response
126
+
127
+ Raises:
128
+ NotFoundError
129
+ JWTDecodeError
130
+ DeletedError
131
+ ExpiredError
132
+ DeactivatedError
133
+ UnverifiedError
134
+ DisabledError
135
+ ChallengeError
136
+ MaxedOutChallengeError
137
+ """
138
+
139
+ def decorator(func):
140
+ @functools.wraps(func)
141
+ async def wrapper(request, *args, **kwargs):
142
+ await two_step_verification(request, tag)
143
+ return await func(request, *args, **kwargs)
144
+
145
+ return wrapper
146
+
147
+ return decorator if func is None else decorator(func)
148
+
149
+
150
+ async def verify_account(request: Request) -> TwoStepSession:
151
+ """
152
+ Verifies the client's account via two-step session code.
153
+
154
+ Args:
155
+ request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): code.
156
+
157
+ Raises:
158
+ NotFoundError
159
+ JWTDecodeError
160
+ DeletedError
161
+ ExpiredError
162
+ DeactivatedError
163
+ ChallengeError
164
+ MaxedOutChallengeError
165
+
166
+ Returns:
167
+ two_step_session
168
+ """
169
+ two_step_session = await TwoStepSession.decode(request, tag="2fa")
170
+ if two_step_session.bearer.verified:
171
+ raise DeactivatedError("Account already verified.", 403)
172
+ two_step_session.validate()
173
+ try:
174
+ await two_step_session.check_code(request.form.get("code"))
175
+ except MaxedOutChallengeError as e:
176
+ logger.warning(
177
+ f"Client {get_ip(request)} has exceeded maximum two-step session {two_step_session.id} challenge attempts "
178
+ "during account verification."
179
+ )
180
+ raise e
181
+ two_step_session.bearer.verified = True
182
+ await two_step_session.bearer.save(update_fields=["verified"])
183
+ logger.info(
184
+ f"Client {get_ip(request)} has verified account {two_step_session.bearer.id}."
185
+ )
186
+ return two_step_session
187
+
188
+
189
+ async def captcha(request: Request) -> CaptchaSession:
190
+ """
191
+ Validates a captcha challenge attempt.
192
+
193
+ Args:
194
+ request (Request): Sanic request parameter. Request body should contain form-data with the following argument(s): captcha.
195
+
196
+ Raises:
197
+ DeletedError
198
+ ExpiredError
199
+ DeactivatedError
200
+ JWTDecodeError
201
+ NotFoundError
202
+ ChallengeError
203
+ MaxedOutChallengeError
204
+
205
+ Returns:
206
+ captcha_session
207
+ """
208
+ captcha_session = await CaptchaSession.decode(request)
209
+ captcha_session.validate()
210
+ try:
211
+ await captcha_session.check_code(request.form.get("captcha"))
212
+ except MaxedOutChallengeError as e:
213
+ logger.warning(
214
+ f"Client {get_ip(request)} has exceeded maximum captcha session {captcha_session.id} challenge attempts."
215
+ )
216
+ raise e
217
+ logger.info(
218
+ f"Client {get_ip(request)} has completed captcha session {captcha_session.id} challenge."
219
+ )
220
+ return captcha_session
221
+
222
+
223
+ def requires_captcha(arg=None):
224
+ """
225
+ Validates a captcha challenge attempt.
226
+
227
+ Example:
228
+ This method is not called directly and instead used as a decorator:
229
+
230
+ @app.post("api/captcha/attempt")
231
+ @requires_captcha
232
+ async def on_captcha_attempt(request):
233
+ return json("Captcha attempt successful!", captcha_session.json())
234
+
235
+ Raises:
236
+ DeletedError
237
+ ExpiredError
238
+ DeactivatedError
239
+ JWTDecodeError
240
+ NotFoundError
241
+ ChallengeError
242
+ MaxedOutChallengeError
243
+ """
244
+
245
+ def decorator(func):
246
+ @functools.wraps(func)
247
+ async def wrapper(request, *args, **kwargs):
248
+ await captcha(request)
249
+ return await func(request, *args, **kwargs)
250
+
251
+ return wrapper
252
+
253
+ return decorator(arg) if callable(arg) else decorator