Skip to content

Commit

Permalink
fix(context): Refactor context (#9371)
Browse files Browse the repository at this point in the history
Co-authored-by: Tobbe Lundberg <[email protected]>
  • Loading branch information
Josh-Walker-GM and Tobbe authored Dec 25, 2023
1 parent 909ab4e commit 6a6687b
Show file tree
Hide file tree
Showing 51 changed files with 1,001 additions and 171 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ test('Set a mock user on the context', async () => {
})

test('Context is isolated between tests', () => {
expect(context).toStrictEqual({ currentUser: undefined })
expect(context).toStrictEqual({})
})
1 change: 1 addition & 0 deletions packages/api-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@fastify/http-proxy": "9.3.0",
"@fastify/static": "6.12.0",
"@fastify/url-data": "5.4.0",
"@redwoodjs/context": "6.0.7",
"@redwoodjs/project-config": "6.0.7",
"ansi-colors": "4.1.3",
"chalk": "4.1.2",
Expand Down
1 change: 1 addition & 0 deletions packages/api-server/src/__tests__/fastify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ jest.mock('fastify', () => {
return jest.fn(() => {
return {
register: () => {},
addHook: () => {},
}
})
})
Expand Down
7 changes: 7 additions & 0 deletions packages/api-server/src/fastify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import path from 'path'
import type { FastifyInstance, FastifyServerOptions } from 'fastify'
import Fastify from 'fastify'

import type { GlobalContext } from '@redwoodjs/context'
import { getAsyncStoreInstance } from '@redwoodjs/context/dist/store'
import { getPaths, getConfig } from '@redwoodjs/project-config'

import type { FastifySideConfigFn } from './types'
Expand Down Expand Up @@ -60,6 +62,11 @@ export const createFastifyInstance = (

const fastify = Fastify(options || config || DEFAULT_OPTIONS)

// Ensure that each request has a unique global context
fastify.addHook('onRequest', (_req, _reply, done) => {
getAsyncStoreInstance().run(new Map<string, GlobalContext>(), done)
})

return fastify
}

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-config/src/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ describe('api', () => {
},
{
members: ['context'],
path: '@redwoodjs/graphql-server',
path: '@redwoodjs/context',
},
],
},
Expand Down
4 changes: 1 addition & 3 deletions packages/babel-config/src/__tests__/prebuildApiFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,9 +443,7 @@ describe('api prebuild ', () => {
})

it('auto imports', () => {
expect(code).toContain(
'import { context } from "@redwoodjs/graphql-server"'
)
expect(code).toContain('import { context } from "@redwoodjs/context"')
expect(code).toContain('import gql from "graphql-tag"')
})
})
Expand Down
19 changes: 17 additions & 2 deletions packages/babel-config/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ export const getApiSideBabelPlugins = (
path: 'graphql-tag',
},
{
// import { context } from '@redwoodjs/graphql-server'
// import { context } from '@redwoodjs/context'
members: ['context'],
path: '@redwoodjs/graphql-server',
path: '@redwoodjs/context',
},
],
},
Expand Down Expand Up @@ -144,10 +144,25 @@ export const getApiSideBabelConfigPath = () => {
}
}

export const getApiSideBabelOverrides = () => {
const overrides = [
// Apply context wrapping to all functions
{
// match */api/src/functions/*.js|ts
test: /.+api(?:[\\|/])src(?:[\\|/])functions(?:[\\|/]).+.(?:js|ts)$/,
plugins: [
require('./plugins/babel-plugin-redwood-context-wrapping').default,
],
},
].filter(Boolean)
return overrides as TransformOptions[]
}

export const getApiSideDefaultBabelConfig = () => {
return {
presets: getApiSideBabelPresets(),
plugins: getApiSideBabelPlugins(),
overrides: getApiSideBabelOverrides(),
extends: getApiSideBabelConfigPath(),
babelrc: false,
ignore: ['node_modules'],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { DbAuthHandler, DbAuthHandlerOptions } from '@redwoodjs/auth-dbauth-api'

import { db } from 'src/lib/db'

export const handler = async (
event,
context
) => {
const forgotPasswordOptions = {
// handler() is invoked after verifying that a user was found with the given
// username. This is where you can send the user an email with a link to
// reset their password. With the default dbAuth routes and field names, the
// URL to reset the password will be:
//
// https://example.com/reset-password?resetToken=${user.resetToken}
//
// Whatever is returned from this function will be returned from
// the `forgotPassword()` function that is destructured from `useAuth()`
// You could use this return value to, for example, show the email
// address in a toast message so the user will know it worked and where
// to look for the email.
handler: (user) => {
return user
},

// How long the resetToken is valid for, in seconds (default is 24 hours)
expires: 60 * 60 * 24,

errors: {
// for security reasons you may want to be vague here rather than expose
// the fact that the email address wasn't found (prevents fishing for
// valid email addresses)
usernameNotFound: 'Username not found',
// if the user somehow gets around client validation
usernameRequired: 'Username is required',
},
}

const loginOptions = {
// handler() is called after finding the user that matches the
// username/password provided at login, but before actually considering them
// logged in. The `user` argument will be the user in the database that
// matched the username/password.
//
// If you want to allow this user to log in simply return the user.
//
// If you want to prevent someone logging in for another reason (maybe they
// didn't validate their email yet), throw an error and it will be returned
// by the `logIn()` function from `useAuth()` in the form of:
// `{ message: 'Error message' }`
handler: (user) => {
return user
},

errors: {
usernameOrPasswordMissing: 'Both username and password are required',
usernameNotFound: 'Username ${username} not found',
// For security reasons you may want to make this the same as the
// usernameNotFound error so that a malicious user can't use the error
// to narrow down if it's the username or password that's incorrect
incorrectPassword: 'Incorrect password for ${username}',
},

// How long a user will remain logged in, in seconds
expires: 60 * 60 * 24 * 365 * 10,
}

const resetPasswordOptions = {
// handler() is invoked after the password has been successfully updated in
// the database. Returning anything truthy will automatically log the user
// in. Return `false` otherwise, and in the Reset Password page redirect the
// user to the login page.
handler: (_user) => {
return true
},

// If `false` then the new password MUST be different from the current one
allowReusedPassword: true,

errors: {
// the resetToken is valid, but expired
resetTokenExpired: 'resetToken is expired',
// no user was found with the given resetToken
resetTokenInvalid: 'resetToken is invalid',
// the resetToken was not present in the URL
resetTokenRequired: 'resetToken is required',
// new password is the same as the old password (apparently they did not forget it)
reusedPassword: 'Must choose a new password',
},
}

const signupOptions = {
// Whatever you want to happen to your data on new user signup. Redwood will
// check for duplicate usernames before calling this handler. At a minimum
// you need to save the `username`, `hashedPassword` and `salt` to your
// user table. `userAttributes` contains any additional object members that
// were included in the object given to the `signUp()` function you got
// from `useAuth()`.
//
// If you want the user to be immediately logged in, return the user that
// was created.
//
// If this handler throws an error, it will be returned by the `signUp()`
// function in the form of: `{ error: 'Error message' }`.
//
// If this returns anything else, it will be returned by the
// `signUp()` function in the form of: `{ message: 'String here' }`.
handler: ({ username, hashedPassword, salt, userAttributes }) => {
return db.user.create({
data: {
email: username,
hashedPassword: hashedPassword,
salt: salt,
fullName: userAttributes['full-name'],
},
})
},

// Include any format checks for password here. Return `true` if the
// password is valid, otherwise throw a `PasswordValidationError`.
// Import the error along with `DbAuthHandler` from `@redwoodjs/api` above.
passwordValidation: (_password) => {
return true
},

errors: {
// `field` will be either "username" or "password"
fieldMissing: '${field} is required',
usernameTaken: 'Username `${username}` already in use',
},
}

const authHandler = new DbAuthHandler(event, context, {
// Provide prisma db client
db: db,

// The name of the property you'd call on `db` to access your user table.
// i.e. if your Prisma model is named `User` this value would be `user`, as in `db.user`
authModelAccessor: 'user',

// A map of what dbAuth calls a field to what your database calls it.
// `id` is whatever column you use to uniquely identify a user (probably
// something like `id` or `userId` or even `email`)
authFields: {
id: 'id',
username: 'email',
hashedPassword: 'hashedPassword',
salt: 'salt',
resetToken: 'resetToken',
resetTokenExpiresAt: 'resetTokenExpiresAt',
},

// Specifies attributes on the cookie that dbAuth sets in order to remember
// who is logged in. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies
cookie: {
HttpOnly: true,
Path: '/',
SameSite: 'Strict',
Secure: process.env.NODE_ENV !== 'development',

// If you need to allow other domains (besides the api side) access to
// the dbAuth session cookie:
// Domain: 'example.com',
},

forgotPassword: forgotPasswordOptions,
login: loginOptions,
resetPassword: resetPasswordOptions,
signup: signupOptions,
})

return await authHandler.invoke()
}
Loading

0 comments on commit 6a6687b

Please sign in to comment.