Skip to content

Password Authentication

We provide a mechanism for securely hashing and authenticating passwords using Bcrypt.

First, add a passwordDigest field to the model to store the hashed password.

db/schema/main.prisma
model User {
// ...
passwordDigest String // Stores the hash value of the password
}

Next, use hasSecurePassword() to add functionality to the model for hashing and authenticating passwords.

src/models/user.ts
import { hasSecurePassword, Mix } from "accel-record";
import { ApplicationRecord } from "./applicationRecord.js";
export class UserModel extends Mix(ApplicationRecord, hasSecurePassword()) {}

With this, you can perform password validation and hashing using the password and passwordConfirmation fields, and authenticate passwords using the authenticate() method.

import { User } from "./models/index.js";
const user = User.build({});
user.password = "";
user.save(); // => false (password can't be blank)
user.password = "myPassword";
user.save(); // => false (password confirmation doesn't match)
user.passwordConfirmation = "myPassword";
user.save(); // => true
user.authenticate("invalid"); // => false
user.authenticate("myPassword"); // => true

You can customize the field name for storing the password by setting it to something other than passwordDigest, and you can manage multiple passwords in the model as well.

src/models/user.ts
import { hasSecurePassword, Mix } from "accel-record";
import { ApplicationRecord } from "./applicationRecord.js";
export class UserModel extends Mix(
ApplicationRecord,
hasSecurePassword(), // Uses the passwordDigest field
hasSecurePassword({ attribute: "recovery", validation: false }) // Uses the recoveryDigest field
) {}