整合spatie/laravel-permission和lara

2024-01-17  本文已影响0人  liurongming
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    use HasRoles;
 
   protected $guard_name ='sanctum';

}
 protected $middlewareAliases = [
        'check.permission'=>\App\Http\Middleware\CheckPermission::class,
 ];

在route.php 下,添加 'check.permission'中间件,这样就可以统一认证。
需要给每个路由命名name('user.info')

Route::middleware(['auth:sanctum', 'check.permission'])->group(function () {
    Route::get('/user/info', [\App\Http\Controllers\Api\UserController::class, 'info'])->name('user.info');
    Route::get('/user/{uid}/info', [\App\Http\Controllers\Api\UserController::class, 'info'])->name('user.info');
});

中间件实现:
核心代码就一句:$user->can($request->route()->getName())

<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (!$user->can($request->route()->getName())) {
            throw new ApiException(__("http-statuses.403"), 403);
        }
        return $next($request);
    }
}
上一篇下一篇

猜你喜欢

热点阅读