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

1 Answer 1

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
      }
    }
    
Sign up to request clarification or add additional context in comments.

7 Comments

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 !!
Now when I do dd (Auth :: user ()) it returns the array with the authenticated user, Thanks :D
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
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.
dd(Auth::attempt($credentials)); is return false :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.