-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
95 lines (89 loc) · 2.45 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
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import Github from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import { signInSchema } from "./lib/zod";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Google({
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
profile(profile) {
return { name: profile.name, role: "admin" };
},
}),
Github({
profile(profile) {
return { name: profile.name, role: "admin" };
},
}),
Credentials({
credentials: {
email: { label: "Email", type: "email", placeholder: "[email protected]" },
password: {
label: "Password",
type: "password",
placeholder: "sua senha",
},
},
async authorize(credentials) {
let user = null;
// validate credentials
const parsedCredentials = signInSchema.safeParse(credentials);
if (!parsedCredentials.success) {
console.error("Invalid credentials", parsedCredentials.error.errors);
return null;
}
// get user
user = {
id: "1",
name: "Aditya Singh",
email: "[email protected]",
role: "admin",
};
if (!user) {
console.log("Invalid credentials");
return null;
}
return user;
},
}),
],
callbacks: {
authorized({ request: { nextUrl }, auth }) {
const isLoggedIn = !!auth?.user;
const { pathname } = nextUrl;
const role = (auth?.user.role as string) || "user";
if (pathname.startsWith("/auth/signin") && isLoggedIn) {
return Response.redirect(new URL("/", nextUrl));
}
if (pathname.startsWith("/page2") && role !== "admin") {
return Response.redirect(new URL("/", nextUrl));
}
return !!auth;
},
jwt({ token, user, trigger, session }) {
if (user) {
token.id = user.id as string;
token.role = user.role as string;
}
if (trigger === "update" && session) {
token = { ...token, ...session };
}
return token;
},
session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
return session;
},
},
pages: {
signIn: "/auth/signin",
},
});