def exception_manager(app, secret, token_url, load_user_fn, custom_exception) -> LoginManager: instance = LoginManager(secret, token_url) instance.user_loader(load_user_fn) # exception handling setup def redirect_on_auth_exc(request, exc): return RedirectResponse(url="/redirect") instance.not_authenticated_exception = custom_exception app.add_exception_handler(custom_exception, redirect_on_auth_exc) # routes @app.get("/private/exception") def raise_exception(_=Depends(instance)): return {"detail": "error"} @app.get("/redirect") def redirect(): return {"detail": "Redirected"} return instance
ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 DATABASE_URL = "sqlite://db/server.db" class NotAuthenticatedException(Exception): pass # these two argument are mandatory def exc_handler(request, exc): return RedirectResponse(url='/login') manager = LoginManager(SECRET_KEY, tokenUrl='/auth/token', use_cookie=True) manager.not_authenticated_exception = NotAuthenticatedException app = FastAPI() app.add_exception_handler(NotAuthenticatedException, exc_handler) app.mount("/sdk", StaticFiles(directory="templates/sdk"), name="static") templates = Jinja2Templates(directory="templates") @manager.user_loader async def load_user(email: str): # could also be an asynchronous function query = users.select().where(users.c.email == email) user = await database.fetch_one(query) return user @app.get("/current_user")