-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
56 lines (53 loc) · 1.87 KB
/
auth.js
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
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import { client } from "./sanity/lib/client";
import { CANDIDATEE_QUERY, RECRUITER_QUERY } from "./sanity/lib/queries";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Google],
callbacks: {
async signIn() {
return true;
},
async jwt({ token, user }) {
if (user) {
const email = user.email.toLowerCase();
try {
const candidates = await client.fetch(CANDIDATEE_QUERY, {
email,
});
const recruiters = await client.fetch(RECRUITER_QUERY, {
email,
});
if (candidates.length > 0) {
token.redirectTo = "/dashboard/candidate";
} else if (recruiters.length > 0) {
token.redirectTo = "/dashboard/recruiter";
} else {
token.redirectTo = "/create-profile";
}
} catch (error) {
console.error(
`Error fetching profiles for ${email}:`,
error
);
token.redirectTo = "/create-profile"; // Fallback redirect
}
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.redirectTo = token.redirectTo;
}
return session;
},
async redirect({ url, baseUrl }) {
if (url.startsWith("/")) {
return `${baseUrl}${url}`;
} else if (url.startsWith(baseUrl)) {
return url;
}
return baseUrl;
},
},
});