dongtang9855 2019-05-02 04:40
浏览 561
已采纳

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

I'm having a problem with authentication in my Laravel 5.8.10 project. I am not using the default form that Laravel creates for authentication. When I access the URL/dashboard in a browser, typically the user would get redirected redirect upon login. The application allows it anyway. Also when I give use Auth::user() it returns null.

When I type an invalid username and password, it's not passed from the login screen. When I type invalid credentials it redirects to the dashboard. The problem of accessing the URL through the dashboard view also continues. It's as if you do not need authentication to access the route.

Note: I have in my .env file a variable PASSWORD_HASH to enable or disable password encryption.

User model

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

Routes

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

View login

<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

The idea is that when it's false when registering a user it stops encrypting the password, and when true, do the encryption. This is working.

Database User

https://pasteboard.co/IcMC2ds.png

  • 写回答

1条回答 默认 最新

  • dptiq46022 2019-05-02 04:52
    关注
    1. to stop redirecting to dashboard without auth use auth middleware route

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

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

      });

    2. env return string, not boolean values so use env('PASSWORD_HASH') == 'true' to check password hash is enable or not

    3. use loginUsingId() to login in manually.

      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
      }
      

      }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案