-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
94 lines (83 loc) · 2.46 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
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { baseURL } from "./utils/constants";
// Define authentication providers
const providers = [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
];
const missingVars: string[] = [];
// Utility to check for missing environment variables
const isMissing = (name: string, envVar: string | undefined) => {
if (!envVar) {
missingVars.push(name);
}
};
// Validate required environment variables
isMissing("GOOGLE_CLIENT_ID", process.env.GOOGLE_CLIENT_ID);
isMissing("GOOGLE_CLIENT_SECRET", process.env.GOOGLE_CLIENT_SECRET);
if (missingVars.length > 0) {
const message = `The following environment variables are missing: ${missingVars.join(", ")}`;
console.warn(`\u001b[33mwarn:\u001b[0m ${message}`);
}
export const providerMap = providers.map((provider) => ({
id: provider.id as "google",
name: provider.name,
}));
export const { handlers, auth, signIn, signOut } = NextAuth({
providers,
secret: process.env.AUTH_SECRET,
cookies: {
sessionToken: {
name: "next-auth.session-token",
options: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
},
},
},
pages: {
signIn: "/auth/signin",
},
callbacks: {
async signIn({ user, account }) {
if (account?.provider === "google") {
try {
const response = await fetch(`${baseURL}/api/auth`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user: {
email: user.email,
name: user.name,
image: user.image,
},
}),
});
const data = await response.json();
if (data.user) {
console.log("User data stored in MongoDB:", data.user);
} else {
console.error("Error storing user:", data.error);
}
} catch (error) {
console.error("API error during sign-in:", error);
}
}
return true; // Continue sign-in
},
async authorized({ request, auth }) {
const isLoggedIn = !!auth?.user;
const isPublicPage = request.nextUrl.pathname.startsWith("/public");
if (isPublicPage || isLoggedIn) {
return true;
}
return false;
},
},
});