Skip to content

Instantly share code, notes, and snippets.

@flybayer
Last active September 23, 2020 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flybayer/ae233adad2a9b9da258f809bccddabd0 to your computer and use it in GitHub Desktop.
Save flybayer/ae233adad2a9b9da258f809bccddabd0 to your computer and use it in GitHub Desktop.
import { SessionContext } from "blitz"
import db from "db"
import { authenticateUser, hashPassword } from "app/auth/auth-utils"
import * as z from "zod"
// --------------------------------------------
// PROTECT UTIL
type Ctx = { session: SessionContext }
type ProtectArgs<T> = { schema: T; authorize?: boolean }
const protect = <T extends z.ZodSchema<any, any>, U = z.infer<T>>(
{ schema, authorize = true }: ProtectArgs<T>,
resolver: (args: U, ctx: Ctx) => any
) => {
return (input: U, ctx?: Ctx) => {
if (!ctx) throw new Error("missing ctx")
if (authorize) {
ctx.session.authorize()
}
const safeInput = schema.parse(input)
return resolver(safeInput, ctx)
}
}
// --------------------------------------------
// USAGE
const schema = z.object({
currentPassword: z.string(),
newPassword: z.string(),
})
export default protect({ schema,},
async function updatePassword({ currentPassword, newPassword }, {session}) {
const user = await db.user.findOne({ where: { id: session.userId } })
await authenticateUser(user!.email, currentPassword)
const hashedPassword = await hashPassword(newPassword)
await db.user.update({
where: { id: session.userId },
data: { hashedPassword },
})
return true
}
)
// -------------------------
// OR, you can also inline the schema
export default protect(
{
schema: z.object({
currentPassword: z.string(),
newPassword: z.string(),
}),
},
async function updatePassword({ currentPassword, newPassword }, ctx) {
const user = await db.user.findOne({ where: { id: ctx.session?.userId } })
await authenticateUser(user!.email, currentPassword)
const hashedPassword = await hashPassword(newPassword)
await db.user.update({
where: { id: ctx.session.userId },
data: { hashedPassword },
})
return true
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment