【问题标题】:Laravel 5.1 Authentication viewsLaravel 5.1 身份验证视图
【发布时间】:2016-06-11 20:08:57
【问题描述】:

我正在使用 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?

有什么想法吗?谢谢

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:
        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2016-04-29
      相关资源
      最近更新 更多