forked from chingu-voyages/v51-tier3-team-33
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.config.ts
79 lines (67 loc) · 2.26 KB
/
auth.config.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
import type { NextAuthConfig } from "next-auth";
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
async authorized({ auth, request: { nextUrl } }) {
const isAuthenticated = !!auth?.user; // check if user session exists
const isLandingPage = nextUrl.pathname === '/';
const isDashboard = nextUrl.pathname.startsWith('/dashboard');
const query = new URLSearchParams(nextUrl.search);
const intendedURL = query.get('callbackUrl');
const isLoginPage = nextUrl.pathname.startsWith('/login');
if (isLandingPage) return true;
if (isDashboard) {
if (isAuthenticated) return true;
return false;
} else if (isLoginPage && intendedURL) {
if (isAuthenticated) return Response.redirect(new URL(intendedURL));
}
return true;
},
async session({ session }): Promise<any> {
try {
const response = await fetch(`${process.env.BASE_URL}/api/auth/user/${session.user.email}`)
if (response.status === 404) {
return {};
}
const userData = await response.json();
session.user.id = userData.user._id; // gives the session the user id from the database
return session;
} catch (error) {
console.log(error);
return {};
}
},
async signIn({ account, profile } ): Promise<any> {
try {
const response = await fetch(`${process.env.BASE_URL}/api/auth/user/${profile?.email}`)
if (response.status === 404) {
await fetch(`${process.env.BASE_URL}/api/auth/user`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
firstName: profile?.given_name,
lastName: profile?.family_name,
email: profile?.email,
image: profile?.picture
})
})
}
else { //add user to database
const userData = await response.json();
console.log("User already exists", userData)
}
return true;
} catch (error) {
console.log(error);
return false;
}
}
},
providers: [],
trustHost: true,
} satisfies NextAuthConfig;