-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
103 lines (95 loc) · 2.81 KB
/
auth.ts
File metadata and controls
103 lines (95 loc) · 2.81 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
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
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "@/lib/prisma";
import { compare } from "bcryptjs";
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma) as any,
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
userType: { label: "User Type", type: "text" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password || !credentials?.userType) {
return null;
}
const user = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});
if (!user || !user.password) {
return null;
}
// Check if user type matches
if (user.userType !== credentials.userType.toUpperCase()) {
throw new Error("Invalid user type");
}
const isPasswordValid = await compare(credentials.password, user.password);
if (!isPasswordValid) {
return null;
}
return {
id: user.id,
email: user.email,
name: user.name,
userType: user.userType,
};
},
}),
],
pages: {
signIn: "/login",
signOut: "/",
error: "/login", // Error code passed in query string as ?error=
},
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.userType = user.userType;
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (session.user && token.id && token.userType) {
session.user.id = token.id as string;
session.user.userType = token.userType as string;
}
return session;
},
async redirect({ url, baseUrl }) {
// After login, redirect to appropriate dashboard
if (url === '/dashboard') {
const token = await this.jwt?.({ user: null, account: null, profile: null, isNewUser: false });
if (token?.userType === 'CHILD') {
return `${baseUrl}/dashboard/child`;
}
if (token?.userType === 'PARENT') {
return `${baseUrl}/dashboard/parent`;
}
}
// Handle dashboard redirects
if (url.startsWith("/dashboard")) {
return url;
}
// Allows relative callback URLs
if (url.startsWith("/")) {
return `${baseUrl}${url}`;
}
// Allows callback URLs on the same origin
if (new URL(url).origin === baseUrl) {
return url;
}
return baseUrl;
},
},
secret: process.env.NEXTAUTH_SECRET,
};