[英]How to Protect the admin Panel in Laravel 5.2
我创建了一个 eCommerace 应用程序,它具有管理面板和用户视图(产品商店),我希望管理员访问管理面板,而其他用户只能访问特定的 URL 和产品详细信息等。我已经通过php artisan make:auth
为我的应用程序安装了身份验证php artisan make:auth
并且它工作正常,但我现在想要做的是应用一个过滤器,该过滤器将仅向 ADMIN 显示管理面板,并将存储显示给其他用户。
我已经在我的数据库中声明了一个布尔字段,默认情况下,普通用户的值为 0,管理员的值为 1。
迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
身份验证控制器:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255', /**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
正如@AnowarCst 所说。 使用中间件。
在项目根目录中:
php artisan make:middleware Admin
打开新文件App/Http/Middleware/Admin.php
。
在handle()
方法中添加:
if ( Auth::check() && Auth::user()->isAdmin() )
{
return $next($request);
}
return redirect('/');
打开App/Http/Kernel.php
并将以下内容添加到$routeMiddleware
数组中:
'admin' => \App\Http\Middleware\Admin::class,
打开用户模型: App/User.php
添加
/**
* Check if user is admin.
*
* @return bool
*/
public function isAdmin()
{
return $this->admin;
}
现在你可以使用routes.php
文件中的中间件:
Route::get('/uri-that-users-will-see', ['middleware' => ['auth','admin'], 'as' => 'your-route-name', 'uses' => 'YourController@yourMethod']);
这主要来自头部,所以如果我跳过某些内容或有错误,请报告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.