-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
49 lines (43 loc) · 1.4 KB
/
auth.ts
File metadata and controls
49 lines (43 loc) · 1.4 KB
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
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { authConfig } from "./auth.config";
import { connectDB } from "@/lib/db/connect";
import { UserModel } from "@/models/User";
import bcrypt from "bcryptjs";
import { loginSchema } from "@/lib/validators/auth.schema";
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
credentials: {
identifier: { label: "Email or Phone", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const parsed = loginSchema.safeParse(credentials);
if (!parsed.success) return null;
await connectDB();
const user = await UserModel.findOne({
$or: [
{ email: parsed.data.identifier.toLowerCase() },
{ phone: parsed.data.identifier },
],
status: "active",
}).select("+password");
if (!user || !user.password) return null;
const isValid = await bcrypt.compare(
parsed.data.password,
user.password
);
if (!isValid) return null;
return {
id: user._id.toString(),
name: user.name,
email: user.email ?? user.phone,
role: user.role,
onboardingCompleted: user.onboardingCompleted,
};
},
}),
],
});