Back

Auth::check() is not working


I am trying to authenticate users in my Laravel application.

I am encountering the following problem:
-> Using driver database in auth.php: I can login using auth::attempt(), and auth::check is working, but I can't validate if the logged in user has a certain role. -> Using driver eloquent in auth.php: I can login using auth::attempt(), but auth::check is not working. I can however check the role of the logged in user.

How can I fix this so that with only one of the drivers, i can do a complete authentication and role check?

Migration tables:

    Schema::create('users', function ($table) {
            $table->increments('id');
            $table->integer('group_id')->unsigned();
            $table->string('name', 64);
            $table->string('email', 64)->unique();
            $table->string('username', 64)->unique();
            $table->string('phone', 13);
            $table->string('address', 64);
            $table->boolean('isresponsible');
            $table->string('password', 64);
            $table->rememberToken()->nullable();
        });
    Schema::create('roles', function ($table) {
            $table->increments('id');
            $table->string('name');
        });

    Schema::create('users_roles', function ($table) {
                $table->integer('user_id')->unsigned();
                $table->integer('role_id')->unsigned();
            }
        );
    Schema::table('users_roles', function($table){
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles');
        });

model class User

    <?php
    use Illuminate\Auth\UserTrait;`
    use Illuminate\Auth\UserInterface;`
    use Illuminate\Auth\Reminders\RemindableTrait;
    use Illuminate\Auth\Reminders\RemindableInterface;

    class User extends Eloquent implements UserInterface, RemindableInterface {


    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';
    public $timestamps = false;

    public static $rules = ['name' => 'required', 'group_id' => 'required', 'email' => 'required', 'phone' => 'required'];
    protected $fillable = ['name', 'group_id', 'email', 'phone', 'address', 'isresponsible', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function group()
    {
        return $this->belongsTo('Group');
    }

    public function userroles(){
        return $this->hasMany('Userrole');
    }

    public function roles()
    {
        return $this->belongsToMany('Role', 'users_roles');
    }

    public function hasRole($check)
    {
        dd($this->roles->toArray());
        return in_array($check, array_fetch($this->roles->toArray(), 'name'));
    }

    public function setBasicPassword($id){
        $user = User::find($id);
        $user->password = Hash::make('changeme');
        $user->save();
    }

    public function isValid()
    {
        $validation = Validator::make($this->attributes, static::$rules);
        if ($validation->passes()) return true;
        $this->messages = $validation->messages();
        return false;
    }


    /**
     * Get the e-mail address where password reminders are sent.
     *
     * @return string
     */
    public function getReminderEmail()
    {
        // TODO: Implement getReminderEmail() method.
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->email;
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->remember_token;
    }

    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    public function getRememberTokenName()
    {
        return 'remember_token';
    }
    }

model Class Role

    <?php

    class Role extends Eloquent
    {

    protected $table = 'roles';
    public $timestamps = false;

    public static $rules = ['role_id' => 'required', 'name' => 'required'];
    protected $fillable = ['name'];

    /**
     * Get users with a certain role
     */
    public function userroles()
    {
        return $this->belongsToMany('User', 'users_roles');
    }
    }

HomeController authentication function

     public function authenticate(){
        $rules = array(
            'email'    => 'required|email',
            'password' => 'required|alphaNum|min:3'
        );
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Redirect::to('login')
                ->withErrors($validator)
                ->withInput(Input::except('password'));
        } else {
            $userdata = array(
                'email' => Input::get('email'),
                'password' => Input::get('password')
            );
            if (Auth::attempt($userdata, true)) {
                return Redirect::action('[email protected]');

            } else {
                return Redirect::action('[email protected]')->withInput();
            }
        }
    }

USING THE DATABASE DRIVER

  • auth:attempt() and auth::check are working

    $this->beforeFilter('admin', ['only' => ['index']]); //filter in controller //filter in filters;php Route::filter('admin', function() { if(!Auth::check()) return Redirect::action('[email protected]'); if(!Auth::user()->hasRole('admin')) return View::make('errors.401'); });

This fails with 'Call to undefined method Illuminate\Auth\GenericUser::hasRole()'

USING THE ELOQUENT DRIVER

  • auth::attempt() succeeds
  • auth::check() fails
  • no error on the filter
nomie7 replied 3 years ago

Here is my understanding... I could be wrong.. Im fairly new to laravel.

Auth::check only works...

You have to do Auth::attempt() AND redirect to a route. (this is where the session is set on redirect)

Once you do that your Auth::check() will work.

shez1983 replied 3 years ago

What version are you using (Laravel 4 or the upcoming 5)

crystalpal replied 3 years ago Solution

The problem was that I was wrongly overwriting the getAuthIdentifier()-method in my User class


public function getAuthIdentifier()
    {
        return $this->email; //should be changed to
        return $this->id;
    }


removing all overwritten methods also solves the problem

Learner replied 3 years ago

In my case, this command made Auth::check() work.

php artisan cache:clear

But a few days later, it doesn't work anymore. I tried to protect some URLs, so that I used auth middleware for a group of URLs. For some hours, everything's fine. But Auth::check() returns false again, though I did nothing.

Is that a bug of Laravel 5?


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us