node.jstypescriptadonis.jsadonisjs-acelucid

How to use Hash.make(user.password) in adonisjs


Trying to encrypt a user password using Hash.make(user.password) from import Hash from '@ioc:Adonis/Core/Hash'

The problem happens when the code tries to execute the Hash.make present inside @beforesave it gives me a referenceError.

message:'Hash is not defined'
stack:'ReferenceError: Hash is not defined\n    at eval (eval at hashPassword (/usr/src/app/Models/User.ts:35:9), <anonymous>:2:28)

Here is the user Model.


import { DateTime } from 'luxon'
import Hash from '@ioc:Adonis/Core/Hash'
import { column, beforeSave, BaseModel } from '@ioc:Adonis/Lucid/Orm'
import Logger from '@ioc:Adonis/Core/Logger'

export default class User extends BaseModel {
  @column({ isPrimary: true })
  public id: number

  @column()
  public email: string

  @column({ columnName: 'first_name' })
  public firstName: string

  @column({ columnName: 'last_name' })
  public lastName: string

  @column({ serializeAs: null })
  public password: string

  @column()
  public rememberMeToken?: string

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  @beforeSave()
  public static async hashPassword(user: User) {
    if (user.$dirty.password) {
      try {
        user.password = await Hash.make(user.password)
      }
      catch (error) {
        Logger.error(error)
      }
    }
  }
}


When debugging steps goes into the right path belonging to the Hash dependency, but it fails inside the hash driver I think


Solution

  • Since I noticed it only happening inside docker, the problem seems to be with the default driver inside docker.

    I solved this by using this:

    await Hash.use('bcrypt').make(user.password)
    

    Or you can change the default hash drive using:

    default: Env.get('HASH_DRIVER', 'bcrypt')