sanic-security 1.16.12__py3-none-any.whl → 1.17.0__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.
- sanic_security/authentication.py +379 -363
- sanic_security/authorization.py +240 -240
- sanic_security/configuration.py +125 -125
- sanic_security/exceptions.py +164 -164
- sanic_security/models.py +721 -701
- sanic_security/oauth.py +242 -241
- sanic_security/test/server.py +368 -368
- sanic_security/test/tests.py +547 -547
- sanic_security/utils.py +121 -121
- sanic_security/verification.py +253 -248
- {sanic_security-1.16.12.dist-info → sanic_security-1.17.0.dist-info}/METADATA +672 -672
- sanic_security-1.17.0.dist-info/RECORD +17 -0
- {sanic_security-1.16.12.dist-info → sanic_security-1.17.0.dist-info}/licenses/LICENSE +21 -21
- sanic_security-1.16.12.dist-info/RECORD +0 -17
- {sanic_security-1.16.12.dist-info → sanic_security-1.17.0.dist-info}/WHEEL +0 -0
- {sanic_security-1.16.12.dist-info → sanic_security-1.17.0.dist-info}/top_level.txt +0 -0
sanic_security/authorization.py
CHANGED
@@ -1,240 +1,240 @@
|
|
1
|
-
import functools
|
2
|
-
|
3
|
-
from sanic.log import logger
|
4
|
-
from sanic.request import Request
|
5
|
-
from tortoise.exceptions import DoesNotExist
|
6
|
-
|
7
|
-
from sanic_security.authentication import authenticate
|
8
|
-
from sanic_security.exceptions import AuthorizationError, AnonymousError
|
9
|
-
from sanic_security.models import Role, Account, AuthenticationSession
|
10
|
-
from sanic_security.utils import get_ip
|
11
|
-
|
12
|
-
"""
|
13
|
-
Copyright (c) 2020-present Nicholas Aidan Stewart
|
14
|
-
|
15
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
16
|
-
of this software and associated documentation files (the "Software"), to deal
|
17
|
-
in the Software without restriction, including without limitation the rights
|
18
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
19
|
-
copies of the Software, and to permit persons to whom the Software is
|
20
|
-
furnished to do so, subject to the following conditions:
|
21
|
-
|
22
|
-
The above copyright notice and this permission notice shall be included in all
|
23
|
-
copies or substantial portions of the Software.
|
24
|
-
|
25
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
26
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
27
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
28
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
29
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
30
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
31
|
-
SOFTWARE.
|
32
|
-
"""
|
33
|
-
|
34
|
-
|
35
|
-
async def check_permissions(
|
36
|
-
request: Request, *required_permissions: str
|
37
|
-
) -> AuthenticationSession:
|
38
|
-
"""
|
39
|
-
Authenticates client and determines if the account has sufficient permissions for an action.
|
40
|
-
|
41
|
-
Args:
|
42
|
-
request (Request): Sanic request parameter.
|
43
|
-
*required_permissions (Tuple[str, ...]): The permissions required to authorize an action.
|
44
|
-
|
45
|
-
Returns:
|
46
|
-
authentication_session
|
47
|
-
|
48
|
-
Raises:
|
49
|
-
NotFoundError
|
50
|
-
JWTDecodeError
|
51
|
-
DeletedError
|
52
|
-
ExpiredError
|
53
|
-
DeactivatedError
|
54
|
-
UnverifiedError
|
55
|
-
DisabledError
|
56
|
-
AuthorizationError
|
57
|
-
AnonymousError
|
58
|
-
"""
|
59
|
-
authentication_session = await authenticate(request)
|
60
|
-
if authentication_session.anonymous:
|
61
|
-
logger.warning(
|
62
|
-
f"Client {get_ip(request)} attempted an unauthorized action anonymously."
|
63
|
-
)
|
64
|
-
raise AnonymousError
|
65
|
-
roles = await authentication_session.bearer.roles.filter(deleted=False).all()
|
66
|
-
for role in roles:
|
67
|
-
for role_permission in role.permissions:
|
68
|
-
for required_permission in required_permissions:
|
69
|
-
if check_wildcard(role_permission, required_permission):
|
70
|
-
return authentication_session
|
71
|
-
logger.warning(
|
72
|
-
f"Client {get_ip(request)} with account {authentication_session.bearer.id} attempted an unauthorized action."
|
73
|
-
)
|
74
|
-
raise AuthorizationError("Insufficient permissions required for this action.")
|
75
|
-
|
76
|
-
|
77
|
-
def check_wildcard(wildcard: str, pattern: str):
|
78
|
-
"""
|
79
|
-
Evaluates if the wildcard matches the pattern.
|
80
|
-
|
81
|
-
Args:
|
82
|
-
wildcard (str): A wildcard string (e.g., "a:b:c").
|
83
|
-
pattern (str): A wildcard pattern optional (`*`) or comma-separated values to match against (e.g., "a:b,c:*").
|
84
|
-
|
85
|
-
Returns:
|
86
|
-
is_match
|
87
|
-
"""
|
88
|
-
wildcard_parts = [set(part.split(",")) for part in wildcard.split(":")]
|
89
|
-
pattern_parts = [set(part.split(",")) for part in pattern.split(":")]
|
90
|
-
for i, pattern_part in enumerate(pattern_parts):
|
91
|
-
if i >= len(wildcard_parts):
|
92
|
-
return False
|
93
|
-
wildcard_part = wildcard_parts[i]
|
94
|
-
if "*" not in wildcard_part and not wildcard_part.issuperset(pattern_part):
|
95
|
-
return False
|
96
|
-
return all("*" in part for part in wildcard_parts[len(pattern_parts) :])
|
97
|
-
|
98
|
-
|
99
|
-
async def check_roles(request: Request, *required_roles: str) -> AuthenticationSession:
|
100
|
-
"""
|
101
|
-
Authenticates client and determines if the account has sufficient roles for an action.
|
102
|
-
|
103
|
-
Args:
|
104
|
-
request (Request): Sanic request parameter.
|
105
|
-
*required_roles (Tuple[str, ...]): The roles required to authorize an action.
|
106
|
-
|
107
|
-
Returns:
|
108
|
-
authentication_session
|
109
|
-
|
110
|
-
Raises:
|
111
|
-
NotFoundError
|
112
|
-
JWTDecodeError
|
113
|
-
DeletedError
|
114
|
-
ExpiredError
|
115
|
-
DeactivatedError
|
116
|
-
UnverifiedError
|
117
|
-
DisabledError
|
118
|
-
AuthorizationError
|
119
|
-
AnonymousError
|
120
|
-
"""
|
121
|
-
authentication_session = await authenticate(request)
|
122
|
-
if authentication_session.anonymous:
|
123
|
-
logger.warning(
|
124
|
-
f"Client {get_ip(request)} attempted an unauthorized action anonymously."
|
125
|
-
)
|
126
|
-
raise AnonymousError
|
127
|
-
if set(required_roles) & {
|
128
|
-
role.name
|
129
|
-
for role in await authentication_session.bearer.roles.filter(
|
130
|
-
deleted=False
|
131
|
-
).all()
|
132
|
-
}:
|
133
|
-
return authentication_session
|
134
|
-
logger.warning(
|
135
|
-
f"Client {get_ip(request)} with account {authentication_session.bearer.id} attempted an unauthorized action"
|
136
|
-
)
|
137
|
-
raise AuthorizationError("Insufficient roles required for this action")
|
138
|
-
|
139
|
-
|
140
|
-
async def assign_role(
|
141
|
-
name: str,
|
142
|
-
account: Account,
|
143
|
-
description: str = None,
|
144
|
-
*permissions: str,
|
145
|
-
) -> Role:
|
146
|
-
"""
|
147
|
-
Easy account role assignment, role being assigned to an account will be created if it doesn't exist.
|
148
|
-
|
149
|
-
Args:
|
150
|
-
name (str): The name of the role associated with the account.
|
151
|
-
account (Account): The account associated with the created role.
|
152
|
-
description (str): The description of the role associated with the account.
|
153
|
-
*permissions (Tuple[str, ...]): The permissions of the role associated with the account, must be in wildcard format.
|
154
|
-
"""
|
155
|
-
try:
|
156
|
-
role = await Role.filter(name=name).get()
|
157
|
-
except DoesNotExist:
|
158
|
-
role = await Role.create(
|
159
|
-
name=name,
|
160
|
-
description=description,
|
161
|
-
permissions=permissions,
|
162
|
-
)
|
163
|
-
await account.roles.add(role)
|
164
|
-
return role
|
165
|
-
|
166
|
-
|
167
|
-
def requires_permission(*required_permissions: str):
|
168
|
-
"""
|
169
|
-
Authenticates client and determines if the account has sufficient permissions for an action.
|
170
|
-
|
171
|
-
Args:
|
172
|
-
*required_permissions (Tuple[str, ...]): The permissions required to authorize an action.
|
173
|
-
|
174
|
-
Example:
|
175
|
-
This method is not called directly and instead used as a decorator:
|
176
|
-
|
177
|
-
@app.post("api/auth/perms")
|
178
|
-
@requires_permission("admin:update", "employee:add")
|
179
|
-
async def on_authorize(request):
|
180
|
-
return text("Account permitted.")
|
181
|
-
|
182
|
-
Raises:
|
183
|
-
NotFoundError
|
184
|
-
JWTDecodeError
|
185
|
-
DeletedError
|
186
|
-
ExpiredError
|
187
|
-
DeactivatedError
|
188
|
-
UnverifiedError
|
189
|
-
DisabledError
|
190
|
-
AuthorizationError
|
191
|
-
AnonymousError
|
192
|
-
"""
|
193
|
-
|
194
|
-
def decorator(func):
|
195
|
-
@functools.wraps(func)
|
196
|
-
async def wrapper(request, *args, **kwargs):
|
197
|
-
await check_permissions(request, *required_permissions)
|
198
|
-
return await func(request, *args, **kwargs)
|
199
|
-
|
200
|
-
return wrapper
|
201
|
-
|
202
|
-
return decorator
|
203
|
-
|
204
|
-
|
205
|
-
def requires_role(*required_roles: str):
|
206
|
-
"""
|
207
|
-
Authenticates client and determines if the account has sufficient roles for an action.
|
208
|
-
|
209
|
-
Args:
|
210
|
-
*required_roles (Tuple[str, ...]): The roles required to authorize an action.
|
211
|
-
|
212
|
-
Example:
|
213
|
-
This method is not called directly and instead used as a decorator:
|
214
|
-
|
215
|
-
@app.post("api/auth/roles")
|
216
|
-
@requires_role("Admin", "Moderator")
|
217
|
-
async def on_authorize(request):
|
218
|
-
return text("Account permitted")
|
219
|
-
|
220
|
-
Raises:
|
221
|
-
NotFoundError
|
222
|
-
JWTDecodeError
|
223
|
-
DeletedError
|
224
|
-
ExpiredError
|
225
|
-
DeactivatedError
|
226
|
-
UnverifiedError
|
227
|
-
DisabledError
|
228
|
-
AuthorizationError
|
229
|
-
AnonymousError
|
230
|
-
"""
|
231
|
-
|
232
|
-
def decorator(func):
|
233
|
-
@functools.wraps(func)
|
234
|
-
async def wrapper(request, *args, **kwargs):
|
235
|
-
await check_roles(request, *required_roles)
|
236
|
-
return await func(request, *args, **kwargs)
|
237
|
-
|
238
|
-
return wrapper
|
239
|
-
|
240
|
-
return decorator
|
1
|
+
import functools
|
2
|
+
|
3
|
+
from sanic.log import logger
|
4
|
+
from sanic.request import Request
|
5
|
+
from tortoise.exceptions import DoesNotExist
|
6
|
+
|
7
|
+
from sanic_security.authentication import authenticate
|
8
|
+
from sanic_security.exceptions import AuthorizationError, AnonymousError
|
9
|
+
from sanic_security.models import Role, Account, AuthenticationSession
|
10
|
+
from sanic_security.utils import get_ip
|
11
|
+
|
12
|
+
"""
|
13
|
+
Copyright (c) 2020-present Nicholas Aidan Stewart
|
14
|
+
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
17
|
+
in the Software without restriction, including without limitation the rights
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
20
|
+
furnished to do so, subject to the following conditions:
|
21
|
+
|
22
|
+
The above copyright notice and this permission notice shall be included in all
|
23
|
+
copies or substantial portions of the Software.
|
24
|
+
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
31
|
+
SOFTWARE.
|
32
|
+
"""
|
33
|
+
|
34
|
+
|
35
|
+
async def check_permissions(
|
36
|
+
request: Request, *required_permissions: str
|
37
|
+
) -> AuthenticationSession:
|
38
|
+
"""
|
39
|
+
Authenticates client and determines if the account has sufficient permissions for an action.
|
40
|
+
|
41
|
+
Args:
|
42
|
+
request (Request): Sanic request parameter.
|
43
|
+
*required_permissions (Tuple[str, ...]): The permissions required to authorize an action.
|
44
|
+
|
45
|
+
Returns:
|
46
|
+
authentication_session
|
47
|
+
|
48
|
+
Raises:
|
49
|
+
NotFoundError
|
50
|
+
JWTDecodeError
|
51
|
+
DeletedError
|
52
|
+
ExpiredError
|
53
|
+
DeactivatedError
|
54
|
+
UnverifiedError
|
55
|
+
DisabledError
|
56
|
+
AuthorizationError
|
57
|
+
AnonymousError
|
58
|
+
"""
|
59
|
+
authentication_session = await authenticate(request)
|
60
|
+
if authentication_session.anonymous:
|
61
|
+
logger.warning(
|
62
|
+
f"Client {get_ip(request)} attempted an unauthorized action anonymously."
|
63
|
+
)
|
64
|
+
raise AnonymousError
|
65
|
+
roles = await authentication_session.bearer.roles.filter(deleted=False).all()
|
66
|
+
for role in roles:
|
67
|
+
for role_permission in role.permissions:
|
68
|
+
for required_permission in required_permissions:
|
69
|
+
if check_wildcard(role_permission, required_permission):
|
70
|
+
return authentication_session
|
71
|
+
logger.warning(
|
72
|
+
f"Client {get_ip(request)} with account {authentication_session.bearer.id} attempted an unauthorized action."
|
73
|
+
)
|
74
|
+
raise AuthorizationError("Insufficient permissions required for this action.")
|
75
|
+
|
76
|
+
|
77
|
+
def check_wildcard(wildcard: str, pattern: str):
|
78
|
+
"""
|
79
|
+
Evaluates if the wildcard matches the pattern.
|
80
|
+
|
81
|
+
Args:
|
82
|
+
wildcard (str): A wildcard string (e.g., "a:b:c").
|
83
|
+
pattern (str): A wildcard pattern optional (`*`) or comma-separated values to match against (e.g., "a:b,c:*").
|
84
|
+
|
85
|
+
Returns:
|
86
|
+
is_match
|
87
|
+
"""
|
88
|
+
wildcard_parts = [set(part.split(",")) for part in wildcard.split(":")]
|
89
|
+
pattern_parts = [set(part.split(",")) for part in pattern.split(":")]
|
90
|
+
for i, pattern_part in enumerate(pattern_parts):
|
91
|
+
if i >= len(wildcard_parts):
|
92
|
+
return False
|
93
|
+
wildcard_part = wildcard_parts[i]
|
94
|
+
if "*" not in wildcard_part and not wildcard_part.issuperset(pattern_part):
|
95
|
+
return False
|
96
|
+
return all("*" in part for part in wildcard_parts[len(pattern_parts) :])
|
97
|
+
|
98
|
+
|
99
|
+
async def check_roles(request: Request, *required_roles: str) -> AuthenticationSession:
|
100
|
+
"""
|
101
|
+
Authenticates client and determines if the account has sufficient roles for an action.
|
102
|
+
|
103
|
+
Args:
|
104
|
+
request (Request): Sanic request parameter.
|
105
|
+
*required_roles (Tuple[str, ...]): The roles required to authorize an action.
|
106
|
+
|
107
|
+
Returns:
|
108
|
+
authentication_session
|
109
|
+
|
110
|
+
Raises:
|
111
|
+
NotFoundError
|
112
|
+
JWTDecodeError
|
113
|
+
DeletedError
|
114
|
+
ExpiredError
|
115
|
+
DeactivatedError
|
116
|
+
UnverifiedError
|
117
|
+
DisabledError
|
118
|
+
AuthorizationError
|
119
|
+
AnonymousError
|
120
|
+
"""
|
121
|
+
authentication_session = await authenticate(request)
|
122
|
+
if authentication_session.anonymous:
|
123
|
+
logger.warning(
|
124
|
+
f"Client {get_ip(request)} attempted an unauthorized action anonymously."
|
125
|
+
)
|
126
|
+
raise AnonymousError
|
127
|
+
if set(required_roles) & {
|
128
|
+
role.name
|
129
|
+
for role in await authentication_session.bearer.roles.filter(
|
130
|
+
deleted=False
|
131
|
+
).all()
|
132
|
+
}:
|
133
|
+
return authentication_session
|
134
|
+
logger.warning(
|
135
|
+
f"Client {get_ip(request)} with account {authentication_session.bearer.id} attempted an unauthorized action"
|
136
|
+
)
|
137
|
+
raise AuthorizationError("Insufficient roles required for this action")
|
138
|
+
|
139
|
+
|
140
|
+
async def assign_role(
|
141
|
+
name: str,
|
142
|
+
account: Account,
|
143
|
+
description: str = None,
|
144
|
+
*permissions: str,
|
145
|
+
) -> Role:
|
146
|
+
"""
|
147
|
+
Easy account role assignment, role being assigned to an account will be created if it doesn't exist.
|
148
|
+
|
149
|
+
Args:
|
150
|
+
name (str): The name of the role associated with the account.
|
151
|
+
account (Account): The account associated with the created role.
|
152
|
+
description (str): The description of the role associated with the account.
|
153
|
+
*permissions (Tuple[str, ...]): The permissions of the role associated with the account, must be in wildcard format.
|
154
|
+
"""
|
155
|
+
try:
|
156
|
+
role = await Role.filter(name=name).get()
|
157
|
+
except DoesNotExist:
|
158
|
+
role = await Role.create(
|
159
|
+
name=name,
|
160
|
+
description=description,
|
161
|
+
permissions=permissions,
|
162
|
+
)
|
163
|
+
await account.roles.add(role)
|
164
|
+
return role
|
165
|
+
|
166
|
+
|
167
|
+
def requires_permission(*required_permissions: str):
|
168
|
+
"""
|
169
|
+
Authenticates client and determines if the account has sufficient permissions for an action.
|
170
|
+
|
171
|
+
Args:
|
172
|
+
*required_permissions (Tuple[str, ...]): The permissions required to authorize an action.
|
173
|
+
|
174
|
+
Example:
|
175
|
+
This method is not called directly and instead used as a decorator:
|
176
|
+
|
177
|
+
@app.post("api/auth/perms")
|
178
|
+
@requires_permission("admin:update", "employee:add")
|
179
|
+
async def on_authorize(request):
|
180
|
+
return text("Account permitted.")
|
181
|
+
|
182
|
+
Raises:
|
183
|
+
NotFoundError
|
184
|
+
JWTDecodeError
|
185
|
+
DeletedError
|
186
|
+
ExpiredError
|
187
|
+
DeactivatedError
|
188
|
+
UnverifiedError
|
189
|
+
DisabledError
|
190
|
+
AuthorizationError
|
191
|
+
AnonymousError
|
192
|
+
"""
|
193
|
+
|
194
|
+
def decorator(func):
|
195
|
+
@functools.wraps(func)
|
196
|
+
async def wrapper(request, *args, **kwargs):
|
197
|
+
await check_permissions(request, *required_permissions)
|
198
|
+
return await func(request, *args, **kwargs)
|
199
|
+
|
200
|
+
return wrapper
|
201
|
+
|
202
|
+
return decorator
|
203
|
+
|
204
|
+
|
205
|
+
def requires_role(*required_roles: str):
|
206
|
+
"""
|
207
|
+
Authenticates client and determines if the account has sufficient roles for an action.
|
208
|
+
|
209
|
+
Args:
|
210
|
+
*required_roles (Tuple[str, ...]): The roles required to authorize an action.
|
211
|
+
|
212
|
+
Example:
|
213
|
+
This method is not called directly and instead used as a decorator:
|
214
|
+
|
215
|
+
@app.post("api/auth/roles")
|
216
|
+
@requires_role("Admin", "Moderator")
|
217
|
+
async def on_authorize(request):
|
218
|
+
return text("Account permitted")
|
219
|
+
|
220
|
+
Raises:
|
221
|
+
NotFoundError
|
222
|
+
JWTDecodeError
|
223
|
+
DeletedError
|
224
|
+
ExpiredError
|
225
|
+
DeactivatedError
|
226
|
+
UnverifiedError
|
227
|
+
DisabledError
|
228
|
+
AuthorizationError
|
229
|
+
AnonymousError
|
230
|
+
"""
|
231
|
+
|
232
|
+
def decorator(func):
|
233
|
+
@functools.wraps(func)
|
234
|
+
async def wrapper(request, *args, **kwargs):
|
235
|
+
await check_roles(request, *required_roles)
|
236
|
+
return await func(request, *args, **kwargs)
|
237
|
+
|
238
|
+
return wrapper
|
239
|
+
|
240
|
+
return decorator
|