-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcommon.py
More file actions
66 lines (45 loc) · 1.96 KB
/
common.py
File metadata and controls
66 lines (45 loc) · 1.96 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
from collections.abc import Mapping
from typing import Mapping as MappingType
from typing import Sequence
from .authorization import AuthorizationContext, Policy, Requirement
class AnonymousRequirement(Requirement):
"""Requires an anonymous user, or service."""
def handle(self, context: AuthorizationContext):
identity = context.identity
if not identity or not identity.is_authenticated():
context.succeed(self)
class AnonymousPolicy(Policy):
"""Policy that requires an anonymous user, or service."""
def __init__(self, name: str = "anonymous"):
super().__init__(name, AnonymousRequirement())
class AuthenticatedRequirement(Requirement):
"""
Requires an authenticated user, or service. Meaning that an `identity` must be set
in the authorization context.
"""
def handle(self, context: AuthorizationContext):
identity = context.identity
if identity and identity.is_authenticated():
context.succeed(self)
RequiredClaimsType = MappingType[str, str] | Sequence[str] | str
class ClaimsRequirement(Requirement):
"""Requires an identity with a claims: one or more, optionally with exact values."""
__slots__ = ("required_claims",)
def __init__(self, required_claims: RequiredClaimsType):
if isinstance(required_claims, str):
required_claims = [required_claims]
self.required_claims = required_claims
def handle(self, context: AuthorizationContext):
identity = context.identity
if not identity:
context.fail("Missing identity")
return
if isinstance(self.required_claims, Mapping):
if all(
identity.has_claim_value(key, value)
for key, value in self.required_claims.items()
):
context.succeed(self)
else:
if all(identity.has_claim(name) for name in self.required_claims):
context.succeed(self)