File size: 11,910 Bytes
5ef6e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { Router } from "express";
import bcrypt from "bcryptjs";
import { randomUUID } from "crypto";
import { db, usersTable, imagesTable, apiKeysTable, configTable, creditTransactionsTable } from "@workspace/db";
import { eq, count, desc, sql, inArray } from "drizzle-orm";
import { requireJwtAuth } from "./auth";
import { refreshAccessToken, encrypt, getStoredCredentials } from "./config";
import multer from "multer";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  endpoint: process.env.S3_ENDPOINT || "https://s3.hi168.com",
  region: "us-east-1",
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY || "",
    secretAccessKey: process.env.S3_SECRET_KEY || "",
  },
  forcePathStyle: true,
});
const S3_BUCKET = process.env.DEFAULT_OBJECT_STORAGE_BUCKET_ID || "hi168-25517-1756t1kf";
const S3_PUBLIC_BASE = `${process.env.S3_ENDPOINT || "https://s3.hi168.com"}/${S3_BUCKET}`;

const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 } });

const OTP_KEY = "bookmarklet_otp";

const router = Router();

async function requireAdmin(req: any, res: any, next: any) {
  const user = await db
    .select({ isAdmin: usersTable.isAdmin })
    .from(usersTable)
    .where(eq(usersTable.id, req.jwtUserId))
    .limit(1);
  if (!user[0]?.isAdmin) {
    return res.status(403).json({ error: "Forbidden" });
  }
  next();
}

router.use(requireJwtAuth);
router.use(requireAdmin);

router.get("/stats", async (_req, res) => {
  const [userCount] = await db.select({ count: count() }).from(usersTable);
  const [imageCount] = await db.select({ count: count() }).from(imagesTable);
  const [apiKeyCount] = await db.select({ count: count() }).from(apiKeysTable);
  res.json({
    users: Number(userCount.count),
    images: Number(imageCount.count),
    apiKeys: Number(apiKeyCount.count),
  });
});

router.get("/users", async (_req, res) => {
  const users = await db
    .select({
      id: usersTable.id,
      email: usersTable.email,
      displayName: usersTable.displayName,
      isAdmin: usersTable.isAdmin,
      createdAt: usersTable.createdAt,
    })
    .from(usersTable)
    .orderBy(desc(usersTable.createdAt));
  res.json({ users });
});

router.put("/users/:id", async (req, res) => {
  const id = Number(req.params.id);
  const { displayName, isAdmin, password } = req.body as {
    displayName?: string;
    isAdmin?: boolean;
    password?: string;
  };

  const updates: Partial<typeof usersTable.$inferInsert> = {};
  if (typeof displayName !== "undefined") updates.displayName = displayName || null;
  if (typeof isAdmin === "boolean") updates.isAdmin = isAdmin;
  if (password) {
    if (password.length < 6) return res.status(400).json({ error: "Password must be at least 6 characters" });
    updates.passwordHash = await bcrypt.hash(password, 12);
  }

  if (Object.keys(updates).length === 0) {
    return res.status(400).json({ error: "Nothing to update" });
  }

  const [updated] = await db
    .update(usersTable)
    .set(updates)
    .where(eq(usersTable.id, id))
    .returning({
      id: usersTable.id,
      email: usersTable.email,
      displayName: usersTable.displayName,
      isAdmin: usersTable.isAdmin,
    });

  if (!updated) return res.status(404).json({ error: "User not found" });
  res.json(updated);
});

router.delete("/users/:id", async (req, res) => {
  const id = Number(req.params.id);
  if (id === req.jwtUserId) {
    return res.status(400).json({ error: "Cannot delete yourself" });
  }
  await db.delete(apiKeysTable).where(eq(apiKeysTable.userId, String(id)));
  const deleted = await db.delete(usersTable).where(eq(usersTable.id, id)).returning({ id: usersTable.id });
  if (!deleted.length) return res.status(404).json({ error: "User not found" });
  res.json({ success: true });
});

router.get("/config", async (_req, res) => {
  const rows = await db.select().from(configTable).orderBy(configTable.key);
  res.json({ config: rows });
});

const CONFIG_KEY_MAP: Record<string, string> = {
  refresh_token: "geminigen_refresh_token",
  access_token: "geminigen_bearer_token",
  capsolver_api_key: "capsolver_api_key",
  playwright_solver_url: "playwright_solver_url",
  playwright_solver_secret: "playwright_solver_secret",
  yescaptcha_api_key: "yescaptcha_api_key",
};

router.put("/config", async (req, res) => {
  const { key, value } = req.body as { key?: string; value?: string };
  if (!key || typeof value === "undefined") {
    return res.status(400).json({ error: "key and value are required" });
  }
  const dbKey = CONFIG_KEY_MAP[key];
  if (!dbKey) {
    return res.status(400).json({ error: "Invalid config key" });
  }
  await db
    .insert(configTable)
    .values({ key: dbKey, value, updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value, updatedAt: new Date() } });
  res.json({ success: true });
});

router.get("/setup-status", async (_req, res) => {
  const row = await db
    .select({ key: configTable.key })
    .from(configTable)
    .where(eq(configTable.key, "geminigen_refresh_token"))
    .limit(1);
  res.json({ refreshTokenConfigured: row.length > 0 });
});

router.post("/setup", async (req, res) => {
  const { refreshToken } = req.body as { refreshToken?: string };
  if (!refreshToken?.trim()) {
    return res.status(400).json({ error: "refreshToken is required" });
  }
  const value = refreshToken.trim();
  if (value.length < 20) {
    return res.status(400).json({ error: "Token seems too short โ€” please copy the full refresh_token value." });
  }
  await db
    .insert(configTable)
    .values({ key: "geminigen_refresh_token", value, updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value, updatedAt: new Date() } });
  refreshAccessToken().catch(() => {});
  res.json({ success: true });
});

// Save geminigen.ai credentials for auto-renewal
router.post("/credentials", requireJwtAuth, requireAdmin, async (req, res) => {
  const { username, password } = req.body as { username?: string; password?: string };
  if (!username?.trim() || !password?.trim()) {
    return res.status(400).json({ error: "username and password are required" });
  }
  await db
    .insert(configTable)
    .values({ key: "geminigen_username", value: username.trim(), updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value: username.trim(), updatedAt: new Date() } });
  const encPass = encrypt(password.trim());
  await db
    .insert(configTable)
    .values({ key: "geminigen_password_enc", value: encPass, updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value: encPass, updatedAt: new Date() } });

  // Try to login with new credentials in background (may fail if Turnstile solver not configured)
  // Do NOT block saving credentials on login success โ€” Turnstile may prevent immediate login
  refreshAccessToken().then((tok) => {
    if (tok) console.log("[admin] Credential login succeeded after save");
    else console.warn("[admin] Credential login failed after save (Turnstile may be required โ€” token will refresh later)");
  }).catch(() => {});
  res.json({ success: true, note: "Credentials saved. Token will refresh automatically." });
});

// Check credential configuration status
router.get("/credentials", requireJwtAuth, requireAdmin, async (_req, res) => {
  const creds = await getStoredCredentials();
  res.json({
    configured: !!creds,
    username: creds?.username ?? null,
  });
});

// Delete stored credentials
router.delete("/credentials", requireJwtAuth, requireAdmin, async (_req, res) => {
  await db.delete(configTable).where(eq(configTable.key, "geminigen_username"));
  await db.delete(configTable).where(eq(configTable.key, "geminigen_password_enc"));
  res.json({ success: true });
});

// Generate a short-lived OTP for the bookmarklet token sync
router.post("/bookmarklet-otp", async (_req, res) => {
  const otp = randomUUID();
  const expiresAt = Date.now() + 10 * 60 * 1000; // 10 minutes
  await db
    .insert(configTable)
    .values({ key: OTP_KEY, value: `${otp}:${expiresAt}`, updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value: `${otp}:${expiresAt}`, updatedAt: new Date() } });
  res.json({ otp, expiresInSeconds: 600 });
});

// โ”€โ”€ Site Config (logo, google ads, credits settings) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
const SITE_CONFIG_KEYS = [
  "logo_url", "site_name",
  "enable_credits", "image_gen_cost", "video_gen_cost", "signup_credits",
  "google_ads_enabled", "google_ads_client", "google_ads_slot",
];

router.get("/site-config", async (_req, res) => {
  const rows = await db
    .select()
    .from(configTable)
    .where(inArray(configTable.key, SITE_CONFIG_KEYS));
  const config: Record<string, string> = {};
  for (const row of rows) config[row.key] = row.value;
  res.json(config);
});

router.put("/site-config", async (req, res) => {
  const updates = req.body as Record<string, string>;
  for (const [key, value] of Object.entries(updates)) {
    if (!SITE_CONFIG_KEYS.includes(key)) continue;
    await db
      .insert(configTable)
      .values({ key, value: String(value), updatedAt: new Date() })
      .onConflictDoUpdate({ target: configTable.key, set: { value: String(value), updatedAt: new Date() } });
  }
  res.json({ success: true });
});

// โ”€โ”€ Logo upload โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
router.post("/logo", upload.single("logo"), async (req, res) => {
  const file = (req as any).file as Express.Multer.File | undefined;
  if (!file) return res.status(400).json({ error: "No file uploaded" });

  const ext = file.originalname.split(".").pop()?.toLowerCase() || "png";
  const key = `logos/site-logo.${ext}`;

  await s3.send(new PutObjectCommand({
    Bucket: S3_BUCKET,
    Key: key,
    Body: file.buffer,
    ContentType: file.mimetype,
    ACL: "public-read",
  }));

  const url = `${S3_PUBLIC_BASE}/${key}?t=${Date.now()}`;
  await db
    .insert(configTable)
    .values({ key: "logo_url", value: url, updatedAt: new Date() })
    .onConflictDoUpdate({ target: configTable.key, set: { value: url, updatedAt: new Date() } });

  res.json({ success: true, url });
});

// โ”€โ”€ Credits management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
router.get("/credits", async (_req, res) => {
  const users = await db
    .select({
      id: usersTable.id,
      email: usersTable.email,
      displayName: usersTable.displayName,
      credits: usersTable.credits,
      isAdmin: usersTable.isAdmin,
    })
    .from(usersTable)
    .orderBy(desc(usersTable.createdAt));
  res.json({ users });
});

router.post("/credits/:userId/adjust", async (req, res) => {
  const userId = Number(req.params.userId);
  const { amount, description } = req.body as { amount?: number; description?: string };
  if (!amount || isNaN(amount)) return res.status(400).json({ error: "amount is required" });

  const [user] = await db
    .update(usersTable)
    .set({ credits: sql`GREATEST(0, ${usersTable.credits} + ${amount})` })
    .where(eq(usersTable.id, userId))
    .returning({ credits: usersTable.credits });

  if (!user) return res.status(404).json({ error: "User not found" });

  await db.insert(creditTransactionsTable).values({
    userId,
    amount,
    type: amount > 0 ? "grant" : "deduct",
    description: description || (amount > 0 ? "็ฎก็†ๅ“กๆ‰‹ๅ‹•ๅขžๅŠ " : "็ฎก็†ๅ“กๆ‰‹ๅ‹•ๆ‰ฃ้™ค"),
  });

  res.json({ success: true, newBalance: user.credits });
});

export { OTP_KEY, requireAdmin, SITE_CONFIG_KEYS };
export default router;