-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.ts
122 lines (111 loc) · 3.36 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import NextAuth, { NextAuthConfig } from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "./app/lib/prisma";
import { z } from 'zod';
import { type DefaultSession } from "next-auth";
import { JWT } from "next-auth/jwt";
import Credentials from "next-auth/providers/credentials";
import bcrypt from 'bcrypt';
import { User } from "@prisma/client";
import { authProviderConfigList } from "./auth.config";
// get user from db
async function getUser(email: string): Promise<User | undefined | null> {
try {
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
throw new Error('Failed to fetch user.');
}
}
// declare custom user properties
declare module "next-auth" {
/**
* Returned by `auth`, `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface User {
role: string;
}
interface Session {
user: {
role: string;
/**
* By default, TypeScript merges new interface properties and overwrites existing ones.
* In this case, the default session user properties will be overwritten,
* with the new ones defined above. To keep the default session user properties,
* you need to add them back into the newly declared interface.
*/
} & DefaultSession["user"];
}
}
declare module "@auth/core/adapters" {
interface AdapterUser {
role: string;
}
}
declare module "next-auth/jwt" {
/** Returned by the `jwt` callback and `auth`, when using JWT sessions */
interface JWT {
role: string;
}
}
// credentials setup for admin email/password login
const credentialsConfig = Credentials({
// The credentials object is used to define the fields used to log in
credentials: {
email: {
label: 'Email',
type: 'email',
},
password: {
label: 'Password',
type: 'password',
},
},
// The authorize callback validates credentials
authorize: async (credentials) => {
// Validate the credentials for the user
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials);
// If the credentials are valid, return the user object
if (parsedCredentials.success) {
const { email, password } = parsedCredentials.data;
const user = await getUser(email);
// If user does not exist or password is missing, throw an error
if (!user || !user.password) return null;
const passwordsMatch = await bcrypt.compare(password, user.password);
// If the password is correct, return the user object
if (passwordsMatch) return user;
}
return null;
},
})
// auth config
export const authConfig = {
adapter: PrismaAdapter(prisma),
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role;
}
return token;
},
async session({ session, token }) {
if (token.sub) {
session.user.id = token.sub;
}
session.user.role = token.role;
return session;
},
},
session: {
strategy: "jwt",
},
providers: [...authProviderConfigList.providers, credentialsConfig ],
} satisfies NextAuthConfig;
export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);