|
| 1 | +#!/usr/bin/env python3 |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from authlib.integrations.starlette_client import OAuth, OAuthError |
| 5 | +from fastapi import Request |
| 6 | +from starlette.responses import RedirectResponse |
| 7 | + |
| 8 | +from nicegui import app, ui |
| 9 | + |
| 10 | +# Get the credentials from the Google Cloud Console |
| 11 | +# https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#get_your_google_api_client_id |
| 12 | +GOOGLE_CLIENT_ID = '...' |
| 13 | +GOOGLE_CLIENT_SECRET = '...' |
| 14 | + |
| 15 | +oauth = OAuth() |
| 16 | +oauth.register( |
| 17 | + name='google', |
| 18 | + server_metadata_url='https://accounts.google.com/.well-known/openid-configuration', |
| 19 | + client_id=GOOGLE_CLIENT_ID, |
| 20 | + client_secret=GOOGLE_CLIENT_SECRET, |
| 21 | + client_kwargs={'scope': 'openid email profile'}, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +@app.get('/auth') |
| 26 | +async def google_oauth(request: Request) -> RedirectResponse: |
| 27 | + try: |
| 28 | + user_data = await oauth.google.authorize_access_token(request) |
| 29 | + except OAuthError as e: |
| 30 | + print(f'OAuth error: {e}') |
| 31 | + return RedirectResponse('/') # or return an error page/message |
| 32 | + app.storage.user['user_data'] = user_data |
| 33 | + return RedirectResponse('/') |
| 34 | + |
| 35 | + |
| 36 | +def logout() -> None: |
| 37 | + del app.storage.user['user_data'] |
| 38 | + ui.navigate.to('/') |
| 39 | + |
| 40 | + |
| 41 | +@ui.page('/') |
| 42 | +async def main(request: Request) -> Optional[RedirectResponse]: |
| 43 | + user_data = app.storage.user.get('user_data', None) |
| 44 | + if user_data: |
| 45 | + ui.label(f'Welcome {user_data.get("userinfo", {}).get("name", "")}!') |
| 46 | + ui.button('Logout', on_click=logout) |
| 47 | + return None |
| 48 | + else: |
| 49 | + url = request.url_for('google_oauth') |
| 50 | + return await oauth.google.authorize_redirect(request, url) |
| 51 | + |
| 52 | +ui.run(host='localhost', storage_secret='random secret goes here') |
0 commit comments