From 64fe4397c3c78ce14111cdb50c78dc82281ba85d Mon Sep 17 00:00:00 2001 From: Azalea <22280294+hykilpikonna@users.noreply.github.com> Date: Tue, 18 Nov 2025 01:44:51 +0800 Subject: [PATCH] [+] User DB --- src/lib/server/user.ts | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/lib/server/user.ts diff --git a/src/lib/server/user.ts b/src/lib/server/user.ts new file mode 100644 index 0000000..b20f1ef --- /dev/null +++ b/src/lib/server/user.ts @@ -0,0 +1,57 @@ +import { db } from "./db" + +type UserDocument = { + _id?: any + registUA: string + createdAt: Date + sessions: string[] + syncCode?: string + syncCodeCreated?: Date + + // User data + data?: any +} + +const users = db.collection("users") + +// Build an index once so session lookups stay fast even as the collection grows. +void users.createIndex({ sessions: 1 }, { name: "users_sessions_idx" }) +void users.createIndex({ syncCode: 1 }, { name: "users_sync_code_idx" }) + +/** + * Create a new user and return the session token. + * @param registUA User's registration User Agent + * @returns New session token + */ +export async function createUser(registUA: string): Promise { + const ses = `${crypto.randomUUID()}-${Date.now().toString(36)}` + await users.insertOne({ registUA, createdAt: new Date(), sessions: [ses] }) + return ses +} + +/** + * Find a user by session token. + * @returns User document or null if not found + */ +export const getUserBySession = (session: string) => users.findOne({ sessions: session }) +export async function login(session: string): Promise { + const user = await getUserBySession(session) + if (!user) throw new Error('Invalid session') + return user +} + +/** + * 创建引继码 (sync code) 以便在其他设备登录。 + * @returns New sync code + */ +export async function createSyncCode(session: string): Promise { + const user = await login(session) + + // Sync code is 4 * 5 numbers + const code = Array.from({ length: 4 }, () => Math.floor(Math.random() * 100000).toString().padStart(5, '0')).join('-') + await users.updateOne({ _id: user._id }, { $set: { syncCode: code, syncCodeCreated: new Date() } }) + return code +} + + + \ No newline at end of file