mercredi 10 mai 2017

Laravel middleware always logs out

I'm working with Laravel 5.1, and I have been searching the answer for this problem long ago, but I've been not succeed.

The problem takes place when a super-administrator tries to login. The whole login process is implemented in AJAX, so when the login takes place AJAX awaits for the redirection url while the Authentication process is taken by an Auth Controller.

If the request is ok, the a dashboard url is sent back to the ajax, BUT the middleware logs me out once the redirection is performed.

The auth WelcomeController to validate the super-admin looks like this (this works just fine, delivering the propper redirection url):

\Config::set('auth.model', 'App\Super_Admin');

        $sadmin = \Auth::createEloquentDriver();

        \Auth::setProvider($sadmin->getProvider());

        //Admin verification
        if(\Auth::attempt(['system_admin_user' => $request->username, 'password' => $request->password])) {

            \Auth::user()->setAttribute('profile','SuperAdmin');
            \Session::set('sadmin_name',\Auth::user()->system_admin_fullname);

            return response()->json(['login_status' => 'success', 'redirect' => 'SuperAdmin/dashboard', 'error' =>'']);
        }
        else {
            return response()->json(['login_status' => 'invalid', 'error' => 'Usuario y/o password invalidos', 'redirect' => '/']);
        }

The function to handle the requests in Middleware is_admin looks like this (not working as intended):

public function handle($request, Closure $next)
{

    if(\Auth::check() && \Auth::user()->profile == "SuperAdmin") {
            return redirect('/');
    }
    else {
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

I also tried with a different code of the middleware:

public function handle($request, Closure $next)
{
    if(!\Auth::check() || \Auth::user()->profile != "SuperAdmin") {
        $this->auth->logout();
    }

    return $next($request);
}

The route group protected for the admin is defined like this:

Route::group(['middleware' => ['auth','is_superAdmin']], function() {
    Route::get('SuperAdmin/dashboard', 'Super_Admin\SuperAdminController@index');
});

If anyone could tell me the propper way to do this, I would be very happy! Thank you in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire