Tables

We store the tokens in TokenAuth table, and the user credentials in BaseUser table.


Migrations

We recommend creating these tables using migrations.

You can add piccolo_api.token_auth.piccolo_app to the apps arguments of the AppRegistry in piccolo_conf.py.

APP_REGISTRY = AppRegistry(
    apps=[
        ...
        "piccolo_api.token_auth.piccolo_app",
        "piccolo.apps.user.piccolo_app",
        ...
    ]
)

To learn more about Piccolo apps, see the Piccolo docs.

To run the migrations and create the tables, run:

piccolo migrations forwards user
piccolo migrations forwards token_auth

Creating them manually

If you prefer not to use migrations, and want to create them manually, you can do this instead:

from piccolo_api.token_auth.tables import TokenAuth
from piccolo.apps.user.tables import BaseUser
from piccolo.tables import create_tables

create_tables(BaseUser, TokenAuth, if_not_exists=True)

Source

TokenAuth

class piccolo_api.token_auth.tables.TokenAuth(_data: Dict[Column, Any] | None = None, _ignore_missing: bool = False, _exists_in_db: bool = False, **kwargs)[source]

Holds randomly generated tokens.

Useful for mobile authentication, IOT etc. Session auth is recommended for web usage.

async classmethod authenticate(token: str) First[source]
async classmethod authenticate_sync(token: str) int | None[source]
async classmethod create_token(user_id: int, one_per_user: bool = True) str[source]

Create a new token.

Parameters:

one_per_user – If True, a ValueError is raised if a token already exists for that user.

classmethod create_token_sync(user_id: int) str[source]
async classmethod get_user_id(token: str) int | None[source]

Returns the user_id if the given token is valid, otherwise None.