php - Laravel 5 Auth::attempt() 总是返回 false

标签 php mysql laravel laravel-5 homestead

我最近在 Laravel 5 上开始了一个新项目,我正在尝试实现一个登录功能。

对于用户名,我使用的代码可以是 CPF 或 CNPJ(个人 (CPF) 和公司 (CNPJ) 的巴西税务登记号,格式为 999.999.999-99 和 99.999.999/9999-99分别),它保存在数据库中所有的点,破折号和斜线,并且输入被屏蔽所以它们也来自输入的格式(我仔细检查了传递给 $username 变量的字符串输入,它是正确的)。

问题是 Auth::attempt() 方法总是返回 false。我尝试了我在 stackoverflow 上找到的关于该问题的所有答案,但都没有解决它,所以我要打开另一个问题。

我在 Homestead 环境和 Homestead 提供的 MySQL 本地数据库上使用 Laravel 5.0.16。

这是我的表格:

<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>                                                                            

这是我的 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;
}

我的授权 Controller :

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.'));
    }
}

我的用户迁移(命名为“pessoa”)数据库:

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');
    }

}

和种子:

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'
            ]);
        }
    }
}

提前致谢。

最佳答案

您的 Auth::attempt 正在寻找 cpfcnpj 作为用户名,但您在 getAuthIdentifier( ) 方法。

您还指定了 cpfcnpj 作为 getAuthPassword() 方法的密码字段,而 Auth::attemptcpfcnpj 作为用户名而不是密码。

关于php - Laravel 5 Auth::attempt() 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38274793/

相关文章:

php - 如何使用php中的 anchor 将包含整个数据库的一个页面中的选定值显示到另一页面

mysql - 获取mysql表中不存在的值

javascript - 如何在 node.js 中设置 mysql 连接以在使用无符号整数进行算术运算时抛出超出范围错误?

php - 在 MySQL 查询中使用 OR 和 AND

php - laravel - json_encodeing trans函数的返回值在使用单引号时发送错误

php - 根据对二维数组进行排序

mysql - 为第 10 部门工资最低的员工增加 1% 的工资

php - 如何在laravel Blade中显示存储图像?

javascript - 在 Laravel Blade 模板中使用 JS/JQuery 时搜索栏过滤器的问题

php - 为什么 Container::getInstance() 可以返回一个应用类