Authentication and authorization
Understand the moving parts
Walk through the code
from pysx import (
AccessDenied,
Fragment,
RequestContext,
SecurityPolicy,
current_request,
pysx,
require_access,
signal,
)
def authorize(request: RequestContext, action: str, target: str) -> bool:
writer = request.principal == "writer"
return action != "write" or (writer and target == "course-demo")
def app() -> Fragment:
user = current_request().principal or "learner"
count = signal(0)
result = signal("No write attempted")
def write(_: object) -> None:
try:
require_access("write", "course-demo")
except AccessDenied:
result.set("Denied by current host policy")
return
count.update(lambda value: value + 1)
result.set("Allowed by current host policy")
return pysx(t"""
p: "Local demonstration identity: "
output(id="auth-principal"): {user}
div:
a(id="auth-reader" href="/demo-login/reader"): "Sign in as reader"
a(id="auth-writer" href="/demo-login/writer"): "Sign in as writer"
a(id="auth-logout" href="/demo-logout"): "Sign out"
button(id="auth-write" onClick={write}): "Attempt protected write"
output(id="auth-count"): {count}
output(id="auth-result" role="status"): {result}
p: "These local roles are not a production credential provider."
""")
policy = SecurityPolicy(authorize=authorize)Try it live
What to observe
Local demonstration identity:
These local roles are not a production credential provider.