Can't check password with Auth


#1

Hi.
I’m having a not validated password message when trying to login with auth.

When a user is registered I hash the password:

    const safePassword = await Hash.make(newUser.password);

    const createdUser = await User.create(
      {
        username:newUser.username,
        email:newUser.email,
        password:safePassword
      }
    )

I’ve tried checking the password this two ways in the login:
const { email, password } = request.all()

await auth.attempt(email, password)

 const safePassword = await Hash.make(password)
    
 await auth.attempt(email, safePassword)

in both ways I got the error.

what Im missiong?


#2

Hey @jorgeyoma! :wave:

The password should be already hashed by the beforeSave hook in your User model.
This hook is added by default and can be found in the boot() method of your model.

If that’s the case, you aren’t storing a hash of the password but a hash of a hash of the password. Which is wrong.

Also, auth.attempt() will manage the hashing for you.

const { email, password } = request.all()
await auth.attemp(email, password)

#3

Good afternoon, I have the following problem:
When I create the user, the password hash is generated successfully. However when I update the user the password hash is not generated.

I have tried this:

async store ({ request, response }) {
		const data = request.body;
		try {
			if(data.id == undefined) {
				return await User.create(data);
			} else{
				const user = await User.findOrFail(data.id);
				user.merge(data);
				user.save()

				return user;
			}
		} catch(err) {
			return response.status(400)
				.send({ error: 'Error ao tentar criar/atualizar Usuário!', details: err });
		}
	}

And also like this:

async store ({ request, response }) {
		const data = request.body;
		try {
			if(data.id == undefined) {
				return await User.create(data);
			} else{
				if(await User.query().where('id', data.id).update(data));
					return await User.findOrFail(data.id);
			}
		} catch(err) {
			return response.status(400)
				.send({ error: 'Error ao tentar criar/atualizar Usuário!', details: err });
		}
	}

Can you help me?


#4

Hi @romain.lanz, you where right, I was double-hashing the password, thanks!


#5

Hi @tijooloo.

First I would recommend to use different functions for the create and update. Adonis can redirect easily using Route.resources.

Then you can try with this code:

const user = await User.findOrFail(data.id);
				user.merge({
password:data.password,
name:data.name,
...
});
				user.save()

The hash will look for the “password” field to hash it. If you use another name for the password field it wonpt use it.

It’s also a good practice that the database name fields aren’t the same of your form name fields.