2016-11-06 164 views
0

有誰知道簡單的方法,使在Laravel 5.3不帶擴展名登錄後:Laravel 5.3重定向到管理頁面只有當用戶是管理員

如果當前用戶是管理員,再經過登錄/註冊 - >使重定向到管理員頁。如果當前用戶是Web用戶 - >重定向到主頁。在數據庫中我把字段$表 - >布爾('admin') - >空(); 所以當用戶註冊他默認情況下不是管理員。

目前我做到了。我得到錯誤Call to undefined method Illuminate\Support\Facades\Auth::check() in AdminMiddleware.php

應用程序\ HTTP \中間件\ AdminMiddleware.php

namespace App\Http\Middleware; 
use Closure; 
use Illuminate\Support\Facades\Auth; 

class AdminMiddleware 
{ 
    public function __construct(Auth $auth) 
    { 
     $this->auth = $auth; 
    } 
    public function handle($request, Closure $next) 
    { 
     if ($this->auth->check()) { 
      if (! $this->auth->user()->isAdmin()) { 
       Auth::logout(); 
       return redirect()->guest('/'); 
      } 
     } 
     return $next($request); 
    } 
} 

Kernel.php

protected $routeMiddleware = [ 
    ... 
    'admin' => \App\Http\Middleware\AdminMiddleware::class, 
]; 

應用程序\ HTTP \控制器\ AdminController.php

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 

class AdminController extends Controller 
{ 

    public function __construct() 
    {  $this->middleware('auth'); } 

    public function index() 
    {  return view('admin.dashboard'); } 

    public function registered() 
    {  return view('admin.registered'); } 

} 

回答

1

登錄後可以這樣做:

if(auth()->user()->admin) { 
    // redirect to admin page 
} else { 
    // redirect to home page 
} 
1

首先你可以使用這個app \ Http \ Middleware \ AdminMiddleware.php。 它將檢查用戶是否首先登錄,然後如果用戶是管理員。

您得到該錯誤的原因可能是您包含驗證碼錯誤的方法。

namespace App\Http\Middleware; 
use Closure; 
use Auth; 

class AdminMiddleware 
{ 


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

     /** 
     * Checks if user is Admin 
     */ 
     if(!$this->CheckAdmin()){ 

      //redirect to admin login 
      return redirect('/admin/login'); 

     } 

     /** 
     * Prodceed to next request 
     */ 
     return $next($request); 

    } 

    /** 
    * Checks if user is logged in as an admin 
    */ 
    private function CheckAdmin(){ 

     /** 
     * Check If User Is Logged In 
     */ 
     if (!Auth::check()) { 

      return false; 

     } 

     /** 
     * Check If User has administrator role 
     */ 
     if (!Auth::user()->isAdmin()) { 

      return false; 

     } 

     //passed Admin rules 
     return true; 

    } 


} 

不要忘了在控制器中使用'admin'中間件。看來你正在使用標準的'auth'中間件。

0

遵循以下步驟: -

1)在phpMyAdmin

CREATE TABLE `role` (
    `id` int(10) UNSIGNED NOT NULL, 
    `role_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
    `role_description` text COLLATE utf8_unicode_ci NOT NULL, 
    `created_at` timestamp NULL DEFAULT NULL, 
    `updated_at` timestamp NULL DEFAULT NULL 
) ENGINE=InnoDB DEFAULT 

ALTER TABLE `role` 
    ADD PRIMARY KEY (`id`); 

-- 
-- AUTO_INCREMENT for dumped tables 
-- 

-- 
-- AUTO_INCREMENT for table `role` 
-- 
ALTER TABLE `role` 
    MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; 

2創建新表)添加​​在用戶表的外鍵

CREATE TABLE `users` (
    `id` int(10) UNSIGNED NOT NULL, 
    `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
    `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
    `user_role` int(11) NOT NULL DEFAULT '0', 
    `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
    `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, 
    `created_at` timestamp NULL DEFAULT NULL, 
    `updated_at` timestamp NULL DEFAULT NULL, 
    `status` enum('0','1','2') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0' 
) ENGINE=InnoDB DEFAULT; 

3)添加以下代碼在用戶模型中,即user.php App/User.php

/** 
    * Description : check user role which type of users login 
    */ 
    public function role() 
    { 
     return $this->hasOne('App\Role', 'id', 'user_role'); 
    } 
    /** 
    * Description : check has role if user has any role assigned 
    */ 
    public function hasRole($roles) 
    { 
     //die('inside hasRole'); 

     $this->have_role = $this->getUserRole(); 

     // Check if the user is a root account 
     if($this->have_role->role_name == 'Admin') { 
      return true; 
     } 

     if(is_array($roles)){ 
      foreach($roles as $need_role){ 
       if($this->checkIfUserHasRole($need_role)) { 
        return true; 
       } 
      } 
     } else{ 
      return $this->checkIfUserHasRole($roles); 
     } 
     return false; 
    } 

    /** 
    * Description : check role from database 
    */ 
    private function getUserRole() 
    { 
     return $this->role()->getResults(); 
    } 

    // 
    private function checkIfUserHasRole($need_role) 
    { 
     return (strtolower($need_role)==strtolower($this->have_role->role_name)) ? true : false; 
    } 

4)建立內部\程序\的Http一個新的文件\中間件CheckRole.php的名稱添加以下代碼,在這個文件中

<?php 
namespace App\Http\Middleware; 

// First copy this file into your middleware directory 

use Closure; 

use Illuminate\Support\Facades\Auth; 

class CheckRole{ 

    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     // Get the required roles from the route 
     $roles = $this->getRequiredRoleForRoute($request->route()); 

     // Check if a role is required for the route, and 
     // if so, ensure that the user has that role. 
     if($request->user()->hasRole($roles) || !$roles) 
     { 
      return $next($request); 
     } 

     return redirect('admin/logout'); 
     /*return response([ 

      'error' => [ 
       'code' => 'INSUFFICIENT_ROLE', 
       'description' => 'You are not authorized to access this resource.' 
      ] 
     ], 401);*/ 

    } 

    private function getRequiredRoleForRoute($route) 
    { 
     $actions = $route->getAction(); 
     return isset($actions['roles']) ? $actions['roles'] : null; 
    } 

} 

5)替換\程序\ HTTP將下面的代碼\核心。PHP

protected $middlewareGroups = [ 
     'web' => [ 
      \App\Http\Middleware\EncryptCookies::class, 
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 
      \Illuminate\Session\Middleware\StartSession::class, 
      \Illuminate\View\Middleware\ShareErrorsFromSession::class, 
      \App\Http\Middleware\VerifyCsrfToken::class, 
      \Illuminate\Routing\Middleware\SubstituteBindings::class, 
     ], 
     'api' => [ 
      'throttle:60,1', 
      'bindings', 
     ], 
    ]; 

下面的代碼

protected $middlewareGroups = [ 
     'web' => [ 
      \App\Http\Middleware\EncryptCookies::class, 
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 
      \Illuminate\Session\Middleware\StartSession::class, 
      \Illuminate\View\Middleware\ShareErrorsFromSession::class, 
      \App\Http\Middleware\VerifyCsrfToken::class, 
      \Illuminate\Routing\Middleware\SubstituteBindings::class, 
     ], 
     'CheckRole' => [ 
      'web', 
      'auth', 
      'roles' 
     ], 
     'api' => [ 
      'throttle:60,1', 
      'bindings', 
     ], 
    ]; 

而且

protected $routeMiddleware = [ 
     'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 
     'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
     'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 
     'can' => \Illuminate\Auth\Middleware\Authorize::class, 
     'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
     'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 
    ]; 

下面的代碼

protected $routeMiddleware = [ 
     'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 
     'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
     'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 
     'can' => \Illuminate\Auth\Middleware\Authorize::class, 
     'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
     'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 
     'roles'  => 'App\Http\Middleware\CheckRole', 
    ]; 

6)最重要的一點,你的狂勝文件\路徑\ web.php應該像下面的控制器可能是根據您的要求而定

Auth::routes(); 

Route::get('/', 'Auth\[email protected]'); 



Route::group(['middleware' => ['CheckRole'], 'roles' => ['admin']], function() { 
    //Route::get('/home', '[email protected]'); 
    Route::get('/admin/dashboard', '[email protected]'); 
    //Route::get('/home', '[email protected]'); 

}); 

Route::group(['middleware' => ['CheckRole'], 'roles' => ['employee']], function() { 
    //Route::get('/home', '[email protected]'); 
    Route::get('/employee', '[email protected]'); 

}); 
1

Laravel使用RedirectUsers::redirectPath()獲取重定向路徑。

它只檢查屬性redirectTo

如果您想要應用自定義邏輯 - 只需在您的控制器中覆蓋redirectPath()方法。

namespace App\Http\Controllers\Auth; 
use App\Http\Controllers\Controller; 
use Illuminate\Foundation\Auth\AuthenticatesUsers; 
use Illuminate\Support\Facades\Auth; 

class LoginController extends Controller 
{ 
    use AuthenticatesUsers; 

    // protected $redirectTo = '/'; 
    public function redirectPath() 
    { 
     // ... 
     // custom logic here 
     // ... 

     // return desired URL 
     return '/my/custom/url/here'; 
    } 

    public function __construct() 
    { 
     $this->middleware('guest', ['except' => 'logout']); 
    } 

} 

同樣的方法將用於RegisterControllerResetPasswordController工作。