main.py 1.7 KB

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