Skip to content
Merged
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ if (await verifyPassword(hashedPassword, 'user_password')) {
}
```

It also provides a `passwordNeedsRehash` function to check if a password needs to be rehashed. This is useful when the hash settings are changed, such as as increasing the scrypt cost parameters.

```ts
const needsRehash = await passwordNeedsRehash(hashedPassword)

if (needsRehash) {
// Password needs to be rehashed
hashedPassword = await hashPassword('user_password')
}
```

You can configure the scrypt options in your `nuxt.config.ts`:

```ts
Expand Down
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)
}