Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions playground/server/api/login.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export default defineEventHandler(async (event) => {
throw invalidCredentialsError
}

if (passwordNeedsReHash(password)) {
await db.sql`UPDATE users SET password = ${hashPassword(password)} WHERE id = ${user.id}`
}

await setUserSession(event, {
user: {
email,
Expand Down
20 changes: 20 additions & 0 deletions src/runtime/server/utils/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,23 @@ export async function hashPassword(password: string) {
export async function verifyPassword(hashedPassword: string, plainPassword: string) {
return await getHash().verify(hashedPassword, plainPassword)
}

/**
* Check if the hash value needs a rehash or not. The rehash is required if
* configuration settings have changed.
* @param hashedPassword - The hashed password to check
* @returns `true` if a rehash is needed, `false` otherwise
* @example
* ```ts
* const isValid = await verifyPassword(hashedPassword, plainText)
*
* // Plain password is valid, and hash needs a rehash
* if (isValid && passwordNeedsReHash(hashedPassword)) {
* const newHash = await hashPassword(plainText)
* }
* ```
* @more you can configure the scrypt options in `auth.hash.scrypt`
*/
export function passwordNeedsReHash(hashedPassword: string) {
return getHash().needsReHash(hashedPassword)
}