-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
auth.ts
306 lines (276 loc) · 6.76 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { NextAuthOptions, User } from "next-auth"
import GitHubProvider from "next-auth/providers/github"
import KeycloakProvider from "next-auth/providers/keycloak"
import CredentialsProvider from "next-auth/providers/credentials"
import { prisma } from "@lib/server/prisma"
import config from "@lib/config"
import * as crypto from "crypto"
import {
isCredentialEnabled,
isGithubEnabled,
isKeycloakEnabled
} from "./auth-props"
const credentialsOptions = () => {
const options: Record<string, unknown> = {
username: {
label: "Username",
required: true,
type: "text"
},
password: {
label: "Password",
required: true,
type: "password"
}
}
if (config.registration_password) {
options["registration_password"] = {
label: "Server Password",
type: "password",
optional: true
}
}
return options
}
const providers = () => {
const providers = []
if (isGithubEnabled()) {
providers.push(
GitHubProvider({
clientId: config.github_client_id,
clientSecret: config.github_client_secret
})
)
}
if (isKeycloakEnabled()) {
const keycloak = KeycloakProvider({
clientId: config.keycloak_client_id,
clientSecret: config.keycloak_client_secret,
issuer: config.keycloak_issuer,
token: {
async request(ctx) {
const { client, provider, params, checks } = ctx
const tokens = await client.callback(
provider.callbackUrl,
params,
checks
)
if ("refresh_expires_in" in tokens) {
tokens.refresh_token_expires_in = tokens.refresh_expires_in
delete tokens.refresh_expires_in
}
delete tokens["not-before-policy"]
return { tokens }
}
}
})
const originalKeycloakProfile = keycloak.profile
keycloak.profile = async (profile, tokens) => {
const originalProfile = await originalKeycloakProfile(profile, tokens)
const newProfile: User & { displayName?: string | null } = {
...originalProfile,
displayName: originalProfile.name ?? null
}
return newProfile
}
providers.push(keycloak)
}
if (isCredentialEnabled()) {
providers.push(
CredentialsProvider({
name: "Drift",
// @ts-expect-error TODO: fix types
credentials: credentialsOptions() as unknown,
async authorize(credentials) {
if (!credentials || !credentials.username || !credentials.password) {
throw new Error("Missing credentials")
}
if (credentials.username.length < 3) {
throw new Error("Username must be at least 3 characters")
}
if (credentials.password.length < 3) {
throw new Error("Password must be at least 3 characters")
}
const user = await prisma.user.findUnique({
where: {
username: credentials.username
},
select: {
id: true,
username: true,
displayName: true,
role: true,
password: true
}
})
const hashedPassword = crypto
.createHash("sha256")
.update(credentials.password + config.nextauth_secret)
.digest("hex")
if (credentials.signingIn === "true") {
if (
user?.password &&
crypto.timingSafeEqual(
Buffer.from(user.password),
Buffer.from(hashedPassword)
)
) {
return user
} else {
throw new Error("Incorrect username or password")
}
} else {
if (config.registration_password) {
if (!credentials.registration_password) {
throw new Error("Missing registration password")
}
if (
credentials.registration_password !==
config.registration_password
) {
throw new Error("Incorrect registration password")
}
}
if (user) {
throw new Error("Username already taken")
}
const newUser = await prisma.user.create({
data: {
username: credentials.username,
displayName: credentials.username,
role: "user",
password: hashedPassword,
name: credentials.username
}
})
return newUser
}
}
})
)
}
return providers
}
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt"
},
pages: {
signIn: "/signin",
error: "/signin"
},
providers: providers(),
events: {
createUser: async ({ user }) => {
const totalUsers = await prisma.user.count()
if (config.enable_admin && totalUsers === 1) {
await prisma.user.update({
where: {
id: user.id
},
data: {
role: "admin"
}
})
}
if (!user.username) {
await prisma.user.update({
where: {
id: user.id
},
data: {
username: user.name?.replace(/ /g, "-")
}
})
}
}
},
callbacks: {
async session({ token, session }) {
if (token) {
session.user.id = token.id
session.user.name = token.name
session.user.email = token.email
session.user.image = token.picture
session.user.role = token.role
session.user.sessionToken = token.sessionToken
}
return session
},
async jwt({ token, user }) {
const dbUser = await prisma.user.findFirst({
where: {
OR: [
{
username: user?.username
}
]
}
})
if (!dbUser) {
// TODO: user should be defined? should we invalidate/signout?
if (user) {
token.id = user.id
}
return token
}
return {
id: dbUser.id,
name: dbUser.displayName,
email: dbUser.email,
picture: dbUser.image,
role: dbUser.role || "user",
username: dbUser.username,
sessionToken: token.sessionToken
}
},
async redirect({ url, baseUrl }) {
if (url.startsWith(baseUrl)) return url
if (url.startsWith("/signedout")) {
const userIdFound = url.match(/userId=([^?&]+)/)
let userId = null
if (userIdFound?.length === 2) {
userId = userIdFound[1]
}
if (!userId) {
return baseUrl
}
const account = await prisma.account.findFirst({
where: {
AND: [
{
userId
}
]
}
})
let ssoLogoutUrl = null
let idToken = null
let clientId = null
// OpenID Connect Logout
if (account?.provider === "keycloak") {
ssoLogoutUrl = `${config.keycloak_issuer}/protocol/openid-connect/logout`
idToken = account.id_token
clientId = config.keycloak_client_id
}
if (!ssoLogoutUrl) {
return baseUrl
}
let signoutWithRedirectUrl = `${ssoLogoutUrl}?post_logout_redirect_uri=${encodeURIComponent(
baseUrl
)}`
if (idToken) {
signoutWithRedirectUrl += `&id_token_hint=${idToken}`
} else if (clientId) {
signoutWithRedirectUrl += `&client_id=${clientId}`
}
return signoutWithRedirectUrl
}
// Allows relative callback URLs
if (url.startsWith("/")) return new URL(url, baseUrl).toString()
return baseUrl
}
}
} as const