AuthorizeMiddleware.php 2.01 KB
Newer Older
秦俊坤's avatar
秦俊坤 committed
1 2 3 4 5 6 7 8 9 10
<?php

namespace Meibuyu\Micro\Middleware;

use Meibuyu\Micro\Model\Auth;
use Meibuyu\Micro\Service\Interfaces\User\AuthenticationServiceInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
秦俊坤's avatar
秦俊坤 committed
11
use Hyperf\Di\Annotation\Inject;
秦俊坤's avatar
秦俊坤 committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

class AuthorizeMiddleware implements MiddlewareInterface
{

    /**
     * @Inject()
     * @var AuthenticationServiceInterface
     */
    private $authorizationService;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $route = $request->getUri()->getPath();
        $token = token();
        $applicationName = env('APP_NAME');

        if (empty($route)) return $handler->handle($request);
        //获取对应的 route 对应的权限,如果 route 是不需要登录鉴权,直接返回
        $passed  = $this->routerAuth($applicationName, $route, $token);
        if ($passed)  {
            return $handler->handle($request);
        }

        return response()->withStatus(403);     //鉴权失败,错误码 403 forbidden
        //route 是需要登录鉴权的,判断当前用户是佛有对应  route 的权限

    }


    /**
     * 获取对应路由的权限,调用 RPC 服务
     * @param $applicationName
     * @param $route
     * @param $token
     * @return bool
     */
    protected function routerAuth($applicationName, $route, $token):  bool
    {
        $userId = $this->getUserIdByToken($token);

        return $this->authorizationService->authByRouter($applicationName, $route, $userId);
    }


    /**
     * 根据 token 获取对应的 user_id
     * @param $token
     * @return int|mixed
     */
    protected function getUserIdByToken($token)
    {
        if (empty($token)) return 0;
        $user = redis()->get($token);
        if ( ! $user)  return 0;

        $userArr =   \json_decode($user, true);
        return !empty($userArr['id']) ? $userArr['id'] : 0;
    }
}