Ali Erfani
Ali Erfani

Reputation: 692

Laravel 5.1 change password functionality

I need a change password functionality for my laravel app. I have created this view:

{!! Form::password('old_password', ['class'=>'form-control']) !!}
{!! Form::password('password', ['class'=>'form-control']) !!}
{!! Form::password('password_confirmation', ['class'=>'form-control']) !!}

Then in my controller I'm checking to see if the value entered for the old_passwordis the same as user's current password.

if(bcrypt($request->old_password) !=$user->password) return redirect()->back()

The problem is that the above condition will always be true. This mins even if the user enters a valid password this condition will return true! Why it is so? By the way I'm hashing the password in my user model:

 public function setPasswordAttribute($password){
        $this->attributes['password'] = bcrypt($password);
    }  

Upvotes: 2

Views: 6069

Answers (2)

Ali Erfani
Ali Erfani

Reputation: 692

bcrypt() generates a random salt each time. In order to check passwords, I should use Hash::check().

Link to docs

Example in docs:

if (Hash::check('plain-text-password', $hashedPassword)) {
    // The passwords match...
}

Upvotes: 6

amith.gotamey
amith.gotamey

Reputation: 988

There is a helpful Authentication function called Auth::validate($credentials) where you pass the [username, password] or [email, password] combination. This will check whether the provided $credentials is valid or not without logging the user in.

So in your AuthController you would check:

...
$credentials = [
    'email' => $request->get('email'),
    'password' => $request->get('old_password'),
];

if(\Auth::validate($credentials)) {
    // TODO: Old password is correct, do your thing
    // Change password and login, OR
    // Send them to the login page
}

return redirect()->back()->withError('Incorrect old password');

Hope this helps.

Cheers!

Upvotes: 4

Related Questions