2016-02-28 99 views
0

我正在使用laravel 5.1和模塊化程序包。 在我控制我用下面的登錄方法:Laravel 5.1身份驗證視圖

public function postLogin(Request $request) 
{ 
    $email = $request->input('email'); 
    $password = $request->input('password'); 

    if (Auth::attempt(['email' => $email, 'password' => $password])) { 
     return redirect()->intended('admin/dashboard'); 
    } 

    return redirect('/login')->withErrors([ 
    'email' => 'These credentials do not match our records.']); 
} 

我的路線:

Route::group(array('module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'), function() { 

Route::get('admin/dashboard', [ 
    'middleware' => 'auth', 
    'uses' => '[email protected]' 
]); 
}} 

我的控制器:

public function index() 
{ 
    return view("Admin::index"); 
} 

我中間件/身份驗證:

public function handle($request, Closure $next) 
    { 
    if ($this->auth->guest()) { 
     if ($request->ajax()) { 
      return response('Unauthorized.', 401); 
     } else { 
      return redirect()->guest('auth/login'); 
     } 
    } 

    return $next($request); 
} 

這會工作並在登錄後將我重定向到索引視圖。 當用戶未登錄時,仍然可以通過訪問url:localhost/admin/dashboard來訪問索引視圖。

如何將用戶重定向到自定義頁面,該頁面向用戶顯示錯誤信息,表示當他未登錄時無法訪問url localhost/admin/dashboard?

任何想法?謝謝

回答

0
The issue is with your route the middleware should be at the top level as soon as you hit the controller it should redirect if not authenticated 

    Route::group(['middleware'=>'auth','module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'], function() 
    { 
     Route::get('admin/dashboard', ['uses' => '[email protected]']); 
    }); 

secondly if you want to redirect user to a custom page you can do this 

public function redirectUnAuthenticateUser() 
{ 

\Session::flash('login_error', 'Kindly login before you can access this page'); 
//create a view that user would be redirected to 
return view('session.unauthenticated') ; 
} 


and the change your auth function to below 

public function handle($request, Closure $next) 
    { 
    if ($this->auth->guest()) { 
     if ($request->ajax()) { 
      return response('Unauthorized.', 401); 
     } else { 
return redirect()->route('you-custom-rout-name-matching-above-function'); 
     } 
    } 

    return $next($request); 
} 

and on your view you can get the value of the flash message