| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- namespace app\agent\middleware;
- use app\agent\model\auth\Log;
- use CasbinAdapter\Think\Facades\AgentCasbin;
- use Lettered\Support\Auth as IAuth;
- use Lettered\Support\Exceptions\ForbiddenException;
- use CasbinAdapter\Think\Facades\Casbin;
- /**
- * 操作权限验证
- * Class CasbinAuthMiddleware
- * @package app\http\middleware
- */
- class CasbinAuthMiddleware
- {
- /**
- * @var IAuth
- */
- protected $auth;
- /**
- * CasbinAuthMiddleware constructor.
- * @param IAuth $auth
- */
- public function __construct(IAuth $auth)
- {
- // 这里要做下来源 是admin 还是agent
- $this->auth = $auth->guard('agent');
- }
- /**
- * Casbin 授权验证
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/3/21 20:28
- *
- * @param $request
- * @param \Closure $next
- * @return mixed
- * @throws ForbiddenException
- * @throws \Casbin\Exceptions\CasbinException
- * @throws \Lettered\Support\Exceptions\FailedException
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function handle($request, \Closure $next)
- {
- // 操作权限验证 v0 v1 v2
- // Uid Uri Method
- // 当前用户
- $user = $this->auth->user();
- // 在这里替换空
- // $baseUrl = str_replace('/agent', '', $request->baseUrl());
- $baseUrl = $request->baseUrl();
- // 检查忽略项
- if (in_array($baseUrl . '^' . strtolower($request->method()), config('casbin.ignore.policy'))
- || in_array($user->id, str2arr(config('casbin.ignore.users_idx')))) {
- } elseif (!AgentCasbin::enforce('user_id_' . $user->id, $baseUrl, strtolower($request->method()))) {
- $baseUrl = str_replace('/agent', '', $request->baseUrl());
- if (!AgentCasbin::enforce('user_id_' . $user->id, $baseUrl, strtolower($request->method()))) {
- throw new ForbiddenException([
- 'errmsg' => 'Unauthorized: 您无权操作!' . enjson(['user_id_' . $user->id, $baseUrl, strtolower($request->method())])
- ]);
- }
- }
- // 操作记录
- $log =[
- 'user_id' => $user->id,
- 'route' => $request->baseUrl(),
- 'operate' => strtolower($request->method()),
- 'query' => enjson($request->param()),
- 'ip' => $request->ip(),
- 'os' => get_user_agent(),
- 'browser' => get_user_agent('br')
- ];
- $Log = new Log();
- // 系统日志记录
- $result = $Log::where($log)->find();
- if (!$result) {
- $Log::create($log);
- } else {
- $log['id'] = $result->id;
- $log['count'] = $result->count+1;
- $Log::update($log);
- }
- return $next($request);
- }
- }
|