有没有人知道在Laravel 5.3中没有扩展的简单方法:
如果当前用户是admin,则在登录/注册后 - >重定向到管理页面。如果当前用户是网络用户 - >重定向到主页。
在数据库中我放置字段$ table-> boolean(' admin') - > nullable(); 因此,当用户注册时,他默认不是管理员。
目前我做到了。我收到错误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'); }
}
答案 0 :(得分:1)
登录后,请执行以下操作:
if(auth()->user()->admin) {
// redirect to admin page
} else {
// redirect to home page
}
答案 1 :(得分:1)
首先,您可以在app \ Http \ Middleware \ AdminMiddleware.php中使用它。 它将检查用户是否首先登录,然后检查用户是否为管理员。
您收到该错误的原因可能是因为您错误地包含了 Auth 。
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'中间件。
答案 2 :(得分: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']);
}
}
同样的方法适用于RegisterController
和ResetPasswordController
。
答案 3 :(得分: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)在\ app \ Http \ Middleware中创建一个名为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)替换\ app \ Http \ Kernel.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)最重要的一点你的路径文件\ routes \ web.php应该是类似下面的控制器可能会根据你的要求而有所不同
Auth::routes();
Route::get('/', 'Auth\LoginController@showLoginForm');
Route::group(['middleware' => ['CheckRole'], 'roles' => ['admin']], function () {
//Route::get('/home', 'HomeController@index');
Route::get('/admin/dashboard', 'AdminController@index');
//Route::get('/home', 'HomeController@index');
});
Route::group(['middleware' => ['CheckRole'], 'roles' => ['employee']], function () {
//Route::get('/home', 'HomeController@index');
Route::get('/employee', 'EmployeeController@index');
});