-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample-07.py
More file actions
75 lines (55 loc) · 1.84 KB
/
example-07.py
File metadata and controls
75 lines (55 loc) · 1.84 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
This example illustrates a basic use of an authorization strategy, with support for
dependency injection for authorization requirements.
"""
from __future__ import annotations
import asyncio
from rodi import Container
from guardpost import (
AuthorizationContext,
AuthorizationError,
AuthorizationStrategy,
Identity,
Policy,
Requirement,
UnauthorizedError,
)
class Foo:
...
class MyInjectedRequirement(Requirement):
foo: Foo
def handle(self, context: AuthorizationContext):
assert isinstance(self.foo, Foo)
# 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():
container = Container()
# NOTE: the following classes are registered as transient services - therefore
# they are instantiated each time they are necessary.
# Refer to rodi documentation to know how to register singletons and scoped
# services.
container.register(Foo)
container.register(MyInjectedRequirement)
authorization = AuthorizationStrategy(
Policy("default", MyInjectedRequirement), container=container
)
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())