-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.ts
77 lines (69 loc) · 1.83 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
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { getUserFromDb } from "./services/users";
import { ZodError } from "zod";
import { signInSchema } from "./lib/signInSchema";
import bcrypt from "bcryptjs";
import { Account, User as AuthUser } from "next-auth";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
try {
let user = null;
const { email, password } = await signInSchema.parseAsync(
credentials
);
// logic to verify if user exists
user = await getUserFromDb(email);
if (!user) {
throw new Error("User not found.");
}
const checkPassword = bcrypt.compareSync(password, user.password);
if (!checkPassword) throw new Error("Incorrect Password.");
return user;
} catch (error) {
if (error instanceof Error) {
if (error instanceof ZodError) {
return null;
}
throw new Error(error.message);
}
return null;
}
},
}),
],
callbacks: {
async signIn({
user,
account,
}: {
user: AuthUser;
account: Account | null;
}) {
if (account?.provider == "credentials") {
return true;
}
return false;
},
async redirect({ url, baseUrl }) {
if (url.startsWith("/")) return `${baseUrl}${url}`;
if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
session: {
strategy: "jwt",
},
secret: `${process.env.NEXTAUTH_SECRET}`,
pages: {
signIn: "/login",
},
trustHost: true,
// trustHostedDomain: true,
});