Auth

Add Google sign-in to a Plash app

Integrating Google OAuth directly means setting up a Google Cloud project, configuring its consent screen, and managing OAuth credentials. You also need redirect URLs for development, staging, and production.

Plash Auth handles that Google-side setup for you. Your app creates a sign-in link and handles the reply containing the user's Google ID.

Tutorial

0. Setup

Before starting:

This example uses FastHTML. Other Plash apps can also use Plash Auth.

1. Create a directory

Create a directory named auth-example-app, then change into it:

cd auth-example-app

2. Create your app

Put this code in main.py:

%%writefile main.py
from fasthtml.common import *
from plash_cli.auth import *

app, rt = fast_app()

@rt
def index(session):
    if uid:=session.get('uid'):   # <1>
            return (H1(f"Welcome! You are logged in as user: {uid}"), 
                    A("Logout", href="/logout"))
    else: 
        return (
            H1("Welcome! Please sign."), 
            A("Sign in with Google", href=mk_signin_url(session)))  # <2>

@rt(signin_completed_rt)  # <3>
def signin_completed(session, signin_reply: str):
    try: 
        uid = goog_id_from_signin_reply(session, signin_reply)  # <4>
        session['uid'] = uid
        return RedirectResponse('/', status_code=303)
    except PlashAuthError as e:  # <5> 
        return Div(
            H2("Login Failed"),
            P(f"There was an error signing you in: {e}"),
            A("Try Again", href="/")
        )
    
@rt('/logout')
def logout(session):
    session.pop('uid')  # <6>
    return RedirectResponse('/', status_code=303)

serve()
Overwriting main.py
  1. Check for a user ID in the session.
  2. Create the sign-in URL.
  3. Handle the sign-in callback.
  4. Validate the reply and extract the Google user ID.
  5. Handle authentication errors.
  6. Remove the user ID from the session to log out.

3. Add requirements

Include FastHTML and plash-cli in requirements.txt:

%%writefile requirements.txt
python-fasthtml
plash-cli
Overwriting requirements.txt

4. Deploy

plash-deploy

5. Try it out

Open your deployed app:

plash-view

Sign in with Google and grant permission. The callback stores your user ID in the FastHTML session. Check that the page displays your ID, then log out.

Next steps

Local use

Running locally with python main.py uses the test user ID 424242424242424242424. It does not authenticate with Google.

Deploy a development version, such as dev-my-app.pla.sh, to test real authentication.

Restricting access

The example accepts any Google user. To restrict access, pass a regex to mk_signin_url:

User data access

Plash Auth returns the user's unique Google ID. It does not provide a name, email address, or access to Google services such as Drive and Gmail. For those, implement OAuth using FastHTML's OAuth documentation.