当一个web系统有登录功能时,那么有些页面只有当用户登录后才能访问,有些页面登录后就不能再访问,这个时候laravel的中间件限制越权访问功能就派上用场了,上代码。
未登录用户不能访问http://student.dev/admin/index,控制器位于app/Http/Controllers/Admin/IndexController.php
<?php
namespace App\Http\Controllers\Admin;
class IndexController extends BaseController
{
public function __construct()
{
// 未登录用户只能访问index页面,访问其他页面即跳转至登录页面
$this->middleware('auth', [
'except' => ['index']
]);
// 只准未登录用户访问,已登录用户不能访问
$this->middleware('guest', [
'only' => ['index', 'login']
]);
}
public function index()
{
return view('admin.index');
}
}
- 用户只能编辑自己的资料
$ php artisan make:policy UserPolicy
- 让我们为默认生成的用户授权策略添加 update 方法,用于用户更新时的权限验证。app/Policies/UserPolicy.php
<?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use App\Models\User;
class UserPolicy
{
use HandlesAuthorization;
public function update(User $currentUser, User $user)
{
return $currentUser->id === $user->id;
}
}
- 为用户模型 User 指定授权策略 UserPolicy:app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;
.
,
.
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
\App\Models\User::class => \App\Policies\UserPolicy::class,
];
}
- 在用户控制器中使用 authorize 方法来验证用户授权策略:app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
.
.
.
class UsersController extends Controller
{
.
.
.
public function edit(User $user)
{
$this->authorize('update', $user);
return view('users.edit', compact('user'));
}
public function update(User $user, Request $request)
{
$this->validate($request, [
'name' => 'required|max:50',
'password' => 'nullable|confirmed|min:6'
]);
$this->authorize('update', $user);
$data = [];
$data['name'] = $request->name;
if ($request->password) {
$data['password'] = bcrypt($request->password);
}
$user->update($data);
session()->flash('success', '个人资料更新成功!');
return redirect()->route('users.show', $user->id);
}
}