-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample-05.py
More file actions
54 lines (40 loc) · 1.29 KB
/
example-05.py
File metadata and controls
54 lines (40 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
This example illustrates a basic use of an authorization strategy.
"""
from __future__ import annotations
import asyncio
from guardpost import (
AuthorizationContext,
AuthorizationError,
AuthorizationStrategy,
Identity,
Policy,
Requirement,
UnauthorizedError,
)
class MyRequirement(Requirement):
def handle(self, context: AuthorizationContext):
# EXAMPLE: implement here the desired notion / requirements for authorization
#
roles = context.identity["roles"]
if roles and "ADMIN" in roles:
context.succeed(self)
else:
context.fail("The user is not an ADMIN")
# NOTE: a Requirement.handle method can also be async!
async def main():
authorization = AuthorizationStrategy(Policy("default", MyRequirement()))
await authorization.authorize(
"default", Identity({"sub": "example", "roles": ["ADMIN"]})
)
auth_error = None
try:
await authorization.authorize(
"default", Identity({"sub": "example", "roles": ["PEASANT"]})
)
except AuthorizationError as error:
auth_error = error
assert auth_error is not None
assert isinstance(auth_error, UnauthorizedError)
assert "The user is not an ADMIN." in str(auth_error)
asyncio.run(main())