Auth :: user()在Laravel 5.8中返回null

时间:2019-05-02 04:40:25

标签: php laravel-5.8

我的Laravel 5.8.10项目中的身份验证有问题。我没有使用Laravel创建的默认表单进行身份验证。当我在浏览器中访问URL /仪表板时,通常用户将在登录时获得重定向重定向。该应用程序仍然允许它。同样,当我使用Auth::user()时,它返回null。

当我输入无效的用户名和密码时,不会从登录屏幕传递过来。当我输入无效的凭据时,它将重定向到仪表板。通过仪表板视图访问URL的问题也继续存在。好像您不需要身份验证即可访问路由。

注意:我的.env文件中有一个变量PASSWORD_HASH,用于启用或禁用密码加密。

用户模型

namespace App\Entities;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    protected $table = "users";
    public $timestamps = true;

    protected $fillable = [
        'cpf', 'name', 'phone', 'birth', 'gender', 'notes', 'email', 'password', 'status', 'permission'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function groups()
    {
        return $this->belongsToMany(Group::Class, 'user_groups');
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = env('PASSWORD_HASH') ? bcrypt($value) : $value;
    }
}

config / auth.php

return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Entities\User::class,
        ],
    ],
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

DashboardController

public function auth(Request $request)
{
    $data = [
        'email' => $request->get('username'),
        'password' => $request->get('password')
    ];
    try {
        if (env('PASSWORD_HASH')) {
            Auth::attempt($data, false);
        } else {
            $user = $this->repository->findWhere(['email' => $request->get('username')])->first();

            if (!$user)
                throw new Exception("O e-mail informado é inválido. PEEEEN!");
            if ($user->password != $request->get('password'))
                throw new Exception("A senha informada é inválida. PEEEEN!");
            Auth::login($user);
        }
        return redirect()->route('user.dashboard');
    } catch (Exception $e) {
        return $e->getMessage();
    }
}

路线

Route::get('/login', ['uses' => 'Controller@fazerlogin']);
Route::post('/login', ['as' => 'user.login', 'uses' => 'DashboardController@auth']);
Route::get('/dashboard', ['as' => 'user.dashboard', 'uses' => 'DashboardController@index']);

查看登录名

<section id="conteudo-view" class="login">
    <h1>Investindo</h1>
    <h3>O nosso gerenciador de investimento</h3>
    {!! Form::open(['route' => 'user.login', 'method' => 'post']) !!}
    <p>Acesse o sistema</p>
    <label>
        {!! Form::text('username', null, ['class' => 'input', 'placeholder' => "Usuário"]) !!}
    </label>
    <label>
        {!! Form::password('password', ['placeholder' => 'Senha']) !!}
    </label>
    {!! Form::submit('Entrar') !!}
    {!! Form::close() !!}
</section>

.env

PASSWORD_HASH=false

这个想法是,当注册用户时为假时,它将停止对密码进行加密;为真时,将进行加密。工作正常。

数据库用户

https://pasteboard.co/IcMC2ds.png

1 个答案:

答案 0 :(得分:0)

  1. 在不进行身份验证的情况下停止重定向到仪表板,请使用身份验证中间件路由

    Route :: middleware(['auth'])-> group(function(){

     Route::get('/dashboard', ['as' => 'user.dashboard', 'uses' => 'DashboardController@index']);
    

    });

  2. env返回字符串,而不是布尔值,因此请使用env('PASSWORD_HASH') == 'true'检查密码哈希是否启用

  3. 使用loginUsingId()手动登录。

    if(env('PASSWORD_HASH')=='true'){         Auth :: attempt($ data,false); }其他{     $ user = User :: where('email',$ request-> username)-> where('password',$ request-> password)-> first();

    if(!$user){
        throw new Exception("O e-mail informado é inválido. PEEEEN!");
    } else {
        Auth::loginUsingId($user->id);
        //redirect
    }
    

    }