Flask-Login like package for FastAPI
Low maintenance activity. Last release 24 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install fastapi-loginFastAPI-Login
FastAPI-Login tries to provide similar functionality as Flask-Login does.
Documentation
In-depth documentation can be found at fastapi-login.readthedocs.io.
Some examples can be found here.
Installation
pip install fastapi-login
Usage
To begin we have to set up our FastAPI app:
from fastapi import FastAPI
SECRET = 'your-secret-key'
app = FastAPI()
To obtain a suitable secret key you can run import secrets; print(secrets.token_hex(24)).
Now we can import and setup the LoginManager, which will handle the process of encoding and decoding our Json Web Tokens.
from fastapi_login import LoginManager
manager = LoginManager(SECRET, token_url='/auth/token')
For the example we will use a dictionary to represent our user database. In your application this could also be a real database like sqlite or Postgres. It does not matter as you have to provide the function which retrieves the user.
fake_db = {'johndoe@e.mail': {'password': 'hunter2'}}
Now we have to provide the LoginManager with a way to load our user. The
user_loader callback should either return your user object or None
@manager.user_loader()
def load_user(email: str): # could also be an asynchronous function
user = fake_db.get(email)
return user