-
Notifications
You must be signed in to change notification settings - Fork 8
/
auth.ts
165 lines (143 loc) · 4.13 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import NextAuth from "next-auth";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { db } from "@/db";
import authConfig from "./auth.config";
import { getUserById } from "./db/api/user";
import {
deleteAccountTokens,
getAccountByProvider,
updateAccountTokens,
getAccountByUser,
refreshAccessToken,
} from "./db/api/account";
export const { handlers, auth, signOut } = NextAuth({
pages: {
signIn: "/auth/login",
},
events: {
async signOut(message) {
try {
// Clean the stale tokens from the account table
if ("token" in message) {
const token = message.token;
if (token?.userId) {
await deleteAccountTokens(token.userId.toString());
}
}
} catch (error) {
console.error("Error occurred at signOut event", error);
}
},
},
adapter: DrizzleAdapter(db),
session: { strategy: "jwt" },
callbacks: {
authorized({ auth }) {
return !!auth;
},
async signIn({ user, account }) {
// Check if user is allowed to sign-in
const email = user?.email;
if (!email) {
return "/auth/login?error=EmailNotFound";
}
try {
if (account && user) {
// If user signs in for very first time then account should be null
const providerAccount = await getAccountByProvider(
account.provider,
account.providerAccountId,
);
// If provider account exists already then update the tokens with the new ones
// As Next-Auth is not doing it properly
// issue: https://github.com/nextauthjs/next-auth/issues/3599
if (providerAccount) {
await updateAccountTokens(account);
}
}
return true;
} catch (error) {
console.error("Error occurred at sign-in event", error);
return false;
}
},
async jwt({ token }) {
// token is not available at initial sign-in
// only account and user are available
if (!token.sub) {
return token;
}
const googleAccount = await getAccountByUser(token.sub);
const expiresAt = googleAccount?.expiresAt;
const refreshToken = googleAccount?.refreshToken;
// Refresh access token if expired;
if (expiresAt && expiresAt * 1000 < Date.now() && refreshToken) {
try {
await refreshAccessToken(refreshToken, token.sub);
} catch (error) {
if (error instanceof RefreshTokenError) {
token.error = error;
}
}
}
const existingUser = await getUserById(token.sub);
if (!existingUser) {
token.error = new UserNotFoundError(
`${token.sub} user-id is not found`,
);
return token;
}
const { name, email } = existingUser;
token.name = name;
token.email = email;
return token;
},
async session({ session, token }) {
if (session.user && token) {
const { name, email, sub, error } = token;
if (!sub || !email) {
// Log user out using this error
const error = new UserNotFoundError(
"No email or sub found in token, this should not happen",
);
session.error = error;
return session;
}
session.user = {
...session.user,
id: sub,
name,
email,
};
// For now only tracking refresh token errors
// As we do not expect any other errors
// User should be logged out on this error
if (
error instanceof RefreshTokenError ||
error instanceof UserNotFoundError
) {
session.error = error;
}
}
return session;
},
},
...authConfig,
});
export class RefreshTokenError extends Error {
constructor(message?: string) {
super(message);
this.name = "RefreshTokenError";
}
}
class UserNotFoundError extends Error {
constructor(message?: string) {
super(message);
this.name = "UserNotFoundError";
}
}
declare module "next-auth" {
interface Session {
error?: RefreshTokenError | UserNotFoundError;
}
}