FreeAuth Dependencies
FreeAuth provides several dependency callables to easily inject to your routes. They are available from your FreeAuthApp
instance.
current_user
Return a dependency callable to retrieve current authenticated user. None
is returned if there is no authenticated user. For example:
import json
from fastapi import Depends, Response
from freeauth.db.auth.auth_qry_async_edgeql import (
create_audit_log,
sign_out,
)
from freeauth.ext.fastapi_ext.utils import get_client_info
@router.post("/logout")
async def logout(
resp: Response,
client_info=Depends(get_client_info),
token=Depends(auth_app.get_access_token),
user=Depends(auth_app.current_user),
):
if not token:
return "ok"
await sign_out(auth_app.db, access_token=token.access_token)
if current_user:
await create_audit_log(
auth_app.db,
user_id=user.id,
client_info=json.dumps(client_info),
status_code="OK",
event_type="SignOut",
)
resp.delete_cookie("access_token")
return "ok"
current_user_or_401
Return a dependency callable to retrieve current authenticated user. A 401 Unauthorized
exception is thrown if there is no authenticated user. For example:
@router.get("/protected-route")
def protected_route(user=Depends(auth_app.current_user_or_401)):
return f"Hello, {user.name or user.username}"
perm_accepted()
Return a dependency callable to confirm permission acceptance for current authenticated user, perm_accepted
can accept multiple permission codes as arguments. 403 Forbidden
exception is thrown if none of the permissions are accepted, otherwise, it returns current authenticated user object. For example:
@router.get(
"/items/{item_id}"
dependencies=[Depends(auth_app.perm_accepted("view:item"))],
)
def show_item(item_id: int):
...
get_client_info
Retrieve client information which includes essential details about the User-Agent data. See the example in current_user
.