@cedarjs/auth-dbauth-setup 7.0.1-next.466 → 7.1.0-rc.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,382 +0,0 @@
1
- import type { APIGatewayProxyEvent, Context } from 'aws-lambda'
2
-
3
- import { DbAuthHandler } from '@cedarjs/auth-dbauth-api'
4
- import type { DbAuthHandlerOptions, UserType } from '@cedarjs/auth-dbauth-api'
5
- import {
6
- OAuthHandler,
7
- googleProvider,
8
- githubProvider,
9
- } from '@cedarjs/auth-dbauth-oauth'
10
-
11
- import { cookieName } from 'src/lib/auth'
12
- import { db } from 'src/lib/db'
13
-
14
- // Any request whose path falls under this prefix is routed to the OAuth
15
- // handler instead of the regular username/password dbAuth handler. This
16
- // must match the callback URLs registered with each provider below (e.g.
17
- // `${apiUrl}/auth/oauth/google/callback`).
18
- const OAUTH_BASE_PATH = '/auth/oauth'
19
-
20
- // The base URL of your deployed api side. Used to build the OAuth callback
21
- // URLs registered with each provider's developer console. Update the
22
- // production value once you know your deployed URL.
23
- const apiUrl =
24
- process.env.NODE_ENV === 'development'
25
- ? 'http://localhost:8911'
26
- : 'https://server.com'
27
-
28
- const cookieAttributes = {
29
- HttpOnly: true,
30
- Path: '/',
31
- SameSite: 'Lax' as const,
32
- Secure: process.env.NODE_ENV !== 'development',
33
-
34
- // If you need to allow other domains (besides the api side) access to
35
- // the dbAuth session cookie:
36
- // Domain: 'example.com',
37
- }
38
-
39
- export const handler = async (
40
- event: APIGatewayProxyEvent,
41
- context: Context
42
- ) => {
43
- if (event.path?.includes(OAUTH_BASE_PATH)) {
44
- const oauthHandler = new OAuthHandler(event, context, {
45
- // Provide prisma db client
46
- db: db,
47
-
48
- // The name of the property you'd call on `db` to access your user
49
- // table. i.e. if your Prisma model is named `User` this value would
50
- // be `user`, as in `db.user`
51
- authModelAccessor: 'user',
52
-
53
- // The name of the property you'd call on `db` to access your OAuth
54
- // identity table. i.e. if your Prisma model is named `OAuth` this
55
- // value would be `oAuth`, as in `db.oAuth`
56
- oauthModelAccessor: 'oAuth',
57
-
58
- // A map of what dbAuth calls a field to what your database calls it,
59
- // matching the same fields used by `DbAuthHandler` below
60
- authFields: {
61
- id: 'id',
62
- username: 'email',
63
- hashedPassword: 'hashedPassword',
64
- },
65
-
66
- basePath: OAUTH_BASE_PATH,
67
-
68
- // The configured OAuth providers, keyed by the path segment used in
69
- // `/auth/oauth/{key}/...`. Get client id/secret values from each
70
- // provider's developer console and set them in your `.env` file.
71
- providers: {
72
- // @oauth-provider:google
73
- google: googleProvider({
74
- clientId: process.env.GOOGLE_CLIENT_ID as string,
75
- clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
76
- redirectUri: `${apiUrl}/auth/oauth/google/callback`,
77
- }),
78
- // @oauth-provider:google:end
79
- // @oauth-provider:github
80
- github: githubProvider({
81
- clientId: process.env.GITHUB_CLIENT_ID as string,
82
- clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
83
- redirectUri: `${apiUrl}/auth/oauth/github/callback`,
84
- }),
85
- // @oauth-provider:github:end
86
- },
87
-
88
- // Where to send the browser after each flow completes
89
- redirects: {
90
- afterLogin: '/',
91
- error: '/login',
92
- },
93
-
94
- signup: {
95
- // handler() is invoked the first time a user signs in with a
96
- // configured OAuth provider and no account is linked to that
97
- // provider identity yet. `profile` is the canonical profile the
98
- // provider returned (`providerUserId`, `email`, `username`, etc).
99
- //
100
- // At a minimum you need to create and return a user row. There's no
101
- // password to store here since this account only ever signs in
102
- // through the provider -- if your `User` model requires
103
- // `hashedPassword`/`salt`, make sure those fields are optional (or
104
- // have a default) so provider-only accounts can be created.
105
- handler: ({ profile }) => {
106
- // Some providers (e.g. GitHub, when the account keeps its email
107
- // private) don't return an email at all. Customize this handler
108
- // for any such provider you configure -- ask for an email on a
109
- // follow-up screen, or derive a placeholder from a field you know
110
- // is always present. Throwing here surfaces to the user as a
111
- // `provider_error` redirect instead of silently creating an
112
- // account with a fabricated address.
113
- if (!profile.email) {
114
- throw new Error(
115
- `OAuth signup handler needs an email, but ${profile.providerUserId} didn't return one. Customize this handler to handle providers that don't supply an email.`,
116
- )
117
- }
118
-
119
- return db.user.create({
120
- data: {
121
- email: profile.email,
122
- },
123
- })
124
- },
125
- },
126
-
127
- // How long a user will remain logged in, in seconds
128
- sessionExpires: 60 * 60 * 24 * 365 * 10,
129
-
130
- // Specifies attributes on the cookie that dbAuth sets in order to
131
- // remember who is logged in. See
132
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies
133
- cookie: {
134
- attributes: cookieAttributes,
135
- name: cookieName,
136
- },
137
- })
138
-
139
- return await oauthHandler.invoke()
140
- }
141
-
142
- const forgotPasswordOptions: DbAuthHandlerOptions['forgotPassword'] = {
143
- // handler() is invoked after verifying that a user was found with the given
144
- // username. This is where you can send the user an email with a link to
145
- // reset their password. With the default dbAuth routes and field names, the
146
- // URL to reset the password will be:
147
- //
148
- // https://example.com/reset-password?resetToken=${user.resetToken}
149
- //
150
- // Whatever is returned from this function will be returned from
151
- // the `forgotPassword()` function that is destructured from `useAuth()`
152
- // You could use this return value to, for example, show the email
153
- // address in a toast message so the user will know it worked and where
154
- // to look for the email.
155
- handler: (user) => {
156
- return user
157
- },
158
-
159
- // How long the resetToken is valid for, in seconds (default is 24 hours)
160
- expires: 60 * 60 * 24,
161
-
162
- errors: {
163
- // for security reasons you may want to be vague here rather than expose
164
- // the fact that the email address wasn't found (prevents fishing for
165
- // valid email addresses)
166
- usernameNotFound: 'Username not found',
167
- // if the user somehow gets around client validation
168
- usernameRequired: 'Username is required',
169
- },
170
- }
171
-
172
- const loginOptions: DbAuthHandlerOptions['login'] = {
173
- // handler() is called after finding the user that matches the
174
- // username/password provided at login, but before actually considering them
175
- // logged in. The `user` argument will be the user in the database that
176
- // matched the username/password.
177
- //
178
- // If you want to allow this user to log in simply return the user.
179
- //
180
- // If you want to prevent someone logging in for another reason (maybe they
181
- // didn't validate their email yet), throw an error and it will be returned
182
- // by the `logIn()` function from `useAuth()` in the form of:
183
- // `{ message: 'Error message' }`
184
- handler: (user) => {
185
- return user
186
- },
187
-
188
- errors: {
189
- usernameOrPasswordMissing: 'Both username and password are required',
190
- usernameNotFound: 'Username ${username} not found',
191
- // For security reasons you may want to make this the same as the
192
- // usernameNotFound error so that a malicious user can't use the error
193
- // to narrow down if it's the username or password that's incorrect
194
- incorrectPassword: 'Incorrect password for ${username}',
195
- },
196
-
197
- // How long a user will remain logged in, in seconds
198
- expires: 60 * 60 * 24 * 365 * 10,
199
- }
200
-
201
- const resetPasswordOptions: DbAuthHandlerOptions['resetPassword'] = {
202
- // handler() is invoked after the password has been successfully updated in
203
- // the database. Returning anything truthy will automatically logs the user
204
- // in. Return `false` otherwise, and in the Reset Password page redirect the
205
- // user to the login page.
206
- handler: (_user) => {
207
- return true
208
- },
209
-
210
- // If `false` then the new password MUST be different than the current one
211
- allowReusedPassword: true,
212
-
213
- errors: {
214
- // the resetToken is valid, but expired
215
- resetTokenExpired: 'resetToken is expired',
216
- // no user was found with the given resetToken
217
- resetTokenInvalid: 'resetToken is invalid',
218
- // the resetToken was not present in the URL
219
- resetTokenRequired: 'resetToken is required',
220
- // new password is the same as the old password (apparently they did not forget it)
221
- reusedPassword: 'Must choose a new password',
222
- },
223
- }
224
-
225
- const changePasswordOptions: DbAuthHandlerOptions['changePassword'] = {
226
- // handler() is invoked after a logged in user has entered their current
227
- // password correctly and the new password has been saved to the database.
228
- // This is a good place to let the user know, by email for example, that
229
- // their password was changed.
230
- //
231
- // Returning anything truthy keeps the user logged in. Return `false` to
232
- // log them out, and in the Change Password page redirect the user to the
233
- // login page.
234
- handler: (_user) => {
235
- // TODO: Send an email/message to the user letting them know that their
236
- // password was changed. When you implement this, change `_user` to
237
- // `user` in the function arguments above.
238
-
239
- return true
240
- },
241
-
242
- // If `false` then the new password MUST be different from the current one
243
- allowReusedPassword: false,
244
-
245
- errors: {
246
- // the current password was not provided
247
- currentPasswordRequired: 'Current password is required',
248
- // the new password was not provided
249
- newPasswordRequired: 'New password is required',
250
- // the current password is not correct
251
- incorrectCurrentPassword: 'Current password is incorrect',
252
- // the user doesn't have a password yet (they signed up with a third
253
- // party login provider, for example)
254
- passwordNotSet:
255
- 'This account does not have a password. Use "Forgot password" to set one',
256
- // new password is the same as the current password
257
- reusedPassword: 'Must choose a new password',
258
- },
259
- }
260
-
261
- interface UserAttributes {
262
- name: string
263
- }
264
-
265
- const signupOptions: DbAuthHandlerOptions<
266
- UserType,
267
- UserAttributes
268
- >['signup'] = {
269
- // Whatever you want to happen to your data on new user signup. Cedar will
270
- // check for duplicate usernames before calling this handler. At a minimum
271
- // you need to save the `username`, `hashedPassword` and `salt` to your
272
- // user table. `userAttributes` contains any additional object members that
273
- // were included in the object given to the `signUp()` function you got
274
- // from `useAuth()`.
275
- //
276
- // If you want the user to be immediately logged in, return the user that
277
- // was created.
278
- //
279
- // If this handler throws an error, it will be returned by the `signUp()`
280
- // function in the form of: `{ error: 'Error message' }`.
281
- //
282
- // If this returns anything else, it will be returned by the
283
- // `signUp()` function in the form of: `{ message: 'String here' }`.
284
- handler: ({
285
- username,
286
- hashedPassword,
287
- salt,
288
- userAttributes: _userAttributes,
289
- }) => {
290
- return db.user.create({
291
- data: {
292
- email: username,
293
- hashedPassword: hashedPassword,
294
- salt: salt,
295
- // name: userAttributes.name
296
- },
297
- })
298
- },
299
-
300
- // Include any format checks for password here. Return `true` if the
301
- // password is valid, otherwise throw a `PasswordValidationError`.
302
- // Import the error along with `DbAuthHandler` from `@cedarjs/api` above.
303
- passwordValidation: (_password) => {
304
- return true
305
- },
306
-
307
- errors: {
308
- // `field` will be either "username" or "password"
309
- fieldMissing: '${field} is required',
310
- usernameTaken: 'Username `${username}` already in use',
311
- },
312
- }
313
-
314
- const authHandler = new DbAuthHandler(event, context, {
315
- // Provide prisma db client
316
- db: db,
317
-
318
- // The name of the property you'd call on `db` to access your user table.
319
- // ie. if your Prisma model is named `User` this value would be `user`, as in `db.user`
320
- authModelAccessor: 'user',
321
-
322
- // The name of the property you'd call on `db` to access your user credentials table.
323
- // ie. if your Prisma model is named `UserCredential` this value would be `userCredential`, as in `db.userCredential`
324
- credentialModelAccessor: 'userCredential',
325
-
326
- // A map of what dbAuth calls a field to what your database calls it.
327
- // `id` is whatever column you use to uniquely identify a user (probably
328
- // something like `id` or `userId` or even `email`)
329
- authFields: {
330
- id: 'id',
331
- username: 'email',
332
- hashedPassword: 'hashedPassword',
333
- salt: 'salt',
334
- resetToken: 'resetToken',
335
- resetTokenExpiresAt: 'resetTokenExpiresAt',
336
- challenge: 'webAuthnChallenge',
337
- },
338
-
339
- // Specifies attributes on the cookie that dbAuth sets in order to remember
340
- // who is logged in. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies
341
- cookie: {
342
- attributes: cookieAttributes,
343
- name: cookieName,
344
- },
345
-
346
- changePassword: changePasswordOptions,
347
- forgotPassword: forgotPasswordOptions,
348
- login: loginOptions,
349
- resetPassword: resetPasswordOptions,
350
- signup: signupOptions,
351
-
352
- // See https://cedarjs.com/docs/auth/dbauth#webauthn for options
353
- webAuthn: {
354
- enabled: true,
355
- // How long to allow re-auth via WebAuthn in seconds (default is 10 years).
356
- // The `login.expires` time denotes how many seconds before a user will be
357
- // logged out, and this value is how long they'll be to continue to use a
358
- // fingerprint/face scan to log in again. When this one expires they
359
- // *must* re-enter username and password to authenticate (WebAuthn will
360
- // then be re-enabled for this amount of time).
361
- expires: 60 * 60 * 24 * 365 * 10,
362
- name: 'Cedar Application',
363
- domain:
364
- process.env.NODE_ENV === 'development' ? 'localhost' : 'server.com',
365
- origin:
366
- process.env.NODE_ENV === 'development'
367
- ? 'http://localhost:8910'
368
- : 'https://server.com',
369
- type: 'platform',
370
- timeout: 60000,
371
- credentialFields: {
372
- id: 'id',
373
- userId: 'userId',
374
- publicKey: 'publicKey',
375
- transports: 'transports',
376
- counter: 'counter',
377
- },
378
- },
379
- })
380
-
381
- return await authHandler.invoke()
382
- }