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 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) if not user: raise InvalidCredentialsException elif password != user['password']:
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) cookie_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) if not user: raise InvalidCredentialsException elif password != user['password']: raise InvalidCredentialsException access_token = manager.create_access_token(