-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
72 lines (66 loc) · 2.12 KB
/
Copy pathauth.ts
File metadata and controls
72 lines (66 loc) · 2.12 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
import NextAuth, { type NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
import { upsertUserFromGoogleProfile } from "@/lib/users";
import type { AppError } from "@/lib/app-error";
type GoogleProfile = {
sub?: string;
email_verified?: boolean;
};
export const authConfig: NextAuthConfig = {
providers: [
Google({
checks: process.env.NODE_ENV === "production" ? ["pkce", "state"] : ["state"],
}),],
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
},
callbacks: {
async signIn({ user, account, profile }) {
if (account?.provider !== "google") return false;
const googleProfile = profile as GoogleProfile | undefined;
if (!googleProfile?.sub) return false;
if (googleProfile.email_verified !== true) return false;
if (!user.email) return false;
try {
const appUser = await upsertUserFromGoogleProfile({
googleSub: googleProfile.sub,
email: user.email,
name: user.name ?? null,
imageUrl: user.image ?? null,
});
user.googleSub = googleProfile.sub;
user.appUserId = appUser.id;
return true;
} catch (error) {
const appError = error as AppError | undefined;
console.error("Failed to upsert user during sign-in", appError ?? error);
return false;
}
},
async jwt({ token, account, profile, user }) {
if (account?.provider === "google") {
const googleProfile = profile as GoogleProfile | undefined;
if (googleProfile?.sub) {
token.googleSub = googleProfile.sub;
}
}
if (typeof user?.appUserId === "number") {
token.appUserId = user.appUserId;
}
return token;
},
async session({ session, token }) {
if (session.user && typeof token.googleSub === "string") {
session.user.googleSub = token.googleSub;
}
if (session.user && typeof token.appUserId === "number") {
session.user.appUserId = token.appUserId;
}
return session;
},
},
};
export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);