Laravel 5.1身份验证视图

时间:2016-02-28 21:28:20

标签: laravel laravel-5

我正在使用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' => 'AdminController@index'
]);
}}

我的控制器:

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的错误?

有什么想法吗?谢谢

1 个答案:

答案 0 :(得分: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' => 'AdminController@index']);
    });

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