-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
79 lines (76 loc) · 2.04 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 NextAuth, { CredentialsSignin } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import bcrypt from 'bcryptjs';
import prisma from '~/lib/prisma';
import { MONTH } from './constants/time';
class InvalidLoginError extends CredentialsSignin {
code = 'Invalid identifier or password';
}
class NoUserFound extends CredentialsSignin {
code = 'No user found';
}
class PasswordError extends CredentialsSignin {
code = 'Invalid password';
}
export const { handlers, signIn, signOut, auth } = NextAuth({
adapter: PrismaAdapter(prisma),
session: {
strategy: 'jwt',
maxAge: 1 * MONTH({ base: 's' }),
},
providers: [
Credentials({
credentials: {
email: { label: 'Email', type: 'email', placeholder: 'email' },
password: { label: 'Password', type: 'password' },
},
authorize: async (credentials) => {
if (!credentials || !credentials.email || !credentials.password) {
throw new InvalidLoginError();
}
const user = await prisma.user.findUnique({
where: {
email: credentials.email as string,
},
});
if (!user) {
throw new NoUserFound();
}
const isPasswordMatch = bcrypt.compareSync(
credentials.password as string,
user?.password as string,
);
if (!isPasswordMatch) {
throw new PasswordError();
}
return user;
},
}),
],
pages: {
signIn: '/signin',
error: '/signin',
},
callbacks: {
jwt({ token, user, account }) {
if (user) {
token.user = {
name: user.name,
id: user.id,
email: user.email,
image: user.image,
// @ts-ignore
role: user.role,
provider: account?.provider,
};
}
return token;
},
session({ session, token }) {
session.user = token.user;
return session;
},
},
debug: process.env.NODE_ENV !== 'production',
});