-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
73 lines (64 loc) · 1.7 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
import { UserSchemaType } from "@/services/mod";
import NextAuth, { type DefaultSession } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { Fetcher } from "@yttiiz/utils";
import { NextResponse } from "next/server";
// Extends User properties.
declare module "next-auth" {
interface Session {
user: {
role: "admin" | "user";
} & DefaultSession["user"];
}
}
export const { auth, handlers, signIn, signOut } = NextAuth({
providers: [
Credentials({
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
const { email, password } = credentials;
const { APP_URL: host } = process.env;
const response = await Fetcher.getData<
{ message: string } | { user: UserSchemaType }
>(
host + "/api/mongodb/user",
`email=${encodeURIComponent(email as string)}&password=${encodeURIComponent(password as string)}`,
);
if (response.ok) {
if ("user" in response.data) {
const { _id, firstname, lastname, email, role } =
response.data.user;
return {
id: _id.toString(),
name: `${firstname} ${lastname}`,
email,
role,
};
}
return null;
}
return null;
},
}),
],
callbacks: {
authorized: async ({ request: { nextUrl }, auth }) => {
const isLoggedIn = !!auth?.user;
const { pathname } = nextUrl;
const role = auth?.user.role ?? "user";
if (pathname.includes("/login") && isLoggedIn) {
return NextResponse.redirect(new URL("/", nextUrl));
}
if (pathname.includes("/admin") && role !== "admin") {
return NextResponse.redirect(new URL("/", nextUrl));
}
return true;
},
},
pages: {
signIn: "/login",
},
});