this repo has no description
at main 76 lines 1.7 kB view raw
1import { eq } from "drizzle-orm"; 2import type { SocketAddress } from "elysia/universal"; 3import { nanoid } from "nanoid"; 4 5import db from "../db"; 6import { schema } from "../db"; 7 8export const createSession = async ( 9 userId: number, 10 req: Request, 11 ip?: SocketAddress, 12) => { 13 const sessionId = nanoid(); 14 const expiryDays = 7; 15 const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * expiryDays; 16 17 const userAgent = req.headers.get("user-agent") || null; 18 const ipAddress = 19 req.headers.get("x-forwarded-for") || 20 req.headers.get("cf-connecting-ip") || 21 ip?.address || 22 null; 23 24 await db 25 .insert(schema.sessions) 26 .values({ 27 id: sessionId, 28 userId, 29 expiresAt, 30 userAgent, 31 ipAddress, 32 }) 33 .returning(); 34 35 return { 36 sessionId, 37 expiresAt, 38 }; 39}; 40 41export const validateSession = async (sessionId: string) => { 42 const session = await db.query.sessions.findFirst({ 43 where: eq(schema.sessions.id, sessionId), 44 with: { 45 user: true, 46 }, 47 }); 48 49 if (!session) return null; 50 51 const now = Math.floor(Date.now() / 1000); 52 if (session.expiresAt < now) { 53 await db.delete(schema.sessions).where(eq(schema.sessions.id, sessionId)); 54 return null; 55 } 56 57 return session; 58}; 59 60export const deleteSession = async (sessionId: string) => { 61 await db 62 .delete(schema.sessions) 63 .where(eq(schema.sessions.id, sessionId)) 64 .returning(); 65}; 66 67export const renewSession = async (sessionId: string, days = 7) => { 68 const newExpiresAt = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * days; 69 70 await db 71 .update(schema.sessions) 72 .set({ expiresAt: newExpiresAt }) 73 .where(eq(schema.sessions.id, sessionId)); 74 75 return newExpiresAt; 76};