Last active
September 23, 2020 14:25
-
-
Save flybayer/ae233adad2a9b9da258f809bccddabd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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