Skip to content

📖 How to Use

All operations are plain async functions that work identically under FastAPI, Flask, a CLI, or a script. Substitute your own repository to change the persistence backend.


✍️ Register a user

import asyncio
from jwtlib import register_user, RegisterRequest

async def main():
    user = await register_user(
        RegisterRequest(username="admin", email="admin@aetoskia.com", password="hunter2")
    )
    print(user.username, user.is_active)

asyncio.run(main())

Returns a PublicUser. Registration hashes the password before it reaches the repository.


🔑 Log in

1
2
3
4
5
6
from jwtlib import login_user, LoginRequest

response = await login_user(LoginRequest(username="admin", password="hunter2"))

response.access_token  # store this in the Authorization header
response.user.username

A successful login returns LoginResponse with an access token and the public user. Failures raise AuthError subclasses; catch them and map to your HTTP semantics (e.g. 401).


👤 Check the current user

1
2
3
4
from jwtlib import get_logged_in_user

user = await get_logged_in_user(bearer_token)
print(user.username, user.email, user.is_active)

Resolves the token subject to a PublicUser. Raises InvalidToken if the token is missing, expired, or malformed, and UserNotFound if the subject no longer exists.


🚪 Log out

1
2
3
4
from jwtlib import logout_user

result = await logout_user()
print(result.message)

Logout is a client-side signal: the returned LogoutResponse tells the caller to discard the stored token. Stateless services should simply stop using the token after logout.


🔎 Introspect a token

Verify an arbitrary token and get a structured verdict:

1
2
3
4
5
6
from jwtlib import introspect_token

verdict = await introspect_token(bearer_token)

verdict.active        # True when the token is valid
verdict.user.username # resolved subject, or None

IntrospectResponse also provides result helpers used by the canonical service for error mapping. For a pure boolean authorization check:

1
2
3
from jwtlib.introspection import authenticate_request

ok = await authenticate_request(bearer_token)  # True / False

💉 Injecting a custom repository

Every operation accepts an optional repo. Provide your own UserRepository-compatible object to swap storage:

1
2
3
4
5
6
7
from jwtlib import login_user, LoginRequest

class MyRepo:
    async def get_by_username(self, username: str): ...
    async def authenticate_user(self, user_auth: LoginRequest): ...

response = await login_user(LoginRequest(username="admin", password="x"), repo=MyRepo())