Leno Leno - 4 months ago 118
PHP Question

Laravel 5 Auth::attempt() always returning false

I started a new project on Laravel 5 recently and I'm trying to implement a login function.

For username I'm using a code number which can be a CPF or a CNPJ (Brazilian tax registration numbers for individuals (CPF) and companies (CNPJ) formatted as 999.999.999-99 and 99.999.999/9999-99 respectively), which is saved on database with all dots, dashes and slash, and the input is masked so they also come formatted from the input (I double-checked the string input passed on $username variable, it's correct).

The problem is the Auth::attempt() method always returns false. I tried all answers I found on stackoverflow about that problem, none of them solved it, so I'm opening another question.

I'm using Laravel 5.0.16 on Homestead enviroment and MySQL local databased provided by Homestead.

This is my form:



<form id="login-form" class="contact-form" name="contact-form" method="post"
action="/auth/login">
<div>
<div class="form-group">
<div class="form-group">
<label>CPF/CNPJ</label>
<input type="text" name="username" class="form-control cpfcnpj">
</div>
<div class="form-group">
<label>Senha</label>
<input type="password" name="password" class="form-control">
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group" style="margin-top: 30px">
<button type="submit" name="submit" class="btn btn-primary btn-lg">
Entrar
</button>
</div>
</div>
</div>
</form>





This is my User.php:

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

use Authenticatable, CanResetPassword;

/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'PESSOA';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['sqpessoa', 'cpfcnpj', 'password', 'nome', 'email', 'telefone', 'contato', 'tipo'];

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];

/**
*
* @var type
*/
protected $primaryKey = 'sqpessoa';

/**
*
* @var type
*/
public $timestamps = false;

/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier() {
return $this->attributes['sqpessoa'];
}

public function getAuthPassword()
{
return $this->cpfcnpj;
}


}

My AuthController:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/

use AuthenticatesAndRegistersUsers;

/**
* Create a new authentication controller instance.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @param \Illuminate\Contracts\Auth\Registrar $registrar
* @return void
*/
public function __construct(Guard $auth, Registrar $registrar) {
$this->auth = $auth;
$this->registrar = $registrar;

$this->middleware('guest', ['except' => 'getLogout']);
}

/**
*
* @param \Illuminate\Http\Request $request
* @return type
*/
public function postLogin(\Illuminate\Http\Request $request) {
$this->validate($request, array('username' => 'required', 'password' => 'required'));

$username = $request->input('username');
$password = $request->input('password');

if (\Auth::attempt(['cpfcnpj' => $username, 'password' => $password])) {
return redirect()->intended($this->redirectPath());
}

return redirect($this->loginPath())->withInput($request->only('username', 'remember'))->withErrors(array('username' => 'Credenciais inválidas.'));
}
}


My migration for users (named as 'pessoa') database:

class CreatePessoaTable extends Migration {

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('PESSOA', function (Blueprint $table) {
$table->increments('SQPESSOA');
$table->string('CPFCNPJ', 20)->unique();
$table->string('PASSWORD', 255);
$table->string('NOME', 200);
$table->string('EMAIL', 200);
$table->string('TELEFONE', 15);
$table->string('CONTATO', 200)->nullable();
$table->enum('TIPO', ['avulso', 'mensalista', 'patio']);
$table->rememberToken();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('PESSOA');
}

}


And seed:

class PessoaTableSeeder extends Seeder
{
public function run()
{
DB::table('PESSOA')->truncate();

$faker = Faker\Factory::create('pt_BR');

DB::table('PESSOA')->insert([
'cpfcnpj' => $faker->cnpj,
'password' => bcrypt('test'),
'nome' => 'Admin',
'email' => 'email@gmail.com',
'telefone' => $faker->phoneNumber,
'contato' => str_random(),
'tipo' => 'patio'
]);

for ($i = 0; $i < 10; $i++) {
DB::table('PESSOA')->insert([
'cpfcnpj' => $faker->unique()->cpf,
'password' => bcrypt($faker->password),
'nome' => $faker->name,
'email' => $faker->email,
'telefone' => $faker->phoneNumber,
'contato' => str_random(),
'tipo' => 'avulso'
]);
}

for ($i = 0; $i < 3; $i++) {
DB::table('PESSOA')->insert([
'cpfcnpj' => $faker->unique()->cnpj,
'password' => bcrypt($faker->password),
'nome' => $faker->company,
'email' => $faker->companyEmail,
'telefone' => $faker->phoneNumber,
'contato' => str_random(),
'tipo' => 'mensalista'
]);
}
}
}


Thanks in advance.

Answer

Your Auth::attempt is looking for cpfcnpj as username but you have specified sqpessoa as the username field at getAuthIdentifier() method.

Also you have specified the cpfcnpj as the password field at getAuthPassword() method while Auth::attempt has cpfcnpj as username instead of password.