簡體   English   中英

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

[英]Auth::user() return null in 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;
    }
}

配置/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,
        ],
    ],
];

儀表盤控制器

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. 停止重定向到沒有身份驗證的儀表板使用身份驗證中間件路由

    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); } else { $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 } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM