简体   繁体   中英

How to create a custom password field for Laravel Auth

I need to login users registered in the table Igrejas that have the fields responsavel_cpf and responsavel_senha , but Laravel in the function validateCredentials expects the name 'password' .

public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];
}

I tried to login using attempt without success:

$userdata = array(
    'responsavel_cpf'      => Input::get('email'),
    'responsavel_senha'    => Input::get('password')
);

if (Auth::guard('igrejas')->attempt($userdata)) {
    return Redirect::to('dashboard_paroquia');
} else {
    return Redirect::to('login');
}

What do I do to replace the default fields email and password with responsavel_cpf and responsavel_senha ?

You can override the password column in your user model like so:

// User.php
public function getAuthPassword()
{
    return $this->custom_pw_field;
}

However, if you actually want to pass an array that does not explicitly contain password to Auth::guard('xxx')->attempt($credentials) (for which there is no reason!), you'll probably have to override and add the Illuminate\\Auth\\EloquentUserProvider manually which seems a lot of work.

So I would suggest to just use the following:

Auth::guard('xxx')->attempt([
    'email' => $request->post('email'),
    'password' => $request->post('password')
]);

The password key should then validate against the custom_pw_field that you defined.

Explanation

By looking at the source of Illuminate\\Auth\\EloquentUserProvider and checking the function public function retrieveByCredentials(array $credentials) , you can see what it does:

  • Find the first record in the auth table that matches all the conditions in the $credentials array except for password (so just email in the example above). So you could add for instance another key like is_webmaster like $authGuard->attempt(['email' => $request->post('email'), 'is_webmaster' => 1]) which would then retrieve the first user record that has these properties.
  • After this record is retrieved, the hash from its password column is then checked against your input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM