How change a user without change the password?

I’m trying to change a user without change the password.

My user model is hidding the password field:

static get hidden () {

    return ['password']

  }

My frontend is sending the password field with: '' when don’t need to change the password.

In adonis i try:

const user = await User.find(request.params.id)

    const requestValues = request.except('company_name')

    user.merge(requestValues)

    await user.save()

    return user

But i’m receiving:

  1. message: “update “users” set “login” = $1, “password” = $2, “created_at” = $3, “updated_at” = $4 where “id” = $5 - null value in column “password” violates not-null constraint”

which value i need to send to my frontend to adonis don’t change the password when not filled?

1 Like

You can override hidden behaviour for a single query:

User.query().setHidden(['password']).fetch()

// or set visible
User.query().setVisible(['title', 'body']).fetch()

See the docs: https://adonisjs.com/docs/4.1/lucid#_setvisiblesethidden

3 Likes

Luo silmukka tai kirjoita vanha salasana muistiin. Odotan kanssasi sopivinta vastausta

Or better that setting the query, in the User model hook.

class User extends Model {
  static boot () {
    super.boot()

    this.addHook('beforeSave', 'UserHook.hashPassword')
  }
}

inside UserHook

UserHook.hashPassword = async (userInstance) => {
  if (userInstance.dirty.password) {
    userInstance.password = await Hash.make(userInstance.password)
  }
}

this way, only if the password param is present then the user will be be updated with the new password.

2 Likes