|
| 1 | +from urllib.parse import quote_plus, urlencode |
| 2 | + |
| 3 | +from fastapi import APIRouter, Request |
| 4 | +from fastapi.responses import RedirectResponse |
| 5 | + |
| 6 | +from auth.config import auth0_config, oauth |
| 7 | + |
| 8 | + |
| 9 | +auth_router = APIRouter() |
| 10 | + |
| 11 | + |
| 12 | +@auth_router.get("/login") |
| 13 | +async def login(request: Request): |
| 14 | + """ |
| 15 | + Redirects the user to the Auth0 Universal Login (https://auth0.com/docs/authenticate/login/auth0-universal-login) |
| 16 | + """ |
| 17 | + if 'id_token' not in request.session: # it could be userinfo instead of id_token |
| 18 | + return await oauth.auth0.authorize_redirect( |
| 19 | + request, |
| 20 | + redirect_uri=request.url_for("callback") |
| 21 | + ) |
| 22 | + return RedirectResponse(url=request.url_for("profile")) |
| 23 | + |
| 24 | + |
| 25 | +@auth_router.get("/signup") |
| 26 | +async def signup(request: Request): |
| 27 | + """ |
| 28 | + Redirects the user to the Auth0 Universal Login (https://auth0.com/docs/authenticate/login/auth0-universal-login) |
| 29 | + """ |
| 30 | + if 'id_token' not in request.session: # it could be userinfo instead of id_token |
| 31 | + return await oauth.auth0.authorize_redirect( |
| 32 | + request, |
| 33 | + redirect_uri=request.url_for("callback"), |
| 34 | + screen_hint="signup" |
| 35 | + ) |
| 36 | + return RedirectResponse(url=request.url_for("profile")) |
| 37 | + |
| 38 | + |
| 39 | +@auth_router.get("/logout") |
| 40 | +def logout(request: Request): |
| 41 | + """ |
| 42 | + Redirects the user to the Auth0 Universal Login (https://auth0.com/docs/authenticate/login/auth0-universal-login) |
| 43 | + """ |
| 44 | + response = RedirectResponse( |
| 45 | + url="https://" + auth0_config['DOMAIN'] |
| 46 | + + "/v2/logout?" |
| 47 | + + urlencode( |
| 48 | + { |
| 49 | + "returnTo": request.url_for("home"), |
| 50 | + "client_id": auth0_config['CLIENT_ID'], |
| 51 | + }, |
| 52 | + quote_via=quote_plus, |
| 53 | + ) |
| 54 | + ) |
| 55 | + request.session.clear() |
| 56 | + return response |
| 57 | + |
| 58 | + |
| 59 | +@auth_router.get("/callback") |
| 60 | +async def callback(request: Request): |
| 61 | + """ |
| 62 | + Callback redirect from Auth0 |
| 63 | + """ |
| 64 | + token = await oauth.auth0.authorize_access_token(request) |
| 65 | + # Store `id_token`, and `userinfo` in session |
| 66 | + request.session['id_token'] = token['id_token'] |
| 67 | + request.session['userinfo'] = token['userinfo'] |
| 68 | + return RedirectResponse(url=request.url_for("profile")) |
0 commit comments