Deploy habadashi_login gateway
Browse filesFiles changed (6)
- LOCAL_TESTING.mdAdded+119
- README.md+37-12
- app.pyAdded+148
- bootstrap.pyAdded+75
- login.pyAdded+52
- requirements.txtAdded+18
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119# Habadashi Login Gateway - Local Testing Guide
## Prerequisites
1. Environment variables must be set:
- `SUPABASE_URL`: Your Supabase project URL
- `SUPABASE_KEY`: Your Supabase anon/service key
- `HF_TOKEN`: Hugging Face token with access to private `DLPO/habadashi` Space
- `OPENAI_KEY`: OpenAI API key (required by ver20)
- `CLIENTPOOL`: Client pool configuration (required by ver20)
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Local Testing Steps
### Step 1: Set environment variables
**PowerShell (Windows):**
```powershell
$env:SUPABASE_URL="your-supabase-url"
$env:SUPABASE_KEY="your-supabase-key"
$env:HF_TOKEN="your-hf-token"
$env:OPENAI_KEY="your-openai-key"
$env:CLIENTPOOL="your-client-pool"
```
**Bash (Linux/Mac):**
```bash
export SUPABASE_URL="your-supabase-url"
export SUPABASE_KEY="your-supabase-key"
export HF_TOKEN="your-hf-token"
export OPENAI_KEY="your-openai-key"
export CLIENTPOOL="your-client-pool"
```
### Step 2: Test bootstrap (download private app)
```bash
python bootstrap.py
```
Expected output:
- `π Downloading private app from DLPO/habadashi...`
- `β
Download complete: ./private_app`
- `π Bootstrap test successful!`
This will create a `./private_app/` directory with ver20 files.
### Step 3: Start the application
```bash
uvicorn app:app --host 0.0.0.0 --port 7860
```
Or use Gradio's default launch (if app.py is configured to run directly):
```bash
python app.py
```
### Step 4: Verify routes
1. **Root route**: http://localhost:7860/
- Should redirect to `/login/` if not authenticated
- Should redirect to `/app/` if authenticated
2. **Login UI**: http://localhost:7860/login/
- Enter email and password
- On success, should set cookie and redirect to `/app/`
3. **Protected app**: http://localhost:7860/app/
- Should show ver20 Gradio interface if authenticated
- Should redirect to login if not authenticated
4. **Logout**: http://localhost:7860/logout
- Should clear cookie and redirect to `/login/`
## Troubleshooting
### Issue: "HF_TOKEN not found"
- Make sure `HF_TOKEN` is set in environment variables
- Verify token has access to private `DLPO/habadashi` Space
### Issue: "Failed to import ver20 app"
- Check that `./private_app/app.py` exists
- Verify ver20's `app.py` exports `app` variable (Gradio Blocks instance)
- Check Python path is correctly set
### Issue: "SUPABASE_URL and SUPABASE_KEY must be set"
- Set both environment variables before running the app
### Issue: Cookie not persisting (localhost HTTP)
- For local development, you may need to modify cookie settings in `login.py`
- Remove `Secure` flag for HTTP testing: `SameSite=Lax;` (remove `Secure;`)
## Deployment to HF Space
Once local testing is successful, deploy to public HF Space:
1. Create new public Space: `DLPO/habadashi_login`
2. Set secrets in Space settings:
- `SUPABASE_URL`
- `SUPABASE_KEY`
- `HF_TOKEN`
- `OPENAI_KEY`
- `CLIENTPOOL`
3. Upload files:
- `app.py`
- `bootstrap.py`
- `login.py`
- `requirements.txt`
- `README.md`
The Space will automatically:
1. Download ver20 from private `DLPO/habadashi` on startup
2. Mount login UI at `/login/`
3. Mount ver20 app at `/app/` (protected by auth)12345678910111212345678910111213141516171819202122232425262728293031323334353637---title: Habadashi Loginemoji: π₯colorFrom: indigocolorTo: greensdk: gradiosdk_version: 6.6.0app_file: app.pypinned: false---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference---
title: Habadashi Login Gateway
emoji: π
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: 5.49.1
app_file: app.py
pinned: false
---
# Habadashi Login Gateway
Public gateway with Supabase authentication that dynamically loads the private ver20 application from `DLPO/habadashi` Space.
## Features
- Supabase email/password authentication
- Cookie-based session management
- Dynamic loading of private application code (source code not exposed in public repo)
- Role-based access control via profiles table
## Environment Variables (Set in HF Space Secrets)
- `SUPABASE_URL`: Your Supabase project URL
- `SUPABASE_KEY`: Your Supabase anon/service key
- `HF_TOKEN`: Hugging Face token with access to private `DLPO/habadashi` Space
- `OPENAI_KEY`: OpenAI API key (required by ver20)
- `CLIENTPOOL`: Client pool configuration (required by ver20)
## Architecture
1. User visits public Space
2. Bootstrap downloads ver20 from private `DLPO/habadashi` Space
3. User logs in with Supabase credentials
4. On successful login, ver20 Gradio app is mounted at `/app/`
5. User profile and organization info loaded from `profiles` table123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148#!/usr/bin/env python3
"""
Habadashi Login Gateway - Main entry point
Public Space that loads private ver20 app dynamically
"""
import os
import sys
from pathlib import Path
from fastapi import FastAPI, Request, Depends, HTTPException
from fastapi.responses import RedirectResponse
import gradio as gr
from supabase import create_client, Client
# Import bootstrap to download private app
from bootstrap import download_private_app
from login import create_login_ui
# --- Bootstrap: Download private app at startup ---
print("π Starting Habadashi Login Gateway...")
try:
private_app_dir = download_private_app()
# Add private app to Python path so we can import it
private_app_path = str(private_app_dir.resolve())
if private_app_path not in sys.path:
sys.path.insert(0, private_app_path)
print(f"β
Added to Python path: {private_app_path}")
except Exception as e:
print(f"β Failed to bootstrap private app: {e}")
print("β οΈ Application will start but /app/ route will not work")
private_app_dir = None
# --- Supabase Setup ---
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
if not SUPABASE_URL or not SUPABASE_KEY:
raise ValueError(
"SUPABASE_URL and SUPABASE_KEY must be set in environment variables. "
"Please configure them in HF Space Secrets."
)
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
# --- FastAPI App ---
app = FastAPI()
# --- Authentication Handler (for login UI) ---
def handle_login(email, password):
"""Handle login attempt via Supabase"""
try:
res = supabase.auth.sign_in_with_password({"email": email, "password": password})
if res.session:
return (
gr.update(visible=False),
gr.update(visible=True, value=f"### β
γγ°γ€γ³ζε: {email}"),
res.session.access_token
)
except Exception as e:
return gr.update(), gr.update(value=f"β γ¨γ©γΌ: {str(e)}"), None
# --- Authentication Dependency ---
def get_current_user(request: Request):
"""Verify token from cookie and fetch user profile"""
token = request.cookies.get("sb_access_token")
print(f"--- Auth Check ---")
print(f"Token present: {bool(token)}")
if not token:
return None
try:
# Verify token with Supabase
res = supabase.auth.get_user(token)
user_id = res.user.id
# Fetch profile from profiles table (with organization name)
profile_res = supabase.from_("profiles").select(
"email, org_id, role, display_name, organizations(name)"
).eq("id", user_id).single().execute()
profile_data = profile_res.data
user_dict = {
"user_id": user_id,
"email": profile_data.get("email"),
"display_name": profile_data.get("display_name"),
"role": profile_data.get("role"),
"org_name": (profile_data.get("organizations") or {}).get("name")
}
print(f"Auth Success: {user_dict['email']}")
return user_dict
except Exception as e:
print(f"Auth Error: {e}")
return None
# --- Create UI instances ---
login_ui = create_login_ui(handle_login)
# Import ver20 app (Gradio Blocks)
ver20_app = None
if private_app_dir:
try:
# Import app module from downloaded private app
from app import app as ver20_blocks
ver20_app = ver20_blocks
print("β
Successfully imported ver20 Gradio app")
except Exception as e:
print(f"β Failed to import ver20 app: {e}")
print(f" Make sure ver20/app.py exports 'app' variable (Gradio Blocks)")
# --- Routes ---
@app.get("/")
async def root(user=Depends(get_current_user)):
"""Root route - redirect to login or app based on auth status"""
if isinstance(user, dict) and user.get("user_id"):
return RedirectResponse(url="/app/")
return RedirectResponse(url="/login/")
@app.get("/logout")
async def logout():
"""Logout route - clear cookie and redirect to login"""
response = RedirectResponse(url="/login/")
response.delete_cookie("sb_access_token")
return response
# --- Mount Gradio UIs ---
# Login UI (public)
app = gr.mount_gradio_app(app, login_ui, path="/login")
# Ver20 App (protected)
if ver20_app:
app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)
print("β
Mounted ver20 app at /app/ (protected)")
else:
# Fallback: simple placeholder if ver20 failed to load
with gr.Blocks() as fallback_ui:
gr.Markdown("# β οΈ Application Not Available")
gr.Markdown("The private application failed to load. Please check logs.")
app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)
print("β οΈ Mounted fallback UI at /app/ (ver20 failed to load)")
print("π Habadashi Login Gateway ready!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#!/usr/bin/env python3
"""
Bootstrap module - Downloads ver20 from private DLPO/habadashi Space
"""
import os
from pathlib import Path
from huggingface_hub import snapshot_download
def get_hf_token():
"""Get HF_TOKEN from environment variable"""
token = os.environ.get("HF_TOKEN")
if not token:
raise ValueError(
"HF_TOKEN not found. Please set HF_TOKEN environment variable "
"in HF Space Secrets to access private repository."
)
return token
def download_private_app(force_download: bool = False):
"""
Download ver20 application from private DLPO/habadashi Space
Args:
force_download: If True, re-download even if already cached
Returns:
Path: Local directory containing downloaded ver20 files
"""
repo_id = "DLPO/habadashi"
repo_type = "space"
local_dir = Path("./private_app")
# Check if already downloaded (skip if exists and not forced)
if local_dir.exists() and not force_download:
# Verify essential files exist
app_py = local_dir / "app.py"
if app_py.exists():
print(f"β
Private app already downloaded: {local_dir}")
return local_dir
print(f"π Downloading private app from {repo_id}...")
try:
token = get_hf_token()
# Download entire Space repository
snapshot_download(
repo_id=repo_id,
repo_type=repo_type,
local_dir=str(local_dir),
local_dir_use_symlinks=False,
token=token,
)
print(f"β
Download complete: {local_dir}")
# Verify essential structure
app_py = local_dir / "app.py"
if not app_py.exists():
raise FileNotFoundError(
f"app.py not found in downloaded repository. "
f"Expected at: {app_py}"
)
return local_dir
except Exception as e:
print(f"β Failed to download private app: {e}")
raise
if __name__ == "__main__":
# Test download
download_private_app()
print("π Bootstrap test successful!")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import gradio as gr
def create_login_ui(handle_login_fn):
"""
Create Gradio login UI
Args:
handle_login_fn: Function to handle login (email, password) -> (form_update, status_update, token)
Returns:
Gradio Blocks UI for login
"""
with gr.Blocks(title="Login") as ui:
gr.Markdown("# π Habadashi Login")
with gr.Column(visible=True) as login_form:
email_input = gr.Textbox(label="Email")
pass_input = gr.Textbox(label="Password", type="password")
login_btn = gr.Button("Login", variant="primary")
status_msg = gr.Markdown("")
# Hidden textbox to store token and trigger cookie setting via JS
token_storage = gr.Textbox(visible=False, elem_id="token_storage")
# External login handler (from app.py) is bound here
login_btn.click(
handle_login_fn,
inputs=[email_input, pass_input],
outputs=[login_form, status_msg, token_storage]
)
# When token is set, use JavaScript to save cookie and redirect
token_storage.change(
None,
inputs=[token_storage],
js="""(token) => {
if (!token || token === "") return;
// Set cookie
document.cookie = `sb_access_token=${token}; path=/; max-age=3600; SameSite=None; Secure;`;
console.log("Cookie set, redirecting...");
// Wait briefly then redirect
setTimeout(() => {
window.location.href = '/app/';
}, 200);
}"""
)
return ui123456789101112131415161718# Public Gateway dependencies
fastapi
uvicorn
gradio
supabase
python-multipart
huggingface_hub
# ver20 dependencies (from ver20/requirements.txt)
gradio_client
requests
openai
Pillow
matplotlib
scipy
pyyaml
pytest
pytest-covLOCAL_TESTING.mdAdded+119
README.md+37-12
app.pyAdded+148
bootstrap.pyAdded+75
login.pyAdded+52
requirements.txtAdded+18