-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
76 lines (68 loc) · 1.81 KB
/
auth.ts
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
import { Lucia } from 'lucia'
import { PrismaAdapter } from '@lucia-auth/adapter-prisma'
import prisma from '@/lib/prisma'
import { cache } from 'react'
import type { Session, User } from 'lucia'
import { cookies } from 'next/headers'
const adapter = new PrismaAdapter(prisma.session, prisma.user)
// expect error (see next section)
export const lucia = new Lucia(adapter, {
sessionCookie: {
attributes: {
secure: process.env.NODE_ENV === 'production',
},
expires: false,
},
getUserAttributes: (attributes) => {
return {
name: attributes.name,
email: attributes.email,
diet: attributes.diet,
}
},
})
export const validateRequest = cache(
async (): Promise<
{ user: User; session: Session } | { user: null; session: null }
> => {
const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null
if (!sessionId) {
return {
user: null,
session: null,
}
}
const result = await lucia.validateSession(sessionId)
// next.js throws when you attempt to set cookie when rendering page
try {
if (result.session && result.session.fresh) {
const sessionCookie = lucia.createSessionCookie(result.session.id)
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
)
}
if (!result.session) {
const sessionCookie = lucia.createBlankSessionCookie()
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
)
}
} catch {}
return result
}
)
declare module 'lucia' {
interface Register {
Lucia: typeof lucia
DatabaseUserAttributes: DatabaseUserAttributes
}
}
interface DatabaseUserAttributes {
email: string
name: string
diet: string
}