|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import httpx |
| 3 | +from fastapi import Form, HTTPException |
| 4 | +from fastapi.responses import RedirectResponse |
| 5 | + |
| 6 | +from nicegui import app, ui |
| 7 | + |
| 8 | +# Get your Google Client ID from the Google Cloud Console. |
| 9 | +# For local development, you should add http://localhost:8080 to the authorized JavaScript origins. |
| 10 | +# In production, you should add the domain of your website to the authorized JavaScript origins. |
| 11 | +# See https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#get_your_google_api_client_id. |
| 12 | +GOOGLE_CLIENT_ID = '484798726913-t4es9ner8aglom3miptbnq1m23dsqagi.apps.googleusercontent.com' |
| 13 | + |
| 14 | + |
| 15 | +@ui.page('/') |
| 16 | +def main_page() -> None: |
| 17 | + user_data = app.storage.user.get('user_data', None) |
| 18 | + if not user_data: |
| 19 | + ui.add_head_html('<script src="https://accounts.google.com/gsi/client" async defer></script>') |
| 20 | + ui.html(f''' |
| 21 | + <div id="g_id_onload" |
| 22 | + data-client_id="{GOOGLE_CLIENT_ID}" |
| 23 | + data-login_uri="http://localhost:8080/auth"> |
| 24 | + </div> |
| 25 | + ''') |
| 26 | + ui.label('Sign in with Google One Tap') |
| 27 | + else: |
| 28 | + ui.label(f'Welcome {user_data["name"]}!') |
| 29 | + ui.button('Logout', on_click=logout) |
| 30 | + |
| 31 | + |
| 32 | +def logout() -> None: |
| 33 | + del app.storage.user['user_data'] |
| 34 | + ui.navigate.to('/') |
| 35 | + |
| 36 | + |
| 37 | +@app.post('/auth') |
| 38 | +async def google_auth(credential: str = Form(...)) -> RedirectResponse: |
| 39 | + async with httpx.AsyncClient() as http_client: |
| 40 | + response = await http_client.get(f'https://oauth2.googleapis.com/tokeninfo?id_token={credential}') |
| 41 | + if response.status_code != 200: |
| 42 | + raise HTTPException(status_code=400, detail='Invalid token') |
| 43 | + app.storage.user['user_data'] = response.json() |
| 44 | + return RedirectResponse('/', status_code=303) |
| 45 | + |
| 46 | +ui.run(host='localhost', storage_secret='here you should pick a random secret string for your app') |
0 commit comments