Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Google one-tap authentication example #3244

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ venv
.nicegui/
*.sqlite*
.DS_Store
.env
53 changes: 53 additions & 0 deletions examples/google-one-tap-auth/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
import os

import httpx
from dotenv import load_dotenv
from fastapi import Form, HTTPException, Request
from fastapi.responses import RedirectResponse

from nicegui import Client, app, core, ui

# Get your Google Client ID from the Google Cloud Console
# https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#get_your_google_api_client_id
# and pass it as an environment variable (or write it to an .env file)
load_dotenv()
GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID', '')


@ui.page('/')
def main_page(request: Request):
assert request.url.hostname
assert core.air
assert core.air.remote_url
if 'on-air.io' not in request.url.hostname:
return RedirectResponse(core.air.remote_url)

if not GOOGLE_CLIENT_ID:
ui.label('Please set the GOOGLE_CLIENT_ID environment variable')
return

ui.add_head_html('<script src="https://accounts.google.com/gsi/client" async defer></script>')
ui.html(f'''
<div id="g_id_onload"
data-client_id="{GOOGLE_CLIENT_ID}"
data-login_uri="{core.air.remote_url}auth/google">
</div>''')
ui.label('Sign in with Google One Tap')


@app.post('/auth/google')
async def google_auth(request: Request, credential: str = Form(...)):
async with httpx.AsyncClient() as http_client:
response = await http_client.get(f'https://oauth2.googleapis.com/tokeninfo?id_token={credential}')
if response.status_code != 200:
raise HTTPException(status_code=400, detail='Invalid token')
user_data = response.json()
with Client(ui.page('')) as nicegui_client:
ui.label(f'Welcome {user_data["name"]}!')
return nicegui_client.build_response(request, 404)

# NOTE we use NiceGUI On Air (https://nicegui.io/documentation/section_configuration_deployment#nicegui_on_air)
# to make the local server available to google one-tap auth
# if you deploy your app on a server, you can remove the whole On Air part
ui.run(on_air=True, storage_secret='THIS_NEEDS_TO_BE_CHANGED')
Loading