3

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

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Martins
  • 45
  • 1
  • 1
  • 6

1 Answers1

2
  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
      }
    }
    
JON
  • 965
  • 2
  • 10
  • 28
Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31
  • Dude, it worked! At first it seems that the problem was just the lack of this middleware. I made the correction on the PASSWORD_HASH check too, thank you !! – Martins May 02 '19 at 05:08
  • Now when I do dd (Auth :: user ()) it returns the array with the authenticated user, Thanks :D – Martins May 02 '19 at 05:09
  • Hey friend, actually I noticed that he is authenticating with any email and password I put, do you know what it can be? And regardless of the user that logged in it appears a user that logged in for the first time – Martins May 02 '19 at 05:36
  • you are authenticating the user based on email and password, so do not need to check password hash condition in the controller as it already managed by Model. check answer I've edited just now. – Sunil Kashyap May 02 '19 at 05:50
  • dd(Auth::attempt($credentials)); is return false :/ – Martins May 02 '19 at 17:35
  • yes, recently check laravel uses advanced auth check function so try with loginInwithUserId() function... edited answer. – Sunil Kashyap May 02 '19 at 18:13
  • Dude it worked, it looks like it's now running smoothly with both true and false hashes. Thank you very much indeed! – Martins May 02 '19 at 18:36