customer-session.ts 971 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import { cookies } from 'next/headers'
  2. import { db } from './db'
  3. export const CUSTOMER_SESSION_COOKIE = 'customer-session'
  4. export const CUSTOMER_SESSION_DURATION = 7 * 24 * 60 * 60 * 1000 // 7 days
  5. export const MAGIC_LINK_DURATION = 15 * 60 * 1000 // 15 minutes
  6. export type CustomerSessionData = {
  7. customerId: string
  8. organizationId: string
  9. }
  10. export async function getCustomerSession(): Promise<CustomerSessionData | null> {
  11. const cookieStore = await cookies()
  12. const token = cookieStore.get(CUSTOMER_SESSION_COOKIE)?.value
  13. if (!token) return null
  14. const session = await db.customerSession.findUnique({
  15. where: { token },
  16. })
  17. if (!session) return null
  18. if (new Date() > session.expiresAt) {
  19. // Clean up expired session
  20. await db.customerSession.delete({ where: { id: session.id } }).catch(() => {
  21. /* ignore */
  22. })
  23. return null
  24. }
  25. return {
  26. customerId: session.customerId,
  27. organizationId: session.organizationId,
  28. }
  29. }