Download src/lib/auth.ts from lljz66/api: direct link, hf CLI and curl.
- Browser
- Download file 2.3 kB
-
https://huggingface.co/spaces/lljz66/api/resolve/main/src/lib/auth.ts
- Command line
-
hf download hf://spaces/lljz66/api/src/lib/auth.ts
-
curl -L -o auth.ts https://huggingface.co/spaces/lljz66/api/resolve/main/src/lib/auth.ts
2.3 kB
| import "server-only"; | |
| import { cache } from "react"; | |
| import { cookies } from "next/headers"; | |
| import { redirect } from "next/navigation"; | |
| import { randomBytes, scrypt as _scrypt, timingSafeEqual } from "node:crypto"; | |
| import { promisify } from "node:util"; | |
| import { and, eq, gt } from "drizzle-orm"; | |
| import { db } from "@/db"; | |
| import { sessions, users } from "@/db/schema"; | |
| const scrypt = promisify(_scrypt) as ( | |
| pw: string, | |
| salt: Buffer, | |
| len: number, | |
| ) => Promise<Buffer>; | |
| const COOKIE = "hf_sid"; | |
| const MAX_AGE = 60 * 60 * 24 * 30; | |
| export async function hashPassword(pw: string) { | |
| const salt = randomBytes(16); | |
| const key = await scrypt(pw, salt, 64); | |
| return `${salt.toString("hex")}:${key.toString("hex")}`; | |
| } | |
| export async function verifyPassword(pw: string, stored: string) { | |
| const [saltHex, keyHex] = stored.split(":"); | |
| if (!saltHex || !keyHex) return false; | |
| const key = await scrypt(pw, Buffer.from(saltHex, "hex"), 64); | |
| const expected = Buffer.from(keyHex, "hex"); | |
| return key.length === expected.length && timingSafeEqual(key, expected); | |
| } | |
| export async function createSession(userId: string) { | |
| const token = randomBytes(32).toString("hex"); | |
| await db.insert(sessions).values({ | |
| token, | |
| userId, | |
| expiresAt: new Date(Date.now() + MAX_AGE * 1000), | |
| }); | |
| const jar = await cookies(); | |
| jar.set(COOKIE, token, { | |
| httpOnly: true, | |
| sameSite: "lax", | |
| secure: false, | |
| path: "/", | |
| maxAge: MAX_AGE, | |
| }); | |
| } | |
| export async function destroySession() { | |
| const jar = await cookies(); | |
| const token = jar.get(COOKIE)?.value; | |
| if (token) await db.delete(sessions).where(eq(sessions.token, token)); | |
| jar.delete(COOKIE); | |
| } | |
| export const getUser = cache(async () => { | |
| const jar = await cookies(); | |
| const token = jar.get(COOKIE)?.value; | |
| if (!token) return null; | |
| const rows = await db | |
| .select({ | |
| id: users.id, | |
| email: users.email, | |
| name: users.name, | |
| plan: users.plan, | |
| onboarded: users.onboarded, | |
| }) | |
| .from(sessions) | |
| .innerJoin(users, eq(users.id, sessions.userId)) | |
| .where(and(eq(sessions.token, token), gt(sessions.expiresAt, new Date()))) | |
| .limit(1); | |
| return rows[0] ?? null; | |
| }); | |
| export async function requireUser() { | |
| const user = await getUser(); | |
| if (!user) redirect("/login"); | |
| return user; | |
| } |