mercredi 30 décembre 2015

Laravel 5 middleware auth always fails and redirects to login

I am authenticating my user and redirecting him to dashboard if credentials are correct. I want to secure the dashboard route and added middleware auth, but now it always redirects to login page.

Routes.php

Route::get('login', array('uses' => 'HomeController@showLogin'));
Route::post('login', array('uses' => 'HomeController@doLogin'));
Route::get('logout', array('uses' => 'HomeController@doLogout'));

Route::group(['middleware' => 'auth'], function() {
    Route::get('/', function () {
        return view('dashboard');
    });
    Route::get('dashboard', function () {
        return view('dashboard');
    });
});

HomeController.php

public function showLogin(){
    return View::make('login');
}

public function doLogin(Request $request){
    $rules = array(
        'email'    => 'required|email',
        'password' => 'required|alphaNum|min:3'
    );
    $validator = Validator::make($request::all(), $rules);
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator)
            ->withRequest($request::except('password'));
    }
    else {
        $userdata = array(
            'email'     => $request::get('email'),
            'password'  => $request::get('password')
            /*'password' => Hash::make($request::get('password'))*/
        );
        if (Auth::attempt($userdata)) {
            $userid = Auth::id();
            return redirect()->intended('/');
        } else {
            return Redirect::to('login');
        }
    }
}

public function doLogout()
{
    Auth::logout();
    return Redirect::to('login');
}

Middleware Authenticate.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}

Middleware RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire