feat: add /reset-password page
Browse filesFiles changed (3)
- app.py+158-2
- bootstrap.py+117-117
- requirements.txt+1
11 unmodified lines1213141516171819350 unmodified lines37037137237337437511 unmodified lineslogging.getLogger("uvicorn.access").setLevel(logging.WARNING)from pathlib import Pathfrom fastapi import FastAPI, Request, Depends, HTTPExceptionfrom fastapi.responses import RedirectResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.middleware.base import BaseHTTPMiddlewareimport gradio as gr350 unmodified linesprint(f"[HEALTHZ] {status}")return JSONResponse(content=status)print("[ROUTES] Root, logout, and healthz routes registered")# --- Mount Gradio UIs ---11 unmodified lines1213141516171819350 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053111 unmodified lineslogging.getLogger("uvicorn.access").setLevel(logging.WARNING)from pathlib import Pathfrom fastapi import FastAPI, Request, Depends, HTTPException, Formfrom fastapi.responses import RedirectResponse, JSONResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.middleware.base import BaseHTTPMiddlewareimport gradio as gr350 unmodified linesprint(f"[HEALTHZ] {status}")return JSONResponse(content=status)_RESET_PASSWORD_HTML = """<!DOCTYPE html><html lang="ja"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>パスワード再設定</title><style>* {{ box-sizing: border-box; margin: 0; padding: 0; }}body {{font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;background: #f5f5f5;display: flex;align-items: center;justify-content: center;min-height: 100vh;}}.card {{background: #fff;border-radius: 12px;box-shadow: 0 2px 16px rgba(0,0,0,0.1);padding: 40px;width: 100%;max-width: 400px;}}h1 {{ font-size: 1.4rem; margin-bottom: 24px; color: #333; }}label {{ display: block; font-size: 0.85rem; color: #555; margin-bottom: 6px; }}input[type=password] {{width: 100%;padding: 10px 14px;border: 1px solid #ddd;border-radius: 8px;font-size: 1rem;margin-bottom: 16px;outline: none;transition: border 0.2s;}}input[type=password]:focus {{ border-color: #f97316; }}button {{width: 100%;padding: 12px;background: #f97316;color: #fff;border: none;border-radius: 8px;font-size: 1rem;cursor: pointer;transition: background 0.2s;}}button:hover {{ background: #ea6c0a; }}.msg {{ margin-top: 16px; font-size: 0.9rem; color: #e53e3e; text-align: center; }}.msg.success {{ color: #38a169; }}</style></head><body><div class="card"><h1>🔑 パスワード再設定</h1><form method="post" action="/reset-password" id="resetForm"><input type="hidden" name="access_token" id="access_token"><input type="hidden" name="refresh_token" id="refresh_token"><label for="new_password">新しいパスワード</label><input type="password" name="new_password" id="new_password" placeholder="8文字以上" required minlength="8"><label for="confirm_password">確認(再入力)</label><input type="password" id="confirm_password" placeholder="同じパスワードを入力" required minlength="8"><button type="submit">パスワードを変更する</button></form><div class="msg" id="msg">{message}</div></div><script>// URLフラグメントからSupabaseのトークンを取得してhidden inputにセット(function() {{var hash = window.location.hash.substring(1);var params = {{}};hash.split('&').forEach(function(part) {{var kv = part.split('=');if (kv.length === 2) params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);}});if (params.access_token) {{document.getElementById('access_token').value = params.access_token;}}if (params.refresh_token) {{document.getElementById('refresh_token').value = params.refresh_token;}}if (!params.access_token && !params.refresh_token) {{document.getElementById('msg').textContent = '⚠️ 無効なリンクです。パスワードリセットメールを再送してください。';}}}})();// パスワード一致チェックdocument.getElementById('resetForm').addEventListener('submit', function(e) {{var pw = document.getElementById('new_password').value;var cpw = document.getElementById('confirm_password').value;if (pw !== cpw) {{e.preventDefault();document.getElementById('msg').textContent = '❌ パスワードが一致しません。';}}}});</script></body></html>"""@app.get("/reset-password")async def reset_password_page():"""パスワード再設定フォームを表示"""return HTMLResponse(_RESET_PASSWORD_HTML.format(message=""))@app.post("/reset-password")async def reset_password_submit(access_token: str = Form(default=""),refresh_token: str = Form(default=""),new_password: str = Form(...),):"""パスワード再設定を実行"""if not access_token:html = _RESET_PASSWORD_HTML.format(message="❌ トークンが取得できませんでした。メールのリンクを再度クリックしてください。")return HTMLResponse(html, status_code=400)if len(new_password) < 8:html = _RESET_PASSWORD_HTML.format(message="❌ パスワードは8文字以上で設定してください。")return HTMLResponse(html, status_code=400)try:supabase.auth.set_session(access_token, refresh_token)supabase.auth.update_user({"password": new_password})log_event("auth", "password_reset_success")success_html = """<!DOCTYPE html><html lang="ja"><head><meta charset="UTF-8"><meta http-equiv="refresh" content="3;url=/login/"><title>パスワード変更完了</title><style>body {{ font-family: -apple-system, sans-serif; display: flex; align-items: center;justify-content: center; min-height: 100vh; background: #f5f5f5; }}.card {{ background: #fff; border-radius: 12px; padding: 40px; text-align: center;box-shadow: 0 2px 16px rgba(0,0,0,0.1); max-width: 360px; width: 100%; }}h1 {{ color: #38a169; margin-bottom: 12px; }}p {{ color: #555; font-size: 0.95rem; }}</style></head><body><div class="card"><h1>✅ パスワードを変更しました</h1><p>3秒後にログイン画面に移動します...</p><p><a href="/login/">今すぐログイン画面へ</a></p></div></body></html>"""return HTMLResponse(success_html)except Exception as e:print(f"[AUTH] Password reset failed: {e}")log_event("auth", "password_reset_failure", level="WARNING", metadata={"error": str(e)})html = _RESET_PASSWORD_HTML.format(message=f"❌ エラーが発生しました: {str(e)}")return HTMLResponse(html, status_code=400)print("[ROUTES] Root, logout, and healthz routes registered")# --- Mount Gradio UIs ---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117#!/usr/bin/env python3"""Bootstrap module - Downloads ver20 from private DLPO/habadashi Space"""import osfrom pathlib import Pathfrom huggingface_hub import snapshot_downloaddef get_hf_token():"""Get HF_TOKEN from environment variable"""token = os.environ.get("HF_TOKEN")if not token:print("[BOOTSTRAP_ERROR] HF_TOKEN not found in environment")raise ValueError("HF_TOKEN not found. Please set HF_TOKEN environment variable ""in HF Space Secrets to access private repository.")print(f"[BOOTSTRAP] HF_TOKEN found (length: {len(token)}, 末尾3文字: ...{token[-3:]})")return tokendef download_private_app(force_download: bool = False):"""Download ver20 application from private DLPO/habadashi SpaceArgs:force_download: If True, re-download even if already cachedReturns:Path: Local directory containing downloaded ver20 files"""repo_id = "DLPO/habadashi"repo_type = "space"local_dir = Path("./private_app")print(f"[BOOTSTRAP] Starting download")print(f"[BOOTSTRAP] repo_id={repo_id} repo_type={repo_type}")print(f"[BOOTSTRAP] local_dir={local_dir} force_download={force_download}")print(f"[BOOTSTRAP] local_dir.exists()={local_dir.exists()}")# Check if already downloaded (skip if exists and not forced)if local_dir.exists() and not force_download:# Verify essential files existapp_py = local_dir / "app.py"print(f"[BOOTSTRAP] Checking cache: app.py exists={app_py.exists()}")if app_py.exists():print(f"[BOOTSTRAP] Using cached download: {local_dir}")# Verify structure_verify_downloaded_structure(local_dir)return local_direlse:print(f"[BOOTSTRAP] Cache invalid (app.py missing), will re-download")print(f"[BOOTSTRAP] Starting fresh download from {repo_id}...")try:token = get_hf_token()# Download entire Space repository (removed local_dir_use_symlinks - deprecated)print(f"[BOOTSTRAP] Calling snapshot_download...")snapshot_download(repo_id=repo_id,repo_type=repo_type,local_dir=str(local_dir),token=token,)print(f"[BOOTSTRAP] Download complete: {local_dir}")# Verify essential structure_verify_downloaded_structure(local_dir)return local_direxcept Exception as e:print(f"[BOOTSTRAP_ERROR] Download failed: {e}")import tracebackprint(f"[TRACEBACK]\n{traceback.format_exc()}")raisedef _verify_downloaded_structure(local_dir: Path):"""Verify downloaded structure has essential components"""print(f"[BOOTSTRAP_VERIFY] Checking downloaded structure...")essential_files = ["app.py","requirements.txt",]essential_dirs = ["lib","exec","core","presentation",]for file_name in essential_files:file_path = local_dir / file_nameexists = file_path.exists()print(f"[BOOTSTRAP_VERIFY] {file_name}: {'EXISTS' if exists else 'MISSING'}")if not exists and file_name == "app.py":raise FileNotFoundError(f"Critical file missing: {file_name}. "f"Expected at: {file_path}")for dir_name in essential_dirs:dir_path = local_dir / dir_nameexists = dir_path.exists() and dir_path.is_dir()print(f"[BOOTSTRAP_VERIFY] {dir_name}/: {'EXISTS' if exists else 'MISSING'}")print(f"[BOOTSTRAP_VERIFY] Verification complete")if __name__ == "__main__":# Test downloaddownload_private_app()print("🎉 Bootstrap test successful!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117#!/usr/bin/env python3"""Bootstrap module - Downloads ver20 from private DLPO/habadashi Space"""import osfrom pathlib import Pathfrom huggingface_hub import snapshot_downloaddef get_hf_token():"""Get HF_TOKEN from environment variable"""token = os.environ.get("HF_TOKEN")if not token:print("[BOOTSTRAP_ERROR] HF_TOKEN not found in environment")raise ValueError("HF_TOKEN not found. Please set HF_TOKEN environment variable ""in HF Space Secrets to access private repository.")print(f"[BOOTSTRAP] HF_TOKEN found (length: {len(token)}, 末尾3文字: ...{token[-3:]})")return tokendef download_private_app(force_download: bool = False):"""Download ver20 application from private DLPO/habadashi SpaceArgs:force_download: If True, re-download even if already cachedReturns:Path: Local directory containing downloaded ver20 files"""repo_id = "DLPO/habadashi"repo_type = "space"local_dir = Path("./private_app")print(f"[BOOTSTRAP] Starting download")print(f"[BOOTSTRAP] repo_id={repo_id} repo_type={repo_type}")print(f"[BOOTSTRAP] local_dir={local_dir} force_download={force_download}")print(f"[BOOTSTRAP] local_dir.exists()={local_dir.exists()}")# Check if already downloaded (skip if exists and not forced)if local_dir.exists() and not force_download:# Verify essential files existapp_py = local_dir / "app.py"print(f"[BOOTSTRAP] Checking cache: app.py exists={app_py.exists()}")if app_py.exists():print(f"[BOOTSTRAP] Using cached download: {local_dir}")# Verify structure_verify_downloaded_structure(local_dir)return local_direlse:print(f"[BOOTSTRAP] Cache invalid (app.py missing), will re-download")print(f"[BOOTSTRAP] Starting fresh download from {repo_id}...")try:token = get_hf_token()# Download entire Space repository (removed local_dir_use_symlinks - deprecated)print(f"[BOOTSTRAP] Calling snapshot_download...")snapshot_download(repo_id=repo_id,repo_type=repo_type,local_dir=str(local_dir),token=token,)print(f"[BOOTSTRAP] Download complete: {local_dir}")# Verify essential structure_verify_downloaded_structure(local_dir)return local_direxcept Exception as e:print(f"[BOOTSTRAP_ERROR] Download failed: {e}")import tracebackprint(f"[TRACEBACK]\n{traceback.format_exc()}")raisedef _verify_downloaded_structure(local_dir: Path):"""Verify downloaded structure has essential components"""print(f"[BOOTSTRAP_VERIFY] Checking downloaded structure...")essential_files = ["app.py","requirements.txt",]essential_dirs = ["lib","exec","core","presentation",]for file_name in essential_files:file_path = local_dir / file_nameexists = file_path.exists()print(f"[BOOTSTRAP_VERIFY] {file_name}: {'EXISTS' if exists else 'MISSING'}")if not exists and file_name == "app.py":raise FileNotFoundError(f"Critical file missing: {file_name}. "f"Expected at: {file_path}")for dir_name in essential_dirs:dir_path = local_dir / dir_nameexists = dir_path.exists() and dir_path.is_dir()print(f"[BOOTSTRAP_VERIFY] {dir_name}/: {'EXISTS' if exists else 'MISSING'}")print(f"[BOOTSTRAP_VERIFY] Verification complete")if __name__ == "__main__":# Test downloaddownload_private_app()print("🎉 Bootstrap test successful!")
4 unmodified lines56789104 unmodified linessupabasepython-multiparthuggingface_hub# ver20 dependencies (from ver20/requirements.txt)gradio_client4 unmodified lines5678910114 unmodified linessupabasepython-multiparthuggingface_hubpython-dotenv# ver20 dependencies (from ver20/requirements.txt)gradio_client
app.py+158-2
bootstrap.py+117-117
requirements.txt+1