Database Authentication backend

This page describes how to store access tokens generated by fastapi-users to the database using tortoise-orm. If you want ot get a better idea of what this is about I suggest you read this page from the official fastapi-users documentation.

We'll expand from the basic Tortoise ORM configuration.

1
2
3
4
5
6
7
from fastapi_users_tortoise.access_token import TortoiseBaseAccessTokenModel, TortoiseAccessTokenDatabase

class AccessToken(TortoiseBaseAccessTokenModel):
    pass

async def get_access_token_db():
    yield TortoiseAccessTokenDatabase[AccessToken](AccessToken)
  1. We define an AccessToken ORM model inheriting from TortoiseBaseAccessTokenModel.

  2. We define a dependency to instantiate the TortoiseAccessTokenDatabase class. Just like the user database adapter, it expects the AccessToken model class we defined above.

That's it, the TortoiseBaseAccessTokenModel class defines a foreign key relationship to your user model like this:

1
2
3
4
5
6
7
class TortoiseBaseAccessTokenModel(models.Model):
    """Tortoise access token model definition."""
    ...
    user = fields.ForeignKeyField("models.User")

    class Meta:
        abstract = True

You only need to change this if your user model is not called User or if it is not present in a tortoise orm app/namespace called models.