mirror of
https://github.com/d3vyce/fastapi-toolsets.git
synced 2026-08-14 19:58:39 +00:00
wip
This commit is contained in:
@@ -33,23 +33,6 @@ class BearerTokenAuth(AuthSource):
|
||||
for user tokens, ``"org_"`` for org tokens).
|
||||
**kwargs: Extra keyword arguments forwarded to the validator on every
|
||||
call (e.g. ``role=Role.ADMIN``).
|
||||
|
||||
Example::
|
||||
|
||||
async def verify_token(token: str, *, role: Role) -> User:
|
||||
user = await db.get_by_token(token) # token includes prefix
|
||||
if not user or user.role != role:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
bearer_admin = BearerTokenAuth(verify_token, prefix="user_", role=Role.ADMIN)
|
||||
|
||||
# Generate a token to store in DB and return to the client:
|
||||
token = bearer_admin.generate_token() # e.g. "user_Xk3..."
|
||||
|
||||
@app.get("/admin")
|
||||
async def admin_route(user: User = Security(bearer_admin)):
|
||||
return user
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -64,18 +47,12 @@ class BearerTokenAuth(AuthSource):
|
||||
self._kwargs = kwargs
|
||||
self._scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
# Capture locals for the closure — self._scheme cannot be referenced
|
||||
# inside the Annotated default because annotations are evaluated at
|
||||
# function-definition time (no `from __future__ import annotations`).
|
||||
_scheme = self._scheme
|
||||
_validator = validator
|
||||
_kwargs = kwargs
|
||||
_prefix = prefix
|
||||
|
||||
async def _call(
|
||||
# security_scopes is unused in the body but its presence in the
|
||||
# signature tells FastAPI to aggregate scopes from Security() calls
|
||||
# up the dependency chain and expose them in the OpenAPI schema.
|
||||
security_scopes: SecurityScopes, # noqa: ARG001
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None, Depends(_scheme)
|
||||
@@ -88,9 +65,6 @@ class BearerTokenAuth(AuthSource):
|
||||
raise UnauthorizedError()
|
||||
return await _validator(token, **_kwargs)
|
||||
|
||||
# __call__ must be defined on the class (not the instance) so that
|
||||
# callable(self) returns True. We expose the closure's signature via
|
||||
# __signature__ so FastAPI resolves the correct sub-dependencies.
|
||||
self._call_fn = _call
|
||||
self.__signature__ = inspect.signature(_call)
|
||||
|
||||
@@ -123,20 +97,7 @@ class BearerTokenAuth(AuthSource):
|
||||
return await self._validator(credential, **self._kwargs)
|
||||
|
||||
def require(self, **kwargs: Any) -> "BearerTokenAuth":
|
||||
"""Return a new instance with additional (or overriding) validator kwargs.
|
||||
|
||||
Useful for specifying per-endpoint requirements inline without
|
||||
declaring a new top-level variable::
|
||||
|
||||
bearer = BearerTokenAuth(verify_token)
|
||||
|
||||
@app.get("/admin")
|
||||
async def admin(user: User = Security(bearer.require(role=Role.ADMIN))):
|
||||
return user
|
||||
|
||||
The ``prefix`` is preserved. New kwargs are merged over existing ones
|
||||
(new values win on conflict).
|
||||
"""
|
||||
"""Return a new instance with additional (or overriding) validator kwargs."""
|
||||
return BearerTokenAuth(
|
||||
self._validator,
|
||||
prefix=self._prefix,
|
||||
@@ -157,13 +118,6 @@ class BearerTokenAuth(AuthSource):
|
||||
|
||||
Returns:
|
||||
A ready-to-use token string (e.g. ``"user_Xk3..."``).
|
||||
|
||||
Example::
|
||||
|
||||
bearer = BearerTokenAuth(verify_token, prefix="user_")
|
||||
token = bearer.generate_token() # "user_<random>"
|
||||
await db.store_token(user_id, token)
|
||||
return {"access_token": token, "token_type": "bearer"}
|
||||
"""
|
||||
token = secrets.token_urlsafe(nbytes)
|
||||
if self._prefix is not None:
|
||||
|
||||
Reference in New Issue
Block a user