forked from CRModders/cosmic-mod-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
193 lines (166 loc) · 5.93 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// This file is part of Cosmic Reach Mod Manager.
//
// Cosmic Reach Mod Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// Cosmic Reach Mod Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Cosmic Reach Mod Manager. If not, see <https://www.gnu.org/licenses/>.
import { findUserByEmail, findUserById, matchPassword } from "@/app/api/actions/user";
import authConfig from "@/auth.config";
import db from "@/lib/db";
import { parseProfileProvider, parseUsername } from "@/lib/user";
import { PrismaAdapter } from "@auth/prisma-adapter";
import type { DeletedUser, Providers, UserRoles } from "@prisma/client";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { cookies } from "next/headers";
import { deleteSessionToken, setSessionToken } from "./app/api/actions/auth";
import { dbSessionTokenCookieKeyName, maxUsernameLength } from "./config";
declare module "next-auth" {
// Additional types in the User field
interface User {
role?: UserRoles;
userName?: string;
profileImageProvider?: string;
emailVerified: Date;
}
}
export const { handlers, auth, signIn, signOut } = NextAuth({
callbacks: {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
async signIn({ user, account }): Promise<any> {
// Delete any previous session, if exists
// If not done, stale sessions may stack up when usere links and unlinks auth providers
await deleteSessionToken({});
let deletedAccount: DeletedUser | null = null;
if (!user?.userName) {
try {
deletedAccount = await db.deletedUser.delete({
where: { email: user?.email },
});
} catch (error) {}
}
const newRandomUsername = parseUsername(user.id);
user.userName =
deletedAccount?.userName || newRandomUsername.slice(0, Math.min(maxUsernameLength, newRandomUsername.length));
user.profileImageProvider = account.provider;
return true;
},
// Returns the session object when using auth() function and useSession() also i guess
async session({ session, token }) {
if (token?.sub) {
session.user.id = token.sub;
}
const dbSessionToken = cookies().get(dbSessionTokenCookieKeyName)?.value;
if (dbSessionToken) {
session.sessionToken = dbSessionToken;
}
return session;
},
async jwt({ token }) {
return token;
},
},
// Events are fired when an action happens, callback functions execute first and then the event functions
events: {
...authConfig,
// Event fired when user links a provider account. To link a provider account a user has to login using a provider that has the same email as his account on site
async linkAccount({ user, account }) {
const userData = await findUserById(user.id);
const data: {
emailVerified?: Date;
profileImageProvider?: Providers;
} = {};
if (!userData?.emailVerified || !userData?.profileImageProvider) {
// Set the email verified to the date if it's null i.e. this is a new registration
if (!userData?.emailVerified) {
data.emailVerified = new Date();
}
if (!userData?.profileImageProvider) {
data.profileImageProvider = parseProfileProvider(account.provider);
}
// Update the data in the database
await db.user.update({
where: {
id: user?.id,
},
data,
});
}
},
// Event fired when the user signs in
async signIn({ user, account, profile }) {
// Delete the previous provider account if the user signs in using the same provider with different email
const accountsData = await db.account.findMany({
where: {
userId: user?.id,
provider: account?.provider,
},
});
for (const providerAccount of accountsData) {
if (
providerAccount?.provider === account?.provider &&
providerAccount?.providerAccountId !== account?.providerAccountId
) {
await db.account.delete({
where: {
id: providerAccount?.id,
},
});
}
}
// profile?.image_url ==> Discord
// profile?.picture ==> Google
// profile?.avatar_url ==> Github and Gitlab
const profileImageLink = profile?.image_url || profile?.picture || profile?.avatar_url;
await db.account.updateMany({
where: {
userId: user?.id,
provider: account?.provider,
providerAccountId: account?.providerAccountId,
},
data: {
profileImage: profileImageLink,
providerAccountEmail: profile?.email,
},
});
await setSessionToken(user?.id, account?.provider);
},
async signOut() {
await deleteSessionToken({});
},
},
adapter: PrismaAdapter(db),
session: {
strategy: "jwt",
},
secret: process.env.AUTH_SECRET,
pages: {
signIn: "/login",
// newUser: "/onboarding",
error: "/login",
},
providers: [
...authConfig.providers,
// The credential provider is being added here instead of auth.config.ts file because that config file is used inside of middleware and that does not support db (prisma + MongoDB) integration
CredentialsProvider({
id: "credentials",
name: "Credentials",
// The signIn logic of the credentials provider
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const userData = await db.user.findUnique({
where: { email: credentials.email as string },
});
const isCorrectPassword = await matchPassword(credentials?.password as string, userData.password);
if (isCorrectPassword) {
const user = await findUserByEmail(credentials?.email as string);
return user;
}
return null;
},
}),
],
});