You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
1.2 KiB
33 lines
1.2 KiB
2 years ago
|
import { SecurePassword } from "@blitzjs/auth"
|
||
|
import { resolver } from "@blitzjs/rpc"
|
||
|
import { AuthenticationError } from "blitz"
|
||
|
import db from "db"
|
||
|
import { Role } from "types"
|
||
|
import { Login } from "../validations"
|
||
|
|
||
|
export const authenticateUser = async (rawEmail: string, rawPassword: string) => {
|
||
|
const { email, password } = Login.parse({ email: rawEmail, password: rawPassword })
|
||
|
const user = await db.user.findFirst({ where: { email } })
|
||
|
if (!user) throw new AuthenticationError()
|
||
|
|
||
|
const result = await SecurePassword.verify(user.hashedPassword, password)
|
||
|
|
||
|
if (result === SecurePassword.VALID_NEEDS_REHASH) {
|
||
|
// Upgrade hashed password with a more secure hash
|
||
|
const improvedHash = await SecurePassword.hash(password)
|
||
|
await db.user.update({ where: { id: user.id }, data: { hashedPassword: improvedHash } })
|
||
|
}
|
||
|
|
||
|
const { hashedPassword, ...rest } = user
|
||
|
return rest
|
||
|
}
|
||
|
|
||
|
export default resolver.pipe(resolver.zod(Login), async ({ email, password }, ctx) => {
|
||
|
// This throws an error if credentials are invalid
|
||
|
const user = await authenticateUser(email, password)
|
||
|
|
||
|
await ctx.session.$create({ userId: user.id, role: user.role as Role })
|
||
|
|
||
|
return user
|
||
|
})
|