def header_manager(app, secret, token_url, load_user_fn) -> LoginManager: instance = LoginManager(secret, token_url) instance.user_loader(load_user_fn) @app.get("/private/header") def private_header_route(_=Depends(instance)): return {"detail": "Success"} return instance
def cookie_manager(app, secret, token_url, load_user_fn) -> LoginManager: instance = LoginManager(secret, token_url, use_cookie=True, use_header=False) instance.user_loader(load_user_fn) @app.get("/private/cookie") def private_cookie_route(_=Depends(instance)): return {"detail": "Success"} return instance
def middleware_manager(app, token_url, load_user_fn): instance = LoginManager("secret", "/auth/token") instance.user_loader(load_user_fn) instance.useRequest(app) @app.get("/private/request") def private_request_route(request: Request): user = request.state.user if user is None: raise InvalidCredentialsException else: return {"detail": "Success"} return instance
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
pass def handle_exc(request, exc): print(request, exc) return RedirectResponse(url='/redirect') # app setup app = FastAPI() app.add_exception_handler(NotAuthenticatedException, handle_exc) # Manager setup manager = LoginManager(SECRET, tokenUrl=TOKEN_URL) cookie_manager = LoginManager(SECRET, tokenUrl=TOKEN_URL, use_cookie=True) manager.user_loader(load_user) cookie_manager.user_loader(load_user) manager.useRequest(app) # routes @app.post(TOKEN_URL) def login(response: Response, data: OAuth2PasswordRequestForm = Depends(), cookie=Optional[bool]): user_identifier = data.username password = data.password user = load_user(user_identifier)