Skip to content

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

Add Supabase auth and credits foundation

freestylefly92d782e5ebb9
diff --git a/.env.example b/.env.example
index b4a0a8a..3f6165e 100644
--- a/.env.example
+++ b/.env.example
@@ -1,4 +1,7 @@
CIYUAN_API_KEY=
-CIYUAN_BASE_URL=https://ciyuan.it.com
-UPSTASH_REDIS_REST_URL=
-UPSTASH_REDIS_REST_TOKEN=
+CIYUAN_BASE_URL=https://ciyuan.today
+
+VITE_SUPABASE_URL=
+VITE_SUPABASE_ANON_KEY=
+SUPABASE_SERVICE_ROLE_KEY=
diff --git a/README.md b/README.md
index 5a45552..8474c4f 100644
--- a/README.md
+++ b/README.md
@@ -271,6 +271,29 @@ npm run install:skill
The skill source lives at [`agents/skills/gpt-image-2-style-library`](agents/skills/gpt-image-2-style-library/SKILL.md). Its generated reference comes from [`data/style-library.json`](data/style-library.json), so the website and Agent workflow share one style library.
+## 🔐 Website Auth & Generation
+
+The visual site includes login-gated case generation powered by Supabase Auth, Supabase Postgres, and a Vercel Function proxy for the GPT Image 2 API.
+
+Required Vercel environment variables:
+
+```bash
+VITE_SUPABASE_URL=
+VITE_SUPABASE_ANON_KEY=
+SUPABASE_SERVICE_ROLE_KEY=
+CIYUAN_API_KEY=
+CIYUAN_BASE_URL=https://ciyuan.today
+```
+
+Setup checklist:
+
+- Apply [`supabase/migrations/202605090001_user_credits.sql`](supabase/migrations/202605090001_user_credits.sql) to the Supabase project.
+- Add `https://gpt-image2.canghe.ai` and local dev URLs such as `http://127.0.0.1:5173` to Supabase Auth redirect URLs.
+- Enable Email OTP or magic links in Supabase Auth.
+- Enable the Google Provider after adding Google OAuth credentials in the Supabase Dashboard.
+- Keep `SUPABASE_SERVICE_ROLE_KEY` only in server-side environments such as Vercel Environment Variables.
+
<a name="section-gallery"></a>
## 🖼️ Featured Cases
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 52dc79e..20d7168 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -269,6 +269,29 @@ npm run install:skill
skill 源码位于 [`agents/skills/gpt-image-2-style-library`](agents/skills/gpt-image-2-style-library/SKILL.md)。生成索引来自 [`data/style-library.json`](data/style-library.json),网站和 Agent 工作流共用这一份风格库。
+## 🔐 网站登录与生成测试
+
+可视化网站已经接入登录后生成测试图能力,底层使用 Supabase Auth、Supabase Postgres,以及 Vercel Function 代理 GPT Image 2 API。
+
+Vercel 需要配置这些环境变量:
+
+```bash
+VITE_SUPABASE_URL=
+VITE_SUPABASE_ANON_KEY=
+SUPABASE_SERVICE_ROLE_KEY=
+CIYUAN_API_KEY=
+CIYUAN_BASE_URL=https://ciyuan.today
+```
+
+配置清单:
+
+- 将 [`supabase/migrations/202605090001_user_credits.sql`](supabase/migrations/202605090001_user_credits.sql) 应用到 Supabase 项目。
+- 在 Supabase Auth Redirect URLs 里加入 `https://gpt-image2.canghe.ai`,以及 `http://127.0.0.1:5173` 等本地开发地址。
+- 在 Supabase Auth 里开启邮箱 OTP 或魔法链接。
+- Google Provider 的代码入口已接好,后续在 Supabase Dashboard 填入 Google OAuth 凭据后即可使用。
+- `SUPABASE_SERVICE_ROLE_KEY` 只放在 Vercel Environment Variables 这类服务端环境里。
+
<a name="section-gallery"></a>
## 🖼️ 首页精选
diff --git a/api/_lib/supabase.js b/api/_lib/supabase.js
new file mode 100644
index 0000000..4cea7cb
--- /dev/null
+++ b/api/_lib/supabase.js
@@ -0,0 +1,151 @@
+import { createClient } from '@supabase/supabase-js';
+
+let adminClient;
+
+export function getSupabaseConfig() {
+ const url = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
+ const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
+ return {
+ url,
+ serviceRoleKey,
+ configured: Boolean(url && serviceRoleKey)
+ };
+}
+
+export function isSupabaseServerConfigured() {
+ return getSupabaseConfig().configured;
+}
+
+export function getSupabaseAdminClient() {
+ const config = getSupabaseConfig();
+ if (!config.configured) return null;
+
+ if (!adminClient) {
+ adminClient = createClient(config.url, config.serviceRoleKey, {
+ auth: {
+ autoRefreshToken: false,
+ persistSession: false
+ }
+ });
+ }
+
+ return adminClient;
+}
+
+export function getBearerToken(req) {
+ const header = req.headers.authorization || req.headers.Authorization || '';
+ if (typeof header !== 'string') return '';
+ const match = header.match(/^Bearer\s+(.+)$/i);
+ return match ? match[1].trim() : '';
+}
+
+function getAdminEmails() {
+ return String(process.env.SUPER_ADMIN_EMAILS || '')
+ .split(',')
+ .map((email) => email.trim().toLowerCase())
+ .filter(Boolean);
+}
+
+export function isSuperAdminEmail(email) {
+ if (!email) return false;
+ return getAdminEmails().includes(String(email).trim().toLowerCase());
+}
+
+function profilePayloadFromUser(user, existingProfile) {
+ const metadata = user.user_metadata || {};
+ const email = String(user.email || existingProfile?.email || '').trim().toLowerCase();
+ const desiredRole = isSuperAdminEmail(email) ? 'super_admin' : existingProfile?.role || 'user';
+
+ return {
+ id: user.id,
+ email,
+ full_name: metadata.full_name || metadata.name || existingProfile?.full_name || null,
+ avatar_url: metadata.avatar_url || metadata.picture || existingProfile?.avatar_url || null,
+ role: existingProfile?.role === 'super_admin' || desiredRole === 'super_admin' ? 'super_admin' : 'user'
+ };
+}
+
+export function normalizeProfile(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ email: row.email,
+ fullName: row.full_name || '',
+ avatarUrl: row.avatar_url || '',
+ role: row.role || 'user',
+ isSuperAdmin: row.role === 'super_admin',
+ creditBalance: Number(row.credit_balance || 0),
+ freeGenerationsUsed: Number(row.free_generations_used || 0),
+ freeUsed: Number(row.free_generations_used || 0) >= 1,
+ createdAt: row.created_at || '',
+ updatedAt: row.updated_at || ''
+ };
+}
+
+export async function ensureProfileForUser(user) {
+ const client = getSupabaseAdminClient();
+ if (!client || !user?.id) throw new Error('Supabase is not configured');
+
+ const { data: existingProfile, error: selectError } = await client
+ .from('profiles')
+ .select('*')
+ .eq('id', user.id)
+ .maybeSingle();
+
+ if (selectError) throw selectError;
+
+ const payload = profilePayloadFromUser(user, existingProfile);
+ const { data, error } = await client
+ .from('profiles')
+ .upsert(payload, { onConflict: 'id' })
+ .select('*')
+ .single();
+
+ if (error) throw error;
+ return normalizeProfile(data);
+}
+
+export async function getProfileById(userId) {
+ const client = getSupabaseAdminClient();
+ if (!client || !userId) return null;
+
+ const { data, error } = await client
+ .from('profiles')
+ .select('*')
+ .eq('id', userId)
+ .maybeSingle();
+
+ if (error) throw error;
+ return normalizeProfile(data);
+}
+
+export async function getAuthContext(req, options = {}) {
+ const { allowAnonymous = false } = options;
+ const client = getSupabaseAdminClient();
+ if (!client) {
+ return { error: 'SERVER_NOT_CONFIGURED', status: 500 };
+ }
+
+ const token = getBearerToken(req);
+ if (!token) {
+ return allowAnonymous
+ ? { user: null, profile: null, token: null, client }
+ : { error: 'AUTH_REQUIRED', status: 401 };
+ }
+
+ const { data, error } = await client.auth.getUser(token);
+ if (error || !data?.user) {
+ return { error: 'AUTH_REQUIRED', status: 401 };
+ }
+
+ try {
+ const profile = await ensureProfileForUser(data.user);
+ return { user: data.user, profile, token, client };
+ } catch (profileError) {
+ console.warn('Failed to ensure Supabase profile', {
+ userId: data.user.id,
+ message: String(profileError?.message || 'unknown').slice(0, 240)
+ });
+ return { error: 'SERVER_NOT_CONFIGURED', status: 500 };
+ }
+}
diff --git a/api/admin/users.js b/api/admin/users.js
new file mode 100644
index 0000000..d64bbf5
--- /dev/null
+++ b/api/admin/users.js
@@ -0,0 +1,53 @@
+import { getAuthContext } from '../_lib/supabase.js';
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+
+function formatAdminUser(row) {
+ return {
+ id: row.id,
+ email: row.email,
+ fullName: row.full_name || '',
+ avatarUrl: row.avatar_url || '',
+ role: row.role || 'user',
+ creditBalance: Number(row.credit_balance || 0),
+ freeGenerationsUsed: Number(row.free_generations_used || 0),
+ freeUsed: Number(row.free_generations_used || 0) >= 1,
+ createdAt: row.created_at || ''
+ };
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return json(res, auth.status || 401, { ok: false, error: auth.error });
+ }
+
+ if (auth.profile?.role !== 'super_admin') {
+ return json(res, 403, { ok: false, error: 'FORBIDDEN' });
+ }
+
+ const { data, error } = await auth.client
+ .from('profiles')
+ .select('id,email,full_name,avatar_url,role,credit_balance,free_generations_used,created_at')
+ .order('created_at', { ascending: false })
+ .limit(100);
+
+ if (error) {
+ console.warn('Failed to list admin users', {
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ return json(res, 200, {
+ ok: true,
+ users: (data || []).map(formatAdminUser)
+ });
+}
diff --git a/api/generate-image.js b/api/generate-image.js
index c20320f..79b9933 100644
--- a/api/generate-image.js
+++ b/api/generate-image.js
@@ -1,90 +1,18 @@
-import crypto from 'node:crypto';
+import {
+ getAuthContext,
+ getProfileById,
+ isSupabaseServerConfigured
+} from './_lib/supabase.js';
-const COOKIE_NAME = 'gpt_image_free_id';
-const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
-const ANON_TTL = COOKIE_MAX_AGE;
-const IP_DAY_TTL = 60 * 60 * 30;
-const PENDING_TTL = 5 * 60;
const MAX_PROMPT_LENGTH = 6000;
-const DEFAULT_CIYUAN_BASE_URL = 'https://ciyuan.it.com';
+const DEFAULT_CIYUAN_BASE_URL = 'https://ciyuan.today';
-function json(res, status, payload, extraHeaders = {}) {
- for (const [key, value] of Object.entries(extraHeaders)) {
- res.setHeader(key, value);
- }
+function json(res, status, payload) {
res.status(status).json(payload);
}
-function parseCookies(cookieHeader = '') {
- return cookieHeader
- .split(';')
- .map((part) => part.trim())
- .filter(Boolean)
- .reduce((cookies, part) => {
- const index = part.indexOf('=');
- if (index === -1) return cookies;
- const key = part.slice(0, index);
- const value = part.slice(index + 1);
- cookies[key] = decodeURIComponent(value);
- return cookies;
- }, {});
-}
-
-function getOrCreateAnonId(req) {
- const cookies = parseCookies(req.headers.cookie || '');
- const existing = cookies[COOKIE_NAME];
- if (existing && /^[a-f0-9-]{32,64}$/i.test(existing)) {
- return { anonId: existing, shouldSetCookie: false };
- }
- return { anonId: crypto.randomUUID(), shouldSetCookie: true };
-}
-
-function buildCookie(anonId) {
- const secure = process.env.NODE_ENV === 'production' ? '; Secure' : '';
- return `${COOKIE_NAME}=${encodeURIComponent(anonId)}; Max-Age=${COOKIE_MAX_AGE}; Path=/; HttpOnly; SameSite=Lax${secure}`;
-}
-
-function getClientIp(req) {
- const forwardedFor = req.headers['x-forwarded-for'];
- if (typeof forwardedFor === 'string' && forwardedFor.trim()) {
- return forwardedFor.split(',')[0].trim();
- }
- const realIp = req.headers['x-real-ip'];
- if (typeof realIp === 'string' && realIp.trim()) {
- return realIp.trim();
- }
- return req.socket?.remoteAddress || 'unknown';
-}
-
-function getRedisConfig() {
- const url = process.env.UPSTASH_REDIS_REST_URL;
- const token = process.env.UPSTASH_REDIS_REST_TOKEN;
- if (!url || !token) return null;
- return { url: url.replace(/\/$/, ''), token };
-}
-
function isServerConfigured() {
- return Boolean(process.env.CIYUAN_API_KEY && getRedisConfig());
-}
-
-async function redisCommand(command) {
- const config = getRedisConfig();
- if (!config) throw new Error('Redis is not configured');
-
- const response = await fetch(config.url, {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${config.token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(command)
- });
- const payload = await response.json().catch(() => ({}));
-
- if (!response.ok || payload.error) {
- throw new Error(payload.error || `Redis command failed with status ${response.status}`);
- }
- return payload.result;
+ return Boolean(process.env.CIYUAN_API_KEY && isSupabaseServerConfigured());
}
async function readBody(req) {
@@ -100,52 +28,69 @@ async function readBody(req) {
return raw ? JSON.parse(raw) : {};
}
-function buildKeys(anonId, ip) {
- const day = new Date().toISOString().slice(0, 10);
- const ipHash = crypto.createHash('sha256').update(ip).digest('hex').slice(0, 24);
+function normalizeReservation(data) {
+ const row = Array.isArray(data) ? data[0] : data;
+ if (!row?.reservation_id) return null;
return {
- anonKey: `freegen:v1:anon:${anonId}`,
- ipDayKey: `freegen:v1:ip:${ipHash}:${day}`,
- pendingAnonKey: `freegen:v1:pending:anon:${anonId}`,
- pendingIpKey: `freegen:v1:pending:ip:${ipHash}:${day}`
+ reservationId: row.reservation_id,
+ usedFreeGeneration: Boolean(row.used_free_generation),
+ creditAmount: Number(row.credit_amount || 0),
+ freeGenerationsUsed: Number(row.free_generations_used || 0),
+ creditBalance: Number(row.credit_balance || 0)
};
}
-async function hasUsedFreeGeneration(keys) {
- const [anonUsed, ipUsed] = await Promise.all([
- redisCommand(['GET', keys.anonKey]),
- redisCommand(['GET', keys.ipDayKey])
- ]);
- return Boolean(anonUsed || ipUsed);
+function profileFromReservation(profile, reservation) {
+ if (!profile || !reservation) return profile;
+ return {
+ ...profile,
+ creditBalance: reservation.creditBalance,
+ freeGenerationsUsed: reservation.freeGenerationsUsed,
+ freeUsed: reservation.freeGenerationsUsed >= 1
+ };
}
-async function reserveGeneration(keys) {
- const anonReserved = await redisCommand(['SET', keys.pendingAnonKey, '1', 'NX', 'EX', PENDING_TTL]);
- if (anonReserved !== 'OK') return false;
+async function reserveGeneration(client, userId, caseId, prompt) {
+ const { data, error } = await client.rpc('reserve_generation_usage', {
+ p_user_id: userId,
+ p_case_id: caseId,
+ p_prompt: prompt
+ });
- const ipReserved = await redisCommand(['SET', keys.pendingIpKey, '1', 'NX', 'EX', PENDING_TTL]);
- if (ipReserved !== 'OK') {
- await redisCommand(['DEL', keys.pendingAnonKey]).catch(() => null);
- return false;
+ if (error) {
+ const normalizedMessage = String(error.message || error.details || '').toUpperCase();
+ if (normalizedMessage.includes('CREDITS_REQUIRED')) {
+ const limitError = new Error('CREDITS_REQUIRED');
+ limitError.code = 'CREDITS_REQUIRED';
+ throw limitError;
+ }
+ throw error;
}
- return true;
+ const reservation = normalizeReservation(data);
+ if (!reservation) throw new Error('RESERVATION_FAILED');
+ return reservation;
}
-async function markFreeGenerationUsed(keys) {
- await Promise.all([
- redisCommand(['SET', keys.anonKey, '1', 'EX', ANON_TTL]),
- redisCommand(['SET', keys.ipDayKey, '1', 'EX', IP_DAY_TTL]),
- redisCommand(['DEL', keys.pendingAnonKey]),
- redisCommand(['DEL', keys.pendingIpKey])
- ]);
+async function completeReservation(client, reservationId) {
+ const { error } = await client.rpc('complete_generation_reservation', {
+ p_reservation_id: reservationId
+ });
+ if (error) throw error;
}
-async function releaseGeneration(keys) {
- await Promise.all([
- redisCommand(['DEL', keys.pendingAnonKey]).catch(() => null),
- redisCommand(['DEL', keys.pendingIpKey]).catch(() => null)
- ]);
+async function releaseReservation(client, reservationId, errorCode) {
+ if (!reservationId) return;
+ const { error } = await client.rpc('release_generation_reservation', {
+ p_reservation_id: reservationId,
+ p_error_code: errorCode || 'GENERATION_FAILED'
+ });
+ if (error) {
+ console.warn('Failed to release generation reservation', {
+ reservationId,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ }
}
async function generateImage(prompt) {
@@ -187,60 +132,78 @@ export default async function handler(req, res) {
return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
}
- const { anonId, shouldSetCookie } = getOrCreateAnonId(req);
- const cookieHeaders = shouldSetCookie ? { 'Set-Cookie': buildCookie(anonId) } : {};
-
if (!isServerConfigured()) {
- return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' }, cookieHeaders);
+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
}
- const keys = buildKeys(anonId, getClientIp(req));
+ const auth = await getAuthContext(req, { allowAnonymous: req.method === 'GET' });
+ if (auth.error) {
+ return json(res, auth.status || 401, { ok: false, error: auth.error });
+ }
- try {
- if (req.method === 'GET') {
- const freeUsed = await hasUsedFreeGeneration(keys);
- return json(res, 200, { ok: true, freeUsed }, cookieHeaders);
- }
+ if (req.method === 'GET') {
+ return json(res, 200, {
+ ok: true,
+ authRequired: !auth.profile,
+ freeUsed: Boolean(auth.profile?.freeUsed),
+ user: auth.profile || null
+ });
+ }
- let body;
- try {
- body = await readBody(req);
- } catch {
- return json(res, 400, { ok: false, error: 'INVALID_PROMPT' }, cookieHeaders);
- }
+ if (!auth.user || !auth.profile) {
+ return json(res, 401, { ok: false, error: 'AUTH_REQUIRED' });
+ }
- const prompt = String(body.prompt || '').trim();
- const caseId = Number(body.caseId);
- if (!prompt || prompt.length > MAX_PROMPT_LENGTH || !Number.isFinite(caseId)) {
- return json(res, 400, { ok: false, error: 'INVALID_PROMPT' }, cookieHeaders);
- }
+ let body;
+ try {
+ body = await readBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_PROMPT' });
+ }
- if (await hasUsedFreeGeneration(keys)) {
- return json(res, 402, { ok: false, error: 'FREE_LIMIT_REACHED' }, cookieHeaders);
- }
+ const prompt = String(body.prompt || '').trim();
+ const caseId = Number(body.caseId);
+ if (!prompt || prompt.length > MAX_PROMPT_LENGTH || !Number.isFinite(caseId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_PROMPT' });
+ }
- if (!(await reserveGeneration(keys))) {
- return json(res, 402, { ok: false, error: 'FREE_LIMIT_REACHED' }, cookieHeaders);
+ let reservation;
+ try {
+ reservation = await reserveGeneration(auth.client, auth.user.id, caseId, prompt);
+ } catch (error) {
+ if (error?.code === 'CREDITS_REQUIRED') {
+ return json(res, 402, { ok: false, error: 'CREDITS_REQUIRED' });
}
+ console.warn('Failed to reserve generation usage', {
+ userId: auth.user.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
- try {
- const image = await generateImage(prompt);
- await markFreeGenerationUsed(keys);
- return json(res, 200, { ok: true, image }, cookieHeaders);
- } catch (error) {
- console.warn('Image generation failed', {
- status: error?.status || null,
- code: error?.code || null,
- type: error?.type || null,
- message: String(error?.message || 'unknown').slice(0, 240)
- });
- await releaseGeneration(keys);
- if (error?.status === 429) {
- return json(res, 503, { ok: false, error: 'UPSTREAM_BUSY' }, cookieHeaders);
- }
- return json(res, 502, { ok: false, error: 'GENERATION_FAILED' }, cookieHeaders);
+ try {
+ const image = await generateImage(prompt);
+ await completeReservation(auth.client, reservation.reservationId);
+ return json(res, 200, {
+ ok: true,
+ image,
+ user: profileFromReservation(auth.profile, reservation)
+ });
+ } catch (error) {
+ console.warn('Image generation failed', {
+ status: error?.status || null,
+ code: error?.code || null,
+ type: error?.type || null,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+
+ const errorCode = error?.status === 429 ? 'UPSTREAM_BUSY' : 'GENERATION_FAILED';
+ await releaseReservation(auth.client, reservation.reservationId, errorCode);
+
+ const refreshedProfile = await getProfileById(auth.user.id).catch(() => null);
+ if (error?.status === 429) {
+ return json(res, 503, { ok: false, error: 'UPSTREAM_BUSY', user: refreshedProfile });
}
- } catch {
- return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' }, cookieHeaders);
+ return json(res, 502, { ok: false, error: 'GENERATION_FAILED', user: refreshedProfile });
}
}
diff --git a/api/me.js b/api/me.js
new file mode 100644
index 0000000..55bce81
--- /dev/null
+++ b/api/me.js
@@ -0,0 +1,26 @@
+import { getAuthContext, isSupabaseServerConfigured } from './_lib/supabase.js';
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+
+ if (!isSupabaseServerConfigured()) {
+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ const auth = await getAuthContext(req, { allowAnonymous: true });
+ if (auth.error) {
+ return json(res, auth.status || 401, { ok: false, error: auth.error });
+ }
+
+ return json(res, 200, {
+ ok: true,
+ user: auth.profile
+ });
+}
diff --git a/package-lock.json b/package-lock.json
index b276e4f..3b5375d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -8,6 +8,7 @@
"name": "awesome-gpt-image-2-site",
"version": "1.0.0",
"dependencies": {
+ "@supabase/supabase-js": "^2.105.4",
"@vitejs/plugin-react": "^5.1.1",
"lucide-react": "^0.561.0",
"react": "^19.2.1",
@@ -1110,6 +1111,90 @@
"win32"
]
},
+ "node_modules/@supabase/auth-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.105.4.tgz",
+ "integrity": "sha512-Ejfa37M5xoIwoxVebxRahnwubPo8g22qkXQ4p50+N9MIvU9UZoN+A8dwVPtczzGf8oV/YXN80ZPxK4aWXuSN/A==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@supabase/functions-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.105.4.tgz",
+ "integrity": "sha512-JVNKbBft3Qkja+WlGaE026AJ2AH9K0UTsxsfvEIHgd4zFrBor4BYRCrYFrv9IDsvVqkF72wKDsODJl5GY/C4tA==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@supabase/phoenix": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.2.tgz",
+ "integrity": "sha512-YSAGnmDAfuleFCVt3CeurQZAhxRfXWeZIIkwp7NhYzQ1UwW6ePSnzsFAiUm/mbCkfoCf70QQHKW/K6RKh52a4A==",
+ "license": "MIT"
+ },
+ "node_modules/@supabase/postgrest-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.105.4.tgz",
+ "integrity": "sha512-SppIyLo/kTwIlz1qpv2HN1EQqBg0GVktrDDFsXygYROha3MgVn4rT7p5EjFHFqXQm2rdRGb/BI7bc+jr10m91w==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@supabase/realtime-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.105.4.tgz",
+ "integrity": "sha512-6ov6c59+8D9h7q4M4Gy/uDJlC0Akxl9/714Y+6vJ+Sijuc16TS/p5DwhfRCLNcIhNiej1gEt+CQUwsjiPt4PxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/phoenix": "^0.4.2",
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@supabase/storage-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.105.4.tgz",
+ "integrity": "sha512-Jx+pzMP1Whjof2PWHoVBUA75/p7PQE9CqKBzn1oXVyJDOggMLSH2OzVWwsXYaxEpdC1K/KltwmOX44nL3LHl9g==",
+ "license": "MIT",
+ "dependencies": {
+ "iceberg-js": "^0.8.1",
+ "tslib": "2.8.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@supabase/supabase-js": {
+ "version": "2.105.4",
+ "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.105.4.tgz",
+ "integrity": "sha512-cEnx+k49knU+qdIP7rXwR6fqEXPHZs+74xFK1R0S8MgQ7v9tbePVdGxvO03n3bPympMdJWVLadARBfU4TgNHCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/auth-js": "2.105.4",
+ "@supabase/functions-js": "2.105.4",
+ "@supabase/postgrest-js": "2.105.4",
+ "@supabase/realtime-js": "2.105.4",
+ "@supabase/storage-js": "2.105.4"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -1361,6 +1446,15 @@
"node": ">=6.9.0"
}
},
+ "node_modules/iceberg-js": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -1599,6 +1693,12 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
"node_modules/update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
diff --git a/package.json b/package.json
index 57691ec..d2c6b0c 100644
--- a/package.json
+++ b/package.json
@@ -16,11 +16,11 @@
"preview": "vite preview"
},
"dependencies": {
+ "@supabase/supabase-js": "^2.105.4",
"@vitejs/plugin-react": "^5.1.1",
- "vite": "^7.2.7",
+ "lucide-react": "^0.561.0",
"react": "^19.2.1",
"react-dom": "^19.2.1",
- "lucide-react": "^0.561.0"
- },
- "devDependencies": {}
+ "vite": "^7.2.7"
+ }
}
diff --git a/src/main.jsx b/src/main.jsx
index 3138a86..ecdbe52 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -4,19 +4,28 @@ import {
ArrowUpRight,
Bot,
Check,
+ Coins,
Copy,
Eye,
Github,
ImageIcon,
LoaderCircle,
+ LogIn,
+ LogOut,
+ Mail,
PackageCheck,
+ RefreshCw,
Search,
+ ShieldCheck,
Sparkles,
Terminal,
+ UserCircle,
+ Users,
WandSparkles,
X
} from 'lucide-react';
import './styles.css';
+import { isSupabaseConfigured, supabase } from './supabaseClient';
import skillExampleImage from '../agents/skills/gpt-image-2-style-library/assets/city-life-system-map.png';
const fallbackRepoUrl = 'https://github.com/freestylefly/awesome-gpt-image-2';
@@ -85,6 +94,36 @@ const copy = {
generationFailed: 'Generation failed. Please try again later.',
promptRequired: 'Prompt is required and must stay under 6000 characters.',
serverUnavailable: 'Generation service is not configured yet.',
+ authRequired: 'Sign in to generate a test image.',
+ signIn: 'Sign in',
+ signInTitle: 'Sign in to generate test images',
+ signInSubtitle: 'Use email magic link or Google to unlock your free test image and future credits.',
+ emailAddress: 'Email address',
+ sendMagicLink: 'Send magic link',
+ magicLinkSent: 'Magic link sent. Check your inbox, then return here.',
+ continueWithGoogle: 'Continue with Google',
+ authNotConfigured: 'Login is not configured yet.',
+ authError: 'Login failed. Please try again.',
+ signOut: 'Sign out',
+ account: 'Account',
+ adminPanel: 'Admin',
+ superAdmin: 'Super admin',
+ credits: 'credits',
+ freeReady: 'Free test ready',
+ freeUsedShort: 'Free test used',
+ signInToGenerate: 'Sign in to generate',
+ creditsAvailable: (count) => `${count} credit${count === 1 ? '' : 's'} available`,
+ adminTitle: 'User admin',
+ adminSubtitle: 'Read-only user, role, credit, and free-generation overview.',
+ refresh: 'Refresh',
+ users: 'Users',
+ role: 'Role',
+ creditBalance: 'Credits',
+ freeGeneration: 'Free test',
+ createdAt: 'Created',
+ loadingUsers: 'Loading users...',
+ noUsers: 'No users yet.',
+ adminOnly: 'Only super admins can view this page.',
fullPrompt: 'Full Prompt',
templatePrompt: 'Template Prompt',
useWhen: 'Use When',
@@ -158,6 +197,36 @@ const copy = {
generationFailed: '生成失败,请稍后再试。',
promptRequired: 'Prompt 不能为空,并且不能超过 6000 字符。',
serverUnavailable: '生成服务还没有完成配置。',
+ authRequired: '登录后即可生成测试图。',
+ signIn: '登录',
+ signInTitle: '登录后生成测试图',
+ signInSubtitle: '使用邮箱魔法链接或 Google 登录,解锁 1 张免费测试图,并为后续积分体系做准备。',
+ emailAddress: '邮箱地址',
+ sendMagicLink: '发送魔法链接',
+ magicLinkSent: '魔法链接已发送,请查收邮箱后回到这里。',
+ continueWithGoogle: '使用 Google 继续',
+ authNotConfigured: '登录功能还没有完成配置。',
+ authError: '登录失败,请稍后再试。',
+ signOut: '退出登录',
+ account: '账号',
+ adminPanel: '管理后台',
+ superAdmin: '超级管理员',
+ credits: '积分',
+ freeReady: '免费测试可用',
+ freeUsedShort: '免费测试已用',
+ signInToGenerate: '登录后生成',
+ creditsAvailable: (count) => `可用积分 ${count}`,
+ adminTitle: '用户管理',
+ adminSubtitle: '只读查看用户、角色、积分余额和免费生成状态。',
+ refresh: '刷新',
+ users: '用户',
+ role: '角色',
+ creditBalance: '积分',
+ freeGeneration: '免费测试',
+ createdAt: '创建时间',
+ loadingUsers: '正在加载用户...',
+ noUsers: '暂无用户。',
+ adminOnly: '仅超级管理员可查看。',
fullPrompt: '完整 Prompt',
templatePrompt: '模板 Prompt',
useWhen: '适用场景',
@@ -357,12 +426,27 @@ function useCopy() {
function generationErrorMessage(error, language) {
const t = copy[language];
if (error === 'FREE_LIMIT_REACHED') return t.freeLimitReached;
+ if (error === 'CREDITS_REQUIRED') return t.freeLimitReached;
+ if (error === 'AUTH_REQUIRED') return t.authRequired;
+ if (error === 'FORBIDDEN') return t.adminOnly;
if (error === 'UPSTREAM_BUSY') return t.generationBusy;
if (error === 'SERVER_NOT_CONFIGURED') return t.serverUnavailable;
if (error === 'INVALID_PROMPT') return t.promptRequired;
return t.generationFailed;
}
+function getAuthHeaders(session) {
+ return session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {};
+}
+
+function getGenerationQuotaText(profile, language) {
+ const t = copy[language];
+ if (!profile) return t.authRequired;
+ if (!profile.freeUsed) return t.oneFreeGeneration;
+ if (profile.creditBalance > 0) return t.creditsAvailable(profile.creditBalance);
+ return t.freeLimitReached;
+}
+
function formatTemplatePrompt(item, language, styleLibrary) {
const title = textFor(item.title, language);
const description = textFor(item.description, language);
@@ -500,6 +584,280 @@ function LanguageSwitch({ language, setLanguage }) {
);
}
+function AuthModal({ open, language, onClose }) {
+ const t = copy[language];
+ const [email, setEmail] = useState('');
+ const [status, setStatus] = useState('idle');
+ const [message, setMessage] = useState('');
+
+ useEffect(() => {
+ if (!open) return;
+ setStatus('idle');
+ setMessage('');
+ }, [open]);
+
+ if (!open) return null;
+
+ const redirectTo = `${window.location.origin}${window.location.pathname}`;
+
+ async function handleEmailSubmit(event) {
+ event.preventDefault();
+ if (!isSupabaseConfigured || !supabase) {
+ setStatus('error');
+ setMessage(t.authNotConfigured);
+ return;
+ }
+
+ const normalizedEmail = email.trim();
+ if (!normalizedEmail) {
+ setStatus('error');
+ setMessage(t.emailAddress);
+ return;
+ }
+
+ setStatus('loading');
+ setMessage('');
+ const { error } = await supabase.auth.signInWithOtp({
+ email: normalizedEmail,
+ options: {
+ emailRedirectTo: redirectTo
+ }
+ });
+
+ if (error) {
+ setStatus('error');
+ setMessage(error.message || t.authError);
+ return;
+ }
+
+ setStatus('sent');
+ setMessage(t.magicLinkSent);
+ }
+
+ async function handleGoogleSignIn() {
+ if (!isSupabaseConfigured || !supabase) {
+ setStatus('error');
+ setMessage(t.authNotConfigured);
+ return;
+ }
+
+ setStatus('loading');
+ setMessage('');
+ const { error } = await supabase.auth.signInWithOAuth({
+ provider: 'google',
+ options: {
+ redirectTo
+ }
+ });
+
+ if (error) {
+ setStatus('error');
+ setMessage(error.message || t.authError);
+ }
+ }
+
+ return (
+ <div
+ className="previewOverlay authOverlay"
+ role="presentation"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <section className="authDialog" role="dialog" aria-modal="true" aria-labelledby="auth-title">
+ <button className="previewClose" type="button" onClick={onClose} aria-label={t.closePreview}>
+ <X size={20} />
+ </button>
+ <div className="authIcon">
+ <UserCircle size={28} />
+ </div>
+ <h2 id="auth-title">{t.signInTitle}</h2>
+ <p>{t.signInSubtitle}</p>
+ <form className="authForm" onSubmit={handleEmailSubmit}>
+ <label>
+ <span>{t.emailAddress}</span>
+ <input
+ type="email"
+ autoComplete="email"
+ value={email}
+ onChange={(event) => setEmail(event.target.value)}
+ placeholder="[email protected]"
+ />
+ </label>
+ <button type="submit" disabled={status === 'loading'}>
+ {status === 'loading' ? <LoaderCircle className="spinIcon" size={17} /> : <Mail size={17} />}
+ {t.sendMagicLink}
+ </button>
+ </form>
+ <button className="googleButton" type="button" onClick={handleGoogleSignIn} disabled={status === 'loading'}>
+ <LogIn size={17} />
+ {t.continueWithGoogle}
+ </button>
+ {message ? (
+ <p className={cx('authMessage', status === 'error' && 'error', status === 'sent' && 'sent')}>
+ {message}
+ </p>
+ ) : null}
+ </section>
+ </div>
+ );
+}
+
+function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin }) {
+ const t = copy[language];
+
+ if (!session) {
+ return (
+ <button className="accountButton" type="button" onClick={onSignIn}>
+ <LogIn size={17} />
+ {t.signIn}
+ </button>
+ );
+ }
+
+ const email = profile?.email || session.user?.email || t.account;
+
+ return (
+ <div className="userMenu">
+ <div className="accountChip">
+ <UserCircle size={17} />
+ <span>{email}</span>
+ {profile?.isSuperAdmin ? <strong>{t.superAdmin}</strong> : null}
+ </div>
+ <div className="creditChip">
+ <Coins size={16} />
+ <span>{profile?.creditBalance || 0} {t.credits}</span>
+ <span>{profile?.freeUsed ? t.freeUsedShort : t.freeReady}</span>
+ </div>
+ {profile?.isSuperAdmin ? (
+ <button className="iconTextButton" type="button" onClick={onAdmin}>
+ <ShieldCheck size={17} />
+ {t.adminPanel}
+ </button>
+ ) : null}
+ <button className="iconTextButton" type="button" onClick={onSignOut}>
+ <LogOut size={17} />
+ {t.signOut}
+ </button>
+ </div>
+ );
+}
+
+function AdminPanel({ open, language, session, onClose }) {
+ const t = copy[language];
+ const [users, setUsers] = useState([]);
+ const [status, setStatus] = useState('idle');
+ const [message, setMessage] = useState('');
+
+ async function loadUsers() {
+ if (!session?.access_token) {
+ setStatus('error');
+ setMessage(t.adminOnly);
+ return;
+ }
+
+ setStatus('loading');
+ setMessage('');
+ try {
+ const response = await fetch('/api/admin/users', {
+ headers: getAuthHeaders(session)
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) {
+ throw new Error(payload.error || 'SERVER_NOT_CONFIGURED');
+ }
+ setUsers(payload.users || []);
+ setStatus('ready');
+ } catch (error) {
+ setStatus('error');
+ setMessage(generationErrorMessage(error.message, language));
+ }
+ }
+
+ useEffect(() => {
+ if (open) loadUsers();
+ }, [open, session?.access_token]);
+
+ if (!open) return null;
+
+ return (
+ <div
+ className="previewOverlay adminOverlay"
+ role="presentation"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <section className="adminDialog" role="dialog" aria-modal="true" aria-labelledby="admin-title">
+ <button className="previewClose" type="button" onClick={onClose} aria-label={t.closePreview}>
+ <X size={20} />
+ </button>
+ <div className="adminHeader">
+ <div>
+ <span className="eyebrow">
+ <ShieldCheck size={16} />
+ {t.superAdmin}
+ </span>
+ <h2 id="admin-title">{t.adminTitle}</h2>
+ <p>{t.adminSubtitle}</p>
+ </div>
+ <button type="button" onClick={loadUsers} disabled={status === 'loading'}>
+ {status === 'loading' ? <LoaderCircle className="spinIcon" size={17} /> : <RefreshCw size={17} />}
+ {t.refresh}
+ </button>
+ </div>
+ {status === 'loading' ? (
+ <div className="adminState">
+ <LoaderCircle className="spinIcon" size={20} />
+ {t.loadingUsers}
+ </div>
+ ) : null}
+ {status === 'error' ? <p className="authMessage error">{message || t.adminOnly}</p> : null}
+ {status !== 'loading' && !users.length && status !== 'error' ? (
+ <div className="adminState">
+ <Users size={20} />
+ {t.noUsers}
+ </div>
+ ) : null}
+ {users.length ? (
+ <div className="adminTableWrap">
+ <table className="adminTable">
+ <thead>
+ <tr>
+ <th>{t.users}</th>
+ <th>{t.role}</th>
+ <th>{t.creditBalance}</th>
+ <th>{t.freeGeneration}</th>
+ <th>{t.createdAt}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {users.map((user) => (
+ <tr key={user.id}>
+ <td>
+ <div className="adminUserCell">
+ {user.avatarUrl ? <img src={user.avatarUrl} alt="" /> : <UserCircle size={28} />}
+ <div>
+ <strong>{user.email}</strong>
+ {user.fullName ? <span>{user.fullName}</span> : null}
+ </div>
+ </div>
+ </td>
+ <td><span className="roleBadge">{user.role}</span></td>
+ <td>{user.creditBalance}</td>
+ <td>{user.freeUsed ? t.freeUsedShort : t.freeReady}</td>
+ <td>{user.createdAt ? new Date(user.createdAt).toLocaleDateString(language === 'zh' ? 'zh-CN' : 'en-US') : '-'}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : null}
+ </section>
+ </div>
+ );
+}
+
function SkillSection({ language, repoUrl }) {
const t = copy[language];
const [commandCopied, setCommandCopied] = useState(false);
@@ -701,10 +1059,12 @@ function PreviewDialog({
language,
styleLibrary,
copiedId,
- freeUsed,
+ session,
+ profile,
onClose,
onCopyText,
- onFreeUsedChange
+ onAuthRequired,
+ onProfileChange
}) {
const t = copy[language];
const repoDocsUrl = `${styleLibrary.repository || fallbackRepoUrl}/blob/main/${styleLibrary.templateDocument}`;
@@ -775,15 +1135,24 @@ function PreviewDialog({
const pitfalls = listFor(item.pitfalls, language);
const isGenerating = generationState.status === 'generating';
const generatedImage = !isTemplate ? generationState.image : '';
+ const isSignedIn = Boolean(session?.access_token);
+ const isOutOfCredits = isSignedIn && Boolean(profile?.freeUsed) && Number(profile?.creditBalance || 0) <= 0;
+ const generationLocked = isGenerating || isOutOfCredits;
+ const quotaText = isSignedIn ? getGenerationQuotaText(profile, language) : t.authRequired;
async function handleGenerate() {
if (isTemplate || isGenerating) return;
+ if (!isSignedIn) {
+ onAuthRequired();
+ setGenerationState({ status: 'error', image: generatedImage, message: t.authRequired });
+ return;
+ }
const prompt = editablePrompt.trim();
if (!prompt || prompt.length > 6000) {
setGenerationState({ status: 'error', image: '', message: t.promptRequired });
return;
}
- if (freeUsed) {
+ if (isOutOfCredits) {
setGenerationState({ status: 'error', image: '', message: t.freeLimitReached });
return;
}
@@ -793,9 +1162,9 @@ function PreviewDialog({
try {
const response = await fetch('/api/generate-image', {
method: 'POST',
- credentials: 'include',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ ...getAuthHeaders(session)
},
body: JSON.stringify({
caseId: item.id,
@@ -805,7 +1174,8 @@ function PreviewDialog({
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload.ok || !payload.image) {
- if (payload.error === 'FREE_LIMIT_REACHED') onFreeUsedChange(true);
+ if (payload.user) onProfileChange(payload.user);
+ if (payload.error === 'AUTH_REQUIRED') onAuthRequired();
throw new Error(payload.error || 'GENERATION_FAILED');
}
@@ -815,7 +1185,7 @@ function PreviewDialog({
prompt,
savedAt
});
- onFreeUsedChange(true);
+ if (payload.user) onProfileChange(payload.user);
setGenerationState({ status: 'success', image: payload.image, message: '', prompt, savedAt });
} catch (error) {
setGenerationState({
@@ -886,9 +1256,9 @@ function PreviewDialog({
{isCopied ? t.copied : isTemplate ? t.copyTemplatePrompt : t.copyPrompt}
</button>
{!isTemplate ? (
- <button type="button" onClick={handleGenerate} disabled={isGenerating || freeUsed}>
+ <button type="button" onClick={handleGenerate} disabled={generationLocked}>
{isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}
- {isGenerating ? t.generating : t.generateTest}
+ {isGenerating ? t.generating : isSignedIn ? t.generateTest : t.signInToGenerate}
</button>
) : null}
<a href={primaryLink} target="_blank" rel="noreferrer">
@@ -924,12 +1294,12 @@ function PreviewDialog({
</div>
{!isTemplate ? (
<div className="generationPanel">
- <div className={cx('generationQuota', freeUsed && 'used')}>
- {freeUsed ? t.freeLimitReached : t.oneFreeGeneration}
+ <div className={cx('generationQuota', (!isSignedIn || isOutOfCredits) && 'used')}>
+ {quotaText}
</div>
- <button type="button" onClick={handleGenerate} disabled={isGenerating || freeUsed}>
+ <button type="button" onClick={handleGenerate} disabled={generationLocked}>
{isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}
- {isGenerating ? t.generating : t.generateImage}
+ {isGenerating ? t.generating : isSignedIn ? t.generateImage : t.signInToGenerate}
</button>
{generationState.status === 'error' ? (
<p className="generationMessage">{generationState.message}</p>
@@ -992,7 +1362,10 @@ function App() {
const [style, setStyle] = useState('All');
const [scene, setScene] = useState('All');
const [preview, setPreview] = useState(null);
- const [freeUsed, setFreeUsed] = useState(false);
+ const [session, setSession] = useState(null);
+ const [profile, setProfile] = useState(null);
+ const [authOpen, setAuthOpen] = useState(false);
+ const [adminOpen, setAdminOpen] = useState(false);
const { copiedId, copyPrompt, copyText } = useCopy();
const repoUrl = siteData?.repository || fallbackRepoUrl;
const t = copy[language];
@@ -1019,20 +1392,51 @@ function App() {
document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en';
}, [language]);
+ useEffect(() => {
+ if (!isSupabaseConfigured || !supabase) return undefined;
+
+ let active = true;
+ supabase.auth.getSession().then(({ data }) => {
+ if (active) setSession(data.session || null);
+ });
+
+ const { data } = supabase.auth.onAuthStateChange((_event, nextSession) => {
+ setSession(nextSession || null);
+ });
+
+ return () => {
+ active = false;
+ data.subscription.unsubscribe();
+ };
+ }, []);
+
useEffect(() => {
let cancelled = false;
- fetch('/api/generate-image', { credentials: 'include' })
+
+ if (!session?.access_token) {
+ setProfile(null);
+ return () => {
+ cancelled = true;
+ };
+ }
+
+ fetch('/api/me', {
+ headers: getAuthHeaders(session)
+ })
.then((response) => response.json())
.then((payload) => {
if (!cancelled && payload?.ok) {
- setFreeUsed(Boolean(payload.freeUsed));
+ setProfile(payload.user);
}
})
- .catch(() => null);
+ .catch(() => {
+ if (!cancelled) setProfile(null);
+ });
+
return () => {
cancelled = true;
};
- }, []);
+ }, [session?.access_token]);
useEffect(() => {
if (!siteData || !styleLibrary || !window.location.hash) return;
@@ -1093,6 +1497,17 @@ function App() {
const visibleCases = filteredCases.slice(0, 72);
+ async function handleSignOut() {
+ if (supabase) await supabase.auth.signOut();
+ setSession(null);
+ setProfile(null);
+ setAdminOpen(false);
+ }
+
+ function handleProfileChange(nextProfile) {
+ if (nextProfile) setProfile(nextProfile);
+ }
+
if (!siteData || !styleLibrary) {
return (
<main>
@@ -1120,6 +1535,14 @@ function App() {
GitHub
</a>
</nav>
+ <UserMenu
+ language={language}
+ session={session}
+ profile={profile}
+ onSignIn={() => setAuthOpen(true)}
+ onSignOut={handleSignOut}
+ onAdmin={() => setAdminOpen(true)}
+ />
<LanguageSwitch language={language} setLanguage={setLanguage} />
</div>
</header>
@@ -1235,10 +1658,23 @@ function App() {
language={language}
styleLibrary={styleLibrary}
copiedId={copiedId}
- freeUsed={freeUsed}
+ session={session}
+ profile={profile}
onClose={() => setPreview(null)}
onCopyText={copyText}
- onFreeUsedChange={setFreeUsed}
+ onAuthRequired={() => setAuthOpen(true)}
+ onProfileChange={handleProfileChange}
+ />
+ <AuthModal
+ open={authOpen}
+ language={language}
+ onClose={() => setAuthOpen(false)}
+ />
+ <AdminPanel
+ open={adminOpen}
+ language={language}
+ session={session}
+ onClose={() => setAdminOpen(false)}
/>
</main>
);
diff --git a/src/styles.css b/src/styles.css
index c667583..f286fbf 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -69,6 +69,8 @@ button {
.brand,
.topbar nav,
.languageSwitch,
+.accountButton,
+.userMenu,
.eyebrow,
.heroActions a,
.metrics span,
@@ -152,6 +154,85 @@ button {
color: #ffffff;
}
+.accountButton,
+.iconTextButton {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 42px;
+ border-radius: 8px;
+ padding: 0 12px;
+ color: #dfeaff;
+ font-weight: 900;
+}
+
+.accountButton,
+.iconTextButton {
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(9, 15, 32, 0.68);
+}
+
+.accountButton:hover,
+.iconTextButton:hover {
+ border-color: rgba(103, 232, 249, 0.62);
+ background: rgba(103, 232, 249, 0.13);
+}
+
+.userMenu {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 42px;
+ border-radius: 8px;
+ padding: 4px;
+}
+
+.accountChip,
+.creditChip {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ min-height: 34px;
+ border-radius: 7px;
+ padding: 0 9px;
+ background: rgba(255, 255, 255, 0.06);
+ color: #c9d8ef;
+ font-size: 12px;
+ font-weight: 800;
+}
+
+.accountChip span {
+ max-width: 150px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.accountChip strong,
+.roleBadge {
+ display: inline-flex;
+ align-items: center;
+ min-height: 22px;
+ border: 1px solid rgba(120, 255, 185, 0.3);
+ border-radius: 999px;
+ padding: 0 7px;
+ background: rgba(120, 255, 185, 0.1);
+ color: #c8ffb8;
+ font-size: 11px;
+ font-weight: 900;
+}
+
+.creditChip {
+ color: #ffe1a8;
+}
+
+.iconTextButton {
+ min-height: 34px;
+ padding: 0 10px;
+ font-size: 12px;
+}
+
.hero {
position: relative;
display: grid;
@@ -1429,6 +1510,230 @@ button {
font-weight: 900;
}
+.authDialog,
+.adminDialog {
+ position: relative;
+ width: min(100%, 460px);
+ max-height: min(860px, 92vh);
+ overflow: auto;
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 8px;
+ background:
+ radial-gradient(circle at 18% 0%, rgba(66, 230, 255, 0.15), transparent 38%),
+ linear-gradient(145deg, rgba(12, 18, 36, 0.98), rgba(6, 10, 21, 0.96));
+ box-shadow: 0 34px 120px rgba(0, 0, 0, 0.56);
+}
+
+.authDialog {
+ padding: 30px;
+}
+
+.authIcon {
+ display: grid;
+ width: 54px;
+ height: 54px;
+ border: 1px solid rgba(103, 232, 249, 0.24);
+ border-radius: 8px;
+ background: rgba(103, 232, 249, 0.12);
+ color: #9eeeff;
+ place-items: center;
+}
+
+.authDialog h2,
+.adminDialog h2 {
+ margin: 18px 48px 10px 0;
+ color: #ffffff;
+ font-size: 30px;
+ line-height: 1.15;
+ letter-spacing: 0;
+}
+
+.authDialog p,
+.adminDialog p {
+ margin: 0;
+ color: #aebcd0;
+ line-height: 1.68;
+}
+
+.authForm {
+ display: grid;
+ gap: 12px;
+ margin-top: 22px;
+}
+
+.authForm label {
+ display: grid;
+ gap: 8px;
+ color: #eaf3ff;
+ font-size: 13px;
+ font-weight: 900;
+}
+
+.authForm input {
+ width: 100%;
+ min-height: 46px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ outline: 0;
+ padding: 0 12px;
+ background: rgba(3, 7, 15, 0.72);
+ color: #ffffff;
+}
+
+.authForm input:focus {
+ border-color: rgba(103, 232, 249, 0.72);
+ box-shadow: 0 0 0 3px rgba(103, 232, 249, 0.1);
+}
+
+.authForm button,
+.googleButton,
+.adminHeader button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 46px;
+ border: 1px solid rgba(120, 255, 185, 0.34);
+ border-radius: 8px;
+ padding: 0 14px;
+ background: linear-gradient(135deg, rgba(66, 230, 255, 0.2), rgba(120, 255, 185, 0.16));
+ color: #ffffff;
+ font-weight: 900;
+}
+
+.googleButton {
+ width: 100%;
+ margin-top: 12px;
+ border-color: rgba(255, 255, 255, 0.14);
+ background: rgba(255, 255, 255, 0.08);
+}
+
+.authForm button:disabled,
+.googleButton:disabled,
+.adminHeader button:disabled {
+ cursor: not-allowed;
+ opacity: 0.6;
+}
+
+.authMessage {
+ margin-top: 14px;
+ border: 1px solid rgba(255, 198, 102, 0.28);
+ border-radius: 8px;
+ padding: 10px 12px;
+ background: rgba(255, 198, 102, 0.08);
+ color: #ffe1a8;
+ font-size: 13px;
+ font-weight: 800;
+}
+
+.authMessage.sent {
+ border-color: rgba(120, 255, 185, 0.28);
+ background: rgba(120, 255, 185, 0.08);
+ color: #c8ffb8;
+}
+
+.authMessage.error {
+ border-color: rgba(255, 112, 112, 0.26);
+ background: rgba(255, 112, 112, 0.08);
+ color: #ffc7c7;
+}
+
+.adminDialog {
+ width: min(980px, 100%);
+ padding: 24px;
+}
+
+.adminHeader {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 18px;
+ margin-bottom: 18px;
+}
+
+.adminHeader h2 {
+ margin-top: 14px;
+}
+
+.adminTableWrap {
+ overflow: auto;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+}
+
+.adminTable {
+ width: 100%;
+ border-collapse: collapse;
+ min-width: 720px;
+ color: #dfeaff;
+}
+
+.adminTable th,
+.adminTable td {
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ padding: 12px;
+ text-align: left;
+ vertical-align: middle;
+}
+
+.adminTable th {
+ background: rgba(255, 255, 255, 0.055);
+ color: #9eeeff;
+ font-size: 12px;
+ font-weight: 900;
+ text-transform: uppercase;
+}
+
+.adminTable tr:last-child td {
+ border-bottom: 0;
+}
+
+.adminUserCell {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+.adminUserCell img,
+.adminUserCell svg {
+ flex: 0 0 auto;
+ width: 32px;
+ height: 32px;
+ border-radius: 999px;
+}
+
+.adminUserCell img {
+ object-fit: cover;
+}
+
+.adminUserCell div {
+ display: grid;
+ gap: 3px;
+ min-width: 0;
+}
+
+.adminUserCell strong,
+.adminUserCell span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.adminUserCell span {
+ color: #8d9bb0;
+ font-size: 12px;
+}
+
+.adminState {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 42px;
+ color: #aebcd0;
+ font-weight: 800;
+}
+
.limitNote {
margin: 24px 0 0;
color: #8d9bb0;
@@ -1462,6 +1767,27 @@ button {
}
@media (max-width: 900px) {
+ .topbar {
+ height: auto;
+ min-height: 72px;
+ flex-wrap: wrap;
+ gap: 10px;
+ padding: 10px 0;
+ }
+
+ .topbarControls {
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ }
+
+ .accountChip span {
+ max-width: 120px;
+ }
+
+ .creditChip {
+ display: none;
+ }
+
.hero {
grid-template-columns: 1fr;
min-height: auto;
@@ -1544,21 +1870,34 @@ button {
@media (max-width: 640px) {
.topbar {
- height: 64px;
+ min-height: 64px;
}
.brand {
max-width: 205px;
}
+ .topbar nav {
+ max-width: 100%;
+ overflow-x: auto;
+ }
+
.topbar nav a {
padding: 0 8px;
}
.topbarControls {
+ justify-content: flex-start;
+ width: 100%;
gap: 6px;
}
+ .userMenu {
+ flex-wrap: wrap;
+ }
+
+ .accountButton,
+ .userMenu,
.languageSwitch {
min-height: 38px;
}
@@ -1682,4 +2021,22 @@ button {
.previewColumns {
grid-template-columns: 1fr;
}
+
+ .authDialog,
+ .adminDialog {
+ max-height: calc(100vh - 20px);
+ }
+
+ .authDialog,
+ .adminDialog {
+ padding: 20px 16px;
+ }
+
+ .adminHeader {
+ flex-direction: column;
+ }
+
+ .adminHeader button {
+ width: 100%;
+ }
}
diff --git a/src/supabaseClient.js b/src/supabaseClient.js
new file mode 100644
index 0000000..c1c8a02
--- /dev/null
+++ b/src/supabaseClient.js
@@ -0,0 +1,16 @@
+import { createClient } from '@supabase/supabase-js';
+
+const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
+const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
+
+export const isSupabaseConfigured = Boolean(supabaseUrl && supabaseAnonKey);
+
+export const supabase = isSupabaseConfigured
+ ? createClient(supabaseUrl, supabaseAnonKey, {
+ auth: {
+ autoRefreshToken: true,
+ detectSessionInUrl: true,
+ persistSession: true
+ }
+ })
+ : null;
diff --git a/supabase/migrations/202605090001_user_credits.sql b/supabase/migrations/202605090001_user_credits.sql
new file mode 100644
index 0000000..8b2882f
--- /dev/null
+++ b/supabase/migrations/202605090001_user_credits.sql
@@ -0,0 +1,254 @@
+create extension if not exists "pgcrypto";
+
+create table if not exists public.profiles (
+ id uuid primary key references auth.users(id) on delete cascade,
+ email text not null,
+ full_name text,
+ avatar_url text,
+ role text not null default 'user' check (role in ('user', 'super_admin')),
+ credit_balance integer not null default 0 check (credit_balance >= 0),
+ free_generations_used integer not null default 0 check (free_generations_used >= 0),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create table if not exists public.credit_transactions (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references auth.users(id) on delete cascade,
+ amount integer not null,
+ type text not null check (type in ('grant', 'purchase', 'generation', 'refund', 'adjustment')),
+ source text,
+ reference_id uuid,
+ metadata jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create table if not exists public.generation_reservations (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references auth.users(id) on delete cascade,
+ case_id integer not null,
+ prompt text not null,
+ status text not null default 'pending' check (status in ('pending', 'succeeded', 'failed')),
+ used_free_generation boolean not null default false,
+ credit_amount integer not null default 0 check (credit_amount >= 0),
+ error_code text,
+ created_at timestamptz not null default now(),
+ completed_at timestamptz
+);
+
+create index if not exists profiles_email_idx on public.profiles (lower(email));
+create index if not exists profiles_role_idx on public.profiles (role);
+create index if not exists credit_transactions_user_id_idx on public.credit_transactions (user_id, created_at desc);
+create index if not exists generation_reservations_user_id_idx on public.generation_reservations (user_id, created_at desc);
+create index if not exists generation_reservations_status_idx on public.generation_reservations (status);
+
+alter table public.profiles enable row level security;
+alter table public.credit_transactions enable row level security;
+alter table public.generation_reservations enable row level security;
+
+drop policy if exists "Users can read own profile" on public.profiles;
+create policy "Users can read own profile"
+ on public.profiles for select
+ using ((select auth.uid()) = id);
+
+drop policy if exists "Users can read own credit transactions" on public.credit_transactions;
+create policy "Users can read own credit transactions"
+ on public.credit_transactions for select
+ using ((select auth.uid()) = user_id);
+
+drop policy if exists "Users can read own generation reservations" on public.generation_reservations;
+create policy "Users can read own generation reservations"
+ on public.generation_reservations for select
+ using ((select auth.uid()) = user_id);
+
+create or replace function public.set_updated_at()
+returns trigger
+language plpgsql
+set search_path = public
+as $$
+begin
+ new.updated_at = now();
+ return new;
+end;
+$$;
+
+drop trigger if exists profiles_set_updated_at on public.profiles;
+create trigger profiles_set_updated_at
+ before update on public.profiles
+ for each row
+ execute function public.set_updated_at();
+
+create or replace function public.reserve_generation_usage(
+ p_user_id uuid,
+ p_case_id integer,
+ p_prompt text
+)
+returns table (
+ reservation_id uuid,
+ used_free_generation boolean,
+ credit_amount integer,
+ free_generations_used integer,
+ credit_balance integer
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_profile public.profiles%rowtype;
+ v_reservation_id uuid;
+begin
+ select *
+ into v_profile
+ from public.profiles
+ where id = p_user_id
+ for update;
+
+ if not found then
+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';
+ end if;
+
+ if v_profile.free_generations_used < 1 then
+ update public.profiles
+ set free_generations_used = free_generations_used + 1
+ where id = p_user_id
+ returning * into v_profile;
+
+ insert into public.generation_reservations (
+ user_id,
+ case_id,
+ prompt,
+ used_free_generation,
+ credit_amount
+ )
+ values (p_user_id, p_case_id, p_prompt, true, 0)
+ returning id into v_reservation_id;
+
+ return query
+ select v_reservation_id, true, 0, v_profile.free_generations_used, v_profile.credit_balance;
+ return;
+ end if;
+
+ if v_profile.credit_balance >= 1 then
+ update public.profiles
+ set credit_balance = credit_balance - 1
+ where id = p_user_id
+ returning * into v_profile;
+
+ insert into public.generation_reservations (
+ user_id,
+ case_id,
+ prompt,
+ used_free_generation,
+ credit_amount
+ )
+ values (p_user_id, p_case_id, p_prompt, false, 1)
+ returning id into v_reservation_id;
+
+ insert into public.credit_transactions (
+ user_id,
+ amount,
+ type,
+ source,
+ reference_id,
+ metadata
+ )
+ values (
+ p_user_id,
+ -1,
+ 'generation',
+ 'case_generation_test',
+ v_reservation_id,
+ jsonb_build_object('caseId', p_case_id)
+ );
+
+ return query
+ select v_reservation_id, false, 1, v_profile.free_generations_used, v_profile.credit_balance;
+ return;
+ end if;
+
+ raise exception 'CREDITS_REQUIRED' using errcode = 'P0001';
+end;
+$$;
+
+create or replace function public.complete_generation_reservation(
+ p_reservation_id uuid
+)
+returns void
+language plpgsql
+security definer
+set search_path = public
+as $$
+begin
+ update public.generation_reservations
+ set status = 'succeeded',
+ completed_at = now()
+ where id = p_reservation_id
+ and status = 'pending';
+end;
+$$;
+
+create or replace function public.release_generation_reservation(
+ p_reservation_id uuid,
+ p_error_code text default null
+)
+returns void
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_reservation public.generation_reservations%rowtype;
+begin
+ select *
+ into v_reservation
+ from public.generation_reservations
+ where id = p_reservation_id
+ for update;
+
+ if not found or v_reservation.status <> 'pending' then
+ return;
+ end if;
+
+ if v_reservation.used_free_generation then
+ update public.profiles
+ set free_generations_used = greatest(free_generations_used - 1, 0)
+ where id = v_reservation.user_id;
+ elsif v_reservation.credit_amount > 0 then
+ update public.profiles
+ set credit_balance = credit_balance + v_reservation.credit_amount
+ where id = v_reservation.user_id;
+
+ insert into public.credit_transactions (
+ user_id,
+ amount,
+ type,
+ source,
+ reference_id,
+ metadata
+ )
+ values (
+ v_reservation.user_id,
+ v_reservation.credit_amount,
+ 'refund',
+ 'generation_failed',
+ v_reservation.id,
+ jsonb_build_object('caseId', v_reservation.case_id, 'error', p_error_code)
+ );
+ end if;
+
+ update public.generation_reservations
+ set status = 'failed',
+ error_code = p_error_code,
+ completed_at = now()
+ where id = p_reservation_id;
+end;
+$$;
+
+revoke execute on function public.reserve_generation_usage(uuid, integer, text) from public, anon, authenticated;
+revoke execute on function public.complete_generation_reservation(uuid) from public, anon, authenticated;
+revoke execute on function public.release_generation_reservation(uuid, text) from public, anon, authenticated;
+
+grant execute on function public.reserve_generation_usage(uuid, integer, text) to service_role;
+grant execute on function public.complete_generation_reservation(uuid) to service_role;
+grant execute on function public.release_generation_reservation(uuid, text) to service_role;
diff --git a/supabase/migrations/202605090002_auth_policy_lints.sql b/supabase/migrations/202605090002_auth_policy_lints.sql
new file mode 100644
index 0000000..e5ed32d
--- /dev/null
+++ b/supabase/migrations/202605090002_auth_policy_lints.sql
@@ -0,0 +1,25 @@
+create or replace function public.set_updated_at()
+returns trigger
+language plpgsql
+set search_path = public
+as $$
+begin
+ new.updated_at = now();
+ return new;
+end;
+$$;
+
+drop policy if exists "Users can read own profile" on public.profiles;
+create policy "Users can read own profile"
+ on public.profiles for select
+ using ((select auth.uid()) = id);
+
+drop policy if exists "Users can read own credit transactions" on public.credit_transactions;
+create policy "Users can read own credit transactions"
+ on public.credit_transactions for select
+ using ((select auth.uid()) = user_id);
+
+drop policy if exists "Users can read own generation reservations" on public.generation_reservations;
+create policy "Users can read own generation reservations"
+ on public.generation_reservations for select
+ using ((select auth.uid()) = user_id);