-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
79 lines (69 loc) · 2.25 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
77
78
79
import { Lucia, Session, User } from "lucia";
import prisma from "./lib/prisma";
import { PrismaAdapter } from "@lucia-auth/adapter-prisma";
import { cookies } from "next/headers";
import { cache } from "react";
const adapter = new PrismaAdapter(prisma.session, prisma.user)
export const luica = new Lucia(adapter,{
sessionCookie: {
expires: false,
attributes: {
secure: process.env.NODE_ENV === "production"
}
},
getUserAttributes(databaseUserAttributes){
return {
id: databaseUserAttributes.id,
username: databaseUserAttributes.username,
displayName: databaseUserAttributes.displayName,
avatarUrl: databaseUserAttributes.avatarUrl,
googleId: databaseUserAttributes.googleId,
}
}
} )
declare module "lucia" {
interface Register {
Lucia: typeof Lucia
DatabaseUserAttributes: databaseUserAttributes
}
}
interface databaseUserAttributes {
id: string,
username: string,
displayName: string,
avatarUrl: string | null,
googleId: string | null,
}
export const validateRequest = cache(
async(): Promise<
{ user: User, session: Session } | { user: null, session: null }
> => {
const sessionId = cookies().get(luica.sessionCookieName)?.value ?? null
if (!sessionId) {
return {
user: null,
session: null
}
}
const result = await luica.validateSession(sessionId)
try {
if (result.session && result.session.fresh) {
const sessionCookie = luica.createSessionCookie(result.session.id)
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
)
}
if (!result.session) {
const sessionCookie = luica.createBlankSessionCookie()
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
)
}
} catch { }
return result
},
)