Skip to content

Prompt as Code | GPT Image 2 / 2.5 提示词与案例库,530+ 个案例、20+ 套工业级模板与可复用 Skills,新增 2.5 同提示词对比专区,附完整提示词与生成记录,持续更新。

Add Watcha OAuth sign-in

freestyleflyecdbcb276c2b
diff --git a/api/_lib/watcha.js b/api/_lib/watcha.js
new file mode 100644
index 0000000..85e02e8
--- /dev/null
+++ b/api/_lib/watcha.js
@@ -0,0 +1,221 @@
+import crypto from 'node:crypto';
+import { getAppUrl } from './billing.js';
+
+const WATCHA_AUTHORIZE_URL = 'https://watcha.cn/oauth/authorize';
+const WATCHA_TOKEN_URL = 'https://watcha.cn/oauth/api/token';
+const WATCHA_USERINFO_URL = 'https://watcha.cn/oauth/api/userinfo';
+const COOKIE_MAX_AGE = 10 * 60;
+
+export const WATCHA_COOKIE_NAMES = {
+ state: 'watcha_oauth_state',
+ verifier: 'watcha_oauth_verifier',
+ returnTo: 'watcha_oauth_return_to'
+};
+
+export function getWatchaConfig(req) {
+ const appUrl = getAppUrl(req);
+ const redirectUri =
+ process.env.WATCHA_REDIRECT_URI ||
+ `${appUrl}/api/auth/watcha/callback`;
+
+ return {
+ appUrl,
+ clientId: process.env.WATCHA_CLIENT_ID || '',
+ clientSecret: process.env.WATCHA_CLIENT_SECRET || '',
+ isPublicClient: process.env.WATCHA_PUBLIC_CLIENT === 'true',
+ redirectUri,
+ scope: process.env.WATCHA_SCOPE || 'read email',
+ authorizeUrl: process.env.WATCHA_AUTHORIZE_URL || WATCHA_AUTHORIZE_URL,
+ tokenUrl: process.env.WATCHA_TOKEN_URL || WATCHA_TOKEN_URL,
+ userinfoUrl: process.env.WATCHA_USERINFO_URL || WATCHA_USERINFO_URL
+ };
+}
+
+export function isWatchaConfigured(req) {
+ const config = getWatchaConfig(req);
+ return Boolean(config.clientId && (config.clientSecret || config.isPublicClient));
+}
+
+export function randomToken(byteLength = 32) {
+ return base64Url(crypto.randomBytes(byteLength));
+}
+
+export function codeChallenge(verifier) {
+ return base64Url(crypto.createHash('sha256').update(verifier).digest());
+}
+
+function base64Url(value) {
+ return Buffer.from(value)
+ .toString('base64')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/g, '');
+}
+
+export function parseCookies(req) {
+ const header = req.headers.cookie || '';
+ return Object.fromEntries(
+ header
+ .split(';')
+ .map((item) => item.trim())
+ .filter(Boolean)
+ .map((item) => {
+ const index = item.indexOf('=');
+ if (index === -1) return [item, ''];
+ return [
+ decodeURIComponent(item.slice(0, index)),
+ decodeURIComponent(item.slice(index + 1))
+ ];
+ })
+ );
+}
+
+export function cookie(name, value, options = {}) {
+ const parts = [
+ `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
+ 'Path=/',
+ 'HttpOnly',
+ 'SameSite=Lax',
+ `Max-Age=${Number(options.maxAge ?? COOKIE_MAX_AGE)}`
+ ];
+
+ if (options.secure !== false) parts.push('Secure');
+ return parts.join('; ');
+}
+
+export function clearCookie(name, options = {}) {
+ return cookie(name, '', { maxAge: 0, secure: options.secure });
+}
+
+export function watchaCookieHeaders(secure = true) {
+ return [
+ clearCookie(WATCHA_COOKIE_NAMES.state, { secure }),
+ clearCookie(WATCHA_COOKIE_NAMES.verifier, { secure }),
+ clearCookie(WATCHA_COOKIE_NAMES.returnTo, { secure })
+ ];
+}
+
+export function safeReturnTo(value, req) {
+ const appUrl = getAppUrl(req);
+ if (!value) return appUrl;
+
+ try {
+ const candidate = new URL(value, appUrl);
+ const allowed = new URL(appUrl);
+ if (candidate.origin !== allowed.origin) return appUrl;
+ return candidate.toString();
+ } catch {
+ return appUrl;
+ }
+}
+
+export function authErrorRedirect(req, code, returnTo) {
+ const target = new URL(returnTo || getAppUrl(req));
+ target.searchParams.set('auth_error', code);
+ target.searchParams.set('auth_provider', 'watcha');
+ return target.toString();
+}
+
+export function buildAuthorizeUrl(config, { state, challenge }) {
+ const url = new URL(config.authorizeUrl);
+ url.searchParams.set('response_type', 'code');
+ url.searchParams.set('client_id', config.clientId);
+ url.searchParams.set('redirect_uri', config.redirectUri);
+ url.searchParams.set('scope', config.scope);
+ url.searchParams.set('state', state);
+ url.searchParams.set('code_challenge', challenge);
+ url.searchParams.set('code_challenge_method', 'S256');
+ return url.toString();
+}
+
+export async function exchangeCodeForToken(config, { code, verifier }) {
+ const body = new URLSearchParams({
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: config.redirectUri,
+ client_id: config.clientId,
+ code_verifier: verifier
+ });
+
+ if (config.clientSecret) {
+ body.set('client_secret', config.clientSecret);
+ }
+
+ const response = await fetch(config.tokenUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ Accept: 'application/json'
+ },
+ body
+ });
+
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload?.access_token) {
+ const error = new Error(payload?.error_description || payload?.error || 'WATCHA_TOKEN_FAILED');
+ error.payload = payload;
+ error.status = response.status;
+ throw error;
+ }
+
+ return payload;
+}
+
+export async function fetchWatchaUserInfo(config, accessToken) {
+ const url = new URL(config.userinfoUrl);
+ url.searchParams.set('access_token', accessToken);
+
+ const response = await fetch(url, {
+ headers: {
+ Accept: 'application/json'
+ }
+ });
+
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || payload?.statusCode !== 200 || !payload?.data?.user_id) {
+ const error = new Error(payload?.message || 'WATCHA_USERINFO_FAILED');
+ error.payload = payload;
+ error.status = response.status;
+ throw error;
+ }
+
+ return normalizeWatchaUser(payload.data);
+}
+
+export function normalizeWatchaUser(data) {
+ const userId = String(data.user_id || '').trim();
+ const email = String(data.email || '').trim().toLowerCase();
+ const nickname = String(data.nickname || '').trim();
+ const avatarUrl = String(data.avatar_url || '').trim();
+ const phone = String(data.phone || '').trim();
+
+ return {
+ userId,
+ email: isEmail(email) ? email : '',
+ nickname,
+ avatarUrl,
+ phone
+ };
+}
+
+export function watchaFallbackEmail(userId) {
+ return `watcha-${String(userId).replace(/[^a-zA-Z0-9_-]/g, '')}@watcha.gpt-image2.canghe.ai`;
+}
+
+export function watchaUserMetadata(user) {
+ const fullName = user.nickname || `Watcha ${user.userId}`;
+ return {
+ provider: 'watcha',
+ full_name: fullName,
+ name: fullName,
+ avatar_url: user.avatarUrl || null,
+ picture: user.avatarUrl || null,
+ watcha_user_id: user.userId,
+ watcha_email: user.email || null,
+ watcha_phone: user.phone || null
+ };
+}
+
+function isEmail(value) {
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
+}
diff --git a/api/auth/watcha/callback.js b/api/auth/watcha/callback.js
new file mode 100644
index 0000000..1411705
--- /dev/null
+++ b/api/auth/watcha/callback.js
@@ -0,0 +1,176 @@
+import { ensureProfileForUser, getSupabaseAdminClient, isSupabaseServerConfigured } from '../../_lib/supabase.js';
+import {
+ authErrorRedirect,
+ exchangeCodeForToken,
+ fetchWatchaUserInfo,
+ getWatchaConfig,
+ parseCookies,
+ safeReturnTo,
+ watchaCookieHeaders,
+ WATCHA_COOKIE_NAMES,
+ watchaFallbackEmail,
+ watchaUserMetadata
+} from '../../_lib/watcha.js';
+
+function redirect(res, location, secureCookie = true) {
+ const cookies = watchaCookieHeaders(secureCookie);
+ if (cookies.length) res.setHeader('Set-Cookie', cookies);
+ res.writeHead(302, { Location: location });
+ res.end();
+}
+
+function logWatchaFailure(stage, error, extra = {}) {
+ console.warn('Watcha OAuth failed', {
+ stage,
+ message: String(error?.message || error || 'unknown').slice(0, 240),
+ status: error?.status || null,
+ ...extra
+ });
+}
+
+function tokenExpiry(expiresIn) {
+ const seconds = Number(expiresIn || 0);
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
+ return new Date(Date.now() + seconds * 1000).toISOString();
+}
+
+async function createSupabaseLoginLink(client, { email, metadata, returnTo }) {
+ const { data, error } = await client.auth.admin.generateLink({
+ type: 'magiclink',
+ email,
+ options: {
+ redirectTo: returnTo,
+ data: metadata
+ }
+ });
+
+ if (error || !data?.properties?.action_link || !data?.user) {
+ throw error || new Error('SUPABASE_LINK_FAILED');
+ }
+
+ const mergedMetadata = {
+ ...(data.user.user_metadata || {}),
+ ...metadata
+ };
+
+ const updateResult = await client.auth.admin.updateUserById(data.user.id, {
+ user_metadata: mergedMetadata
+ });
+
+ if (updateResult.error) {
+ throw updateResult.error;
+ }
+
+ const user = {
+ ...data.user,
+ email,
+ user_metadata: mergedMetadata
+ };
+
+ await ensureProfileForUser(user);
+
+ return {
+ actionLink: data.properties.action_link,
+ user
+ };
+}
+
+async function resolveWatchaLoginEmail(client, watchaUser) {
+ const { data: account, error } = await client
+ .from('watcha_accounts')
+ .select('user_id')
+ .eq('watcha_user_id', watchaUser.userId)
+ .maybeSingle();
+
+ if (error) throw error;
+
+ if (account?.user_id) {
+ const { data: profile, error: profileError } = await client
+ .from('profiles')
+ .select('email')
+ .eq('id', account.user_id)
+ .maybeSingle();
+
+ if (profileError) throw profileError;
+ if (profile?.email) return profile.email;
+ }
+
+ return watchaUser.email || watchaFallbackEmail(watchaUser.userId);
+}
+
+async function upsertWatchaAccount(client, { supabaseUserId, watchaUser, token }) {
+ const { error } = await client
+ .from('watcha_accounts')
+ .upsert(
+ {
+ user_id: supabaseUserId,
+ watcha_user_id: watchaUser.userId,
+ email: watchaUser.email || null,
+ nickname: watchaUser.nickname || null,
+ avatar_url: watchaUser.avatarUrl || null,
+ scope: token.scope || null,
+ access_token_expires_at: tokenExpiry(token.expires_in)
+ },
+ { onConflict: 'watcha_user_id' }
+ );
+
+ if (error) throw error;
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ return;
+ }
+
+ const cookies = parseCookies(req);
+ const config = getWatchaConfig(req);
+ const secureCookie = config.appUrl.startsWith('https://');
+ const returnTo = safeReturnTo(cookies[WATCHA_COOKIE_NAMES.returnTo], req);
+
+ if (req.query?.error) {
+ redirect(res, authErrorRedirect(req, 'watcha_denied', returnTo), secureCookie);
+ return;
+ }
+
+ const code = String(req.query?.code || '').trim();
+ const state = String(req.query?.state || '').trim();
+ const expectedState = cookies[WATCHA_COOKIE_NAMES.state] || '';
+ const verifier = cookies[WATCHA_COOKIE_NAMES.verifier] || '';
+
+ if (!code || !state || !expectedState || state !== expectedState || !verifier) {
+ redirect(res, authErrorRedirect(req, 'watcha_state_failed', returnTo), secureCookie);
+ return;
+ }
+
+ if (!isSupabaseServerConfigured()) {
+ redirect(res, authErrorRedirect(req, 'supabase_not_configured', returnTo), secureCookie);
+ return;
+ }
+
+ const client = getSupabaseAdminClient();
+
+ try {
+ const token = await exchangeCodeForToken(config, { code, verifier });
+ const watchaUser = await fetchWatchaUserInfo(config, token.access_token);
+ const email = await resolveWatchaLoginEmail(client, watchaUser);
+ const metadata = watchaUserMetadata(watchaUser);
+ const { actionLink, user } = await createSupabaseLoginLink(client, {
+ email,
+ metadata,
+ returnTo
+ });
+
+ await upsertWatchaAccount(client, {
+ supabaseUserId: user.id,
+ watchaUser,
+ token
+ });
+
+ redirect(res, actionLink, secureCookie);
+ } catch (error) {
+ logWatchaFailure('callback', error);
+ redirect(res, authErrorRedirect(req, 'watcha_login_failed', returnTo), secureCookie);
+ }
+}
diff --git a/api/auth/watcha/start.js b/api/auth/watcha/start.js
new file mode 100644
index 0000000..aec4ce8
--- /dev/null
+++ b/api/auth/watcha/start.js
@@ -0,0 +1,46 @@
+import {
+ authErrorRedirect,
+ buildAuthorizeUrl,
+ codeChallenge,
+ cookie,
+ getWatchaConfig,
+ randomToken,
+ safeReturnTo,
+ WATCHA_COOKIE_NAMES
+} from '../../_lib/watcha.js';
+
+function redirect(res, location, cookies = []) {
+ if (cookies.length) res.setHeader('Set-Cookie', cookies);
+ res.writeHead(302, { Location: location });
+ res.end();
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ res.status(405).json({ ok: false, error: 'METHOD_NOT_ALLOWED' });
+ return;
+ }
+
+ const config = getWatchaConfig(req);
+ const returnTo = safeReturnTo(req.query?.returnTo || req.query?.return_to, req);
+ const secureCookie = config.appUrl.startsWith('https://');
+
+ if (!config.clientId || (!config.clientSecret && !config.isPublicClient)) {
+ redirect(res, authErrorRedirect(req, 'watcha_not_configured', returnTo));
+ return;
+ }
+
+ const state = randomToken(24);
+ const verifier = randomToken(48);
+ const location = buildAuthorizeUrl(config, {
+ state,
+ challenge: codeChallenge(verifier)
+ });
+
+ redirect(res, location, [
+ cookie(WATCHA_COOKIE_NAMES.state, state, { secure: secureCookie }),
+ cookie(WATCHA_COOKIE_NAMES.verifier, verifier, { secure: secureCookie }),
+ cookie(WATCHA_COOKIE_NAMES.returnTo, returnTo, { secure: secureCookie })
+ ]);
+}
diff --git a/src/main.jsx b/src/main.jsx
index ecfaf4c..86e0952 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -39,6 +39,8 @@ import skillExampleImage from '../agents/skills/gpt-image-2-style-library/assets
const fallbackRepoUrl = 'https://github.com/freestylefly/awesome-gpt-image-2';
const gaMeasurementId = import.meta.env.VITE_GA_MEASUREMENT_ID;
+const watchaLogoUrl =
+ 'https://watcha.tos-cn-beijing.volces.com/products/logo/1752064513_guan-cha-insights.png?x-tos-process=image/resize,w_720/format,webp';
const copy = {
en: {
@@ -125,11 +127,16 @@ const copy = {
authRequired: 'Sign in to generate a test image.',
signIn: 'Sign in',
signInTitle: 'Sign in to generate test images',
- signInSubtitle: 'Use your Google account to unlock image generation, credits, and membership features.',
- authRateLimited: 'Too many login attempts. Please wait a bit, then try Google sign-in again.',
+ signInSubtitle: 'Use Google or Watcha to unlock image generation, credits, and membership features.',
+ authRateLimited: 'Too many login attempts. Please wait a bit, then try again.',
googleNotConfigured: 'Google sign-in is not enabled yet.',
continueWithGoogle: 'Continue with Google',
+ continueWithWatcha: 'Continue with Watcha',
authNotConfigured: 'Login is not configured yet.',
+ watchaNotConfigured: 'Watcha sign-in is not configured yet.',
+ watchaSessionExpired: 'Watcha sign-in expired. Please try again.',
+ watchaDenied: 'Watcha authorization was cancelled.',
+ watchaLoginFailed: 'Watcha sign-in failed. Please try again.',
authError: 'Login failed. Please try again.',
signOut: 'Sign out',
account: 'Account',
@@ -140,7 +147,7 @@ const copy = {
saveProfile: 'Save profile',
profileSaved: 'Profile saved.',
profileUpdateFailed: 'Profile update failed. Please try again.',
- googleAvatarSource: 'Avatar is synced from your Google account.',
+ googleAvatarSource: 'Avatar is synced from your login provider.',
accountOverview: 'Account overview',
totalGenerations: 'Generated tests',
totalGenerationCredits: 'Credits spent',
@@ -329,11 +336,16 @@ const copy = {
authRequired: '登录后即可生成测试图。',
signIn: '登录',
signInTitle: '登录后生成测试图',
- signInSubtitle: '使用你的 Google 账号登录,解锁生图测试、积分和会员能力。',
- authRateLimited: '登录尝试过于频繁,请稍后再使用 Google 登录。',
+ signInSubtitle: '使用 Google 或观猹登录,解锁生图测试、积分和会员能力。',
+ authRateLimited: '登录尝试过于频繁,请稍后再试。',
googleNotConfigured: 'Google 登录还没有启用。',
continueWithGoogle: '使用 Google 登录',
+ continueWithWatcha: '使用观猹登录',
authNotConfigured: '登录功能还没有完成配置。',
+ watchaNotConfigured: '观猹登录还没有完成配置。',
+ watchaSessionExpired: '观猹登录已过期,请重新尝试。',
+ watchaDenied: '已取消观猹授权。',
+ watchaLoginFailed: '观猹登录失败,请稍后再试。',
authError: '登录失败,请稍后再试。',
signOut: '退出登录',
account: '账号',
@@ -344,7 +356,7 @@ const copy = {
saveProfile: '保存资料',
profileSaved: '资料已保存。',
profileUpdateFailed: '资料保存失败,请稍后再试。',
- googleAvatarSource: '头像会同步你的 Google 账号头像。',
+ googleAvatarSource: '头像会同步你的登录账号头像。',
accountOverview: '账户概览',
totalGenerations: '生成测试数',
totalGenerationCredits: '已消耗积分',
@@ -1119,6 +1131,16 @@ function authErrorMessage(error, language) {
return message || t.authError;
}
+function authRedirectErrorMessage(code, language) {
+ const t = copy[language];
+ if (code === 'watcha_not_configured') return t.watchaNotConfigured;
+ if (code === 'supabase_not_configured') return t.authNotConfigured;
+ if (code === 'watcha_state_failed') return t.watchaSessionExpired;
+ if (code === 'watcha_denied') return t.watchaDenied;
+ if (code === 'watcha_login_failed') return t.watchaLoginFailed;
+ return t.authError;
+}
+
function GoogleIcon() {
return (
<svg className="googleIcon" viewBox="0 0 18 18" aria-hidden="true" focusable="false">
@@ -1130,7 +1152,11 @@ function GoogleIcon() {
);
}
-function AuthModal({ open, language, onClose }) {
+function WatchaIcon() {
+ return <img className="watchaIcon" src={watchaLogoUrl} alt="" aria-hidden="true" loading="lazy" />;
+}
+
+function AuthModal({ open, language, initialErrorCode, onClose }) {
const t = copy[language];
const [status, setStatus] = useState('idle');
const [message, setMessage] = useState('');
@@ -1138,13 +1164,19 @@ function AuthModal({ open, language, onClose }) {
useEffect(() => {
if (!open) return;
+ if (initialErrorCode) {
+ setStatus('error');
+ setMessage(authRedirectErrorMessage(initialErrorCode, language));
+ return;
+ }
setStatus('idle');
setMessage('');
- }, [open]);
+ }, [open, initialErrorCode, language]);
if (!open) return null;
const redirectTo = `${window.location.origin}${window.location.pathname}`;
+ const isLoading = status === 'loading-google' || status === 'loading-watcha';
async function handleGoogleSignIn() {
if (!isSupabaseConfigured || !supabase) {
@@ -1153,7 +1185,7 @@ function AuthModal({ open, language, onClose }) {
return;
}
- setStatus('loading');
+ setStatus('loading-google');
setMessage('');
const { error } = await supabase.auth.signInWithOAuth({
provider: 'google',
@@ -1168,6 +1200,18 @@ function AuthModal({ open, language, onClose }) {
}
}
+ function handleWatchaSignIn() {
+ if (!isSupabaseConfigured || !supabase) {
+ setStatus('error');
+ setMessage(t.authNotConfigured);
+ return;
+ }
+
+ setStatus('loading-watcha');
+ setMessage('');
+ window.location.assign(`/api/auth/watcha/start?returnTo=${encodeURIComponent(redirectTo)}`);
+ }
+
return (
<div
className="previewOverlay authOverlay"
@@ -1185,10 +1229,16 @@ function AuthModal({ open, language, onClose }) {
</div>
<h2 id="auth-title">{t.signInTitle}</h2>
<p>{t.signInSubtitle}</p>
- <button className="googleButton" type="button" onClick={handleGoogleSignIn} disabled={status === 'loading'}>
- {status === 'loading' ? <LoaderCircle className="spinIcon" size={18} /> : <GoogleIcon />}
- {t.continueWithGoogle}
- </button>
+ <div className="authProviders" aria-label={t.signInTitle}>
+ <button className="googleButton" type="button" onClick={handleGoogleSignIn} disabled={isLoading}>
+ {status === 'loading-google' ? <LoaderCircle className="spinIcon" size={18} /> : <GoogleIcon />}
+ {t.continueWithGoogle}
+ </button>
+ <button className="watchaButton" type="button" onClick={handleWatchaSignIn} disabled={isLoading}>
+ {status === 'loading-watcha' ? <LoaderCircle className="spinIcon" size={18} /> : <WatchaIcon />}
+ {t.continueWithWatcha}
+ </button>
+ </div>
{message ? (
<p className={cx('authMessage', status === 'error' && 'error', status === 'sent' && 'sent')}>
{message}
@@ -2942,6 +2992,7 @@ function App() {
const [favoriteBusyId, setFavoriteBusyId] = useState(null);
const [favoriteMessage, setFavoriteMessage] = useState('');
const [authOpen, setAuthOpen] = useState(false);
+ const [authErrorCode, setAuthErrorCode] = useState('');
const [accountOpen, setAccountOpen] = useState(false);
const [accountInitialSection, setAccountInitialSection] = useState('overview');
const [adminOpen, setAdminOpen] = useState(false);
@@ -2973,6 +3024,20 @@ function App() {
document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en';
}, [language]);
+ useEffect(() => {
+ const params = new URLSearchParams(window.location.search);
+ const authError = params.get('auth_error');
+ if (!authError) return;
+
+ setAuthErrorCode(authError);
+ setAuthOpen(true);
+ params.delete('auth_error');
+ params.delete('auth_provider');
+ const nextSearch = params.toString();
+ const nextUrl = `${window.location.pathname}${nextSearch ? `?${nextSearch}` : ''}${window.location.hash}`;
+ window.history.replaceState({}, '', nextUrl);
+ }, []);
+
useEffect(() => {
if (!isSupabaseConfigured || !supabase) return undefined;
@@ -3072,6 +3137,11 @@ function App() {
});
}, [siteData, styleLibrary]);
+ function openAuth() {
+ setAuthErrorCode('');
+ setAuthOpen(true);
+ }
+
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const billing = params.get('billing');
@@ -3177,7 +3247,7 @@ function App() {
async function handleToggleFavorite(caseItem) {
if (!caseItem?.id) return;
if (!session?.access_token) {
- setAuthOpen(true);
+ openAuth();
setTimedFavoriteMessage(t.signInToFavorite);
return;
}
@@ -3208,7 +3278,7 @@ function App() {
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload.ok) {
- if (payload.error === 'AUTH_REQUIRED' || payload.loginRequired) setAuthOpen(true);
+ if (payload.error === 'AUTH_REQUIRED' || payload.loginRequired) openAuth();
throw new Error(payload.error || 'FAVORITE_FAILED');
}
@@ -3276,7 +3346,7 @@ function App() {
language={language}
session={session}
profile={profile}
- onSignIn={() => setAuthOpen(true)}
+ onSignIn={openAuth}
onSignOut={handleSignOut}
onAccount={() => handleOpenAccount('overview')}
onFavorites={() => handleOpenAccount('favorites')}
@@ -3385,7 +3455,7 @@ function App() {
onOpen={(item) => setPreview({ type: 'case', item })}
onGenerate={(item) => {
setPreview({ type: 'case', item });
- if (!session?.access_token) setAuthOpen(true);
+ if (!session?.access_token) openAuth();
}}
onToggleFavorite={handleToggleFavorite}
styleLibrary={styleLibrary}
@@ -3420,7 +3490,7 @@ function App() {
onClose={() => setPreview(null)}
onCopyText={copyText}
onToggleFavorite={handleToggleFavorite}
- onAuthRequired={() => setAuthOpen(true)}
+ onAuthRequired={openAuth}
onBillingRequired={() => {
setBillingNotice(t.creditsRequired);
setBillingOpen(true);
@@ -3430,7 +3500,11 @@ function App() {
<AuthModal
open={authOpen}
language={language}
- onClose={() => setAuthOpen(false)}
+ initialErrorCode={authErrorCode}
+ onClose={() => {
+ setAuthOpen(false);
+ setAuthErrorCode('');
+ }}
/>
<AccountPanel
open={accountOpen}
@@ -3465,7 +3539,7 @@ function App() {
notice={billingNotice}
casesById={casesById}
onClose={() => setBillingOpen(false)}
- onAuthRequired={() => setAuthOpen(true)}
+ onAuthRequired={openAuth}
onProfileChange={handleProfileChange}
onOpenCase={handleOpenCaseFromAccount}
/>
diff --git a/src/styles.css b/src/styles.css
index 92a5162..44bcc56 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1878,6 +1878,7 @@ button {
}
.googleButton,
+.watchaButton,
.adminHeader button {
display: inline-flex;
align-items: center;
@@ -1892,9 +1893,14 @@ button {
font-weight: 900;
}
+.authProviders {
+ display: grid;
+ gap: 12px;
+ margin-top: 24px;
+}
+
.googleButton {
width: 100%;
- margin-top: 24px;
min-height: 44px;
border-color: #dadce0;
background: #ffffff;
@@ -1912,13 +1918,38 @@ button {
box-shadow: 0 2px 6px rgba(26, 115, 232, 0.18);
}
+.watchaButton {
+ width: 100%;
+ min-height: 44px;
+ border-color: rgba(64, 213, 117, 0.48);
+ background: linear-gradient(135deg, rgba(15, 185, 93, 0.92), rgba(5, 137, 75, 0.9));
+ color: #ffffff;
+ font-size: 14px;
+ letter-spacing: 0;
+ box-shadow: 0 10px 28px rgba(5, 137, 75, 0.22);
+}
+
+.watchaButton:hover {
+ border-color: rgba(135, 255, 183, 0.72);
+ background: linear-gradient(135deg, rgba(30, 205, 112, 0.96), rgba(7, 154, 84, 0.94));
+}
+
.googleIcon {
width: 18px;
height: 18px;
flex: 0 0 auto;
}
+.watchaIcon {
+ width: 22px;
+ height: 22px;
+ flex: 0 0 auto;
+ border-radius: 6px;
+ object-fit: cover;
+}
+
.googleButton:disabled,
+.watchaButton:disabled,
.adminHeader button:disabled {
cursor: not-allowed;
opacity: 0.6;
diff --git a/supabase/migrations/20260528090000_watcha_oauth_accounts.sql b/supabase/migrations/20260528090000_watcha_oauth_accounts.sql
new file mode 100644
index 0000000..7366ebe
--- /dev/null
+++ b/supabase/migrations/20260528090000_watcha_oauth_accounts.sql
@@ -0,0 +1,35 @@
+create table if not exists public.watcha_accounts (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references auth.users(id) on delete cascade,
+ watcha_user_id text not null,
+ email text,
+ nickname text,
+ avatar_url text,
+ scope text,
+ access_token_expires_at timestamptz,
+ linked_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (user_id),
+ unique (watcha_user_id)
+);
+
+create index if not exists watcha_accounts_user_id_idx
+ on public.watcha_accounts (user_id);
+
+create index if not exists watcha_accounts_watcha_user_id_idx
+ on public.watcha_accounts (watcha_user_id);
+
+alter table public.watcha_accounts enable row level security;
+
+grant select on public.watcha_accounts to authenticated;
+
+drop policy if exists "Users can read own watcha account" on public.watcha_accounts;
+create policy "Users can read own watcha account"
+ on public.watcha_accounts for select
+ using ((select auth.uid()) = user_id);
+
+drop trigger if exists watcha_accounts_set_updated_at on public.watcha_accounts;
+create trigger watcha_accounts_set_updated_at
+ before update on public.watcha_accounts
+ for each row
+ execute function public.set_updated_at();