-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
121 lines (101 loc) · 2.58 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
import { getUserByEmail, getUserById } from "@/db/query/user";
import Credentials from "next-auth/providers/credentials";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import Github from "@auth/core/providers/github";
import Google from "@auth/core/providers/google";
import { LoginSchema } from "@/schemas/login";
import NextAuth from "next-auth";
import { RoleType } from "@/db/schemas";
import authConfig from "@/auth.config";
import bcrypt from "bcryptjs";
import { db } from "@/db/connection";
import {verifyUserEmail} from "@/db/mutation/user";
declare module "next-auth" {
interface User {
role?: RoleType;
}
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
adapter: DrizzleAdapter(db),
session: {
strategy: "jwt",
},
...authConfig,
providers: [
Github({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
Credentials({
async authorize(credentials) {
const validatedFields = LoginSchema.safeParse(credentials);
if (validatedFields.success) {
const { email, password } = validatedFields.data;
let user = await getUserByEmail(email);
if (!user || !user?.password) {
return null;
}
const isPasswordMatched = await bcrypt.compare(
password,
user.password
);
if (isPasswordMatched) {
return user;
}
}
return null;
},
}),
],
callbacks: {
async session({ token, session }) {
if (token.sub && session.user) {
session.user.id = token.sub;
if (token.role) {
session.user.role = token.role as RoleType;
}
}
return session;
},
async jwt({ token }) {
if (token.sub) {
const user = await getUserById(token.sub);
if (user) {
token.role = user.role;
}
}
return token;
},
async signIn({ user, account }) {
if (account?.provider === "credentials") {
if(!user.id) return false;
const existingUser = await getUserById(user.id);
if (!existingUser || !existingUser.emailVerified) {
return false;
}
}
return true;
},
},
events: {
async linkAccount({user}){
if(user.id){
await verifyUserEmail(user.id);
}
}
},
pages: {
signIn: "/auth/login",
error: "/auth/error",
}
});
//EDGE Incompatible...