Hashing Module
Formulaic includes a simple Nest module that wraps bcrypt.
Usage
This example will use the UserService
example started in the docs for @formulaic/entity-service
.
Add the HashModule
to the Nest Module:
src/user/user.module.ts
import { HashModule } from "@formulaic/hash";
import { Module } from "@nestjs/common";
import { TypeORMModule } from "@nestjs/typeorm";
import { User } from "./user.entity";
import { UserService } from "./user.service";
@Module({
imports: [
TypeORMModule.forFeature([ User ]),
HashModule,
],
providers: [
UserService,
],
})
export class UserModule {}
Now you can use the HashService
methods hash
and compare
:
import { HashService } from "@formulaic/hash";
// ... existing imports
@Injectable()
export class UserService extends EntityService<User> {
public constructor(
private readonly hash: HashService, (1)
@InjectRepository(User)
private readonly users: Repository<User>,
) {
super("User", users);
}
public async createUser(
username: string,
password: string,
name?: string,
isAdmin: boolean = false,
) {
const user = new User();
user.username = username;
user.password = await this.hash.hash(password); (2)
user.name = name;
user.isAdmin = isAdmin;
return this.save(user);
}
public async checkPassword(user: User, password: string): Promise<boolean> {
return this.hash.compare(password, user.password); (3)
}
}
1 | Inject in the constructor |
2 | Provide plaintext, and optionally the hashing rounds. |
3 | Plaintext, then saved hash. |