AuthorizeMiddleware.php 2.04 KB
Newer Older
秦俊坤's avatar
秦俊坤 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?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;

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');
秦俊坤's avatar
秦俊坤 committed
26
        $method = $request->getMethod();
秦俊坤's avatar
秦俊坤 committed
27 28 29

        if (empty($route)) return $handler->handle($request);
        //获取对应的 route 对应的权限,如果 route 是不需要登录鉴权,直接返回
秦俊坤's avatar
秦俊坤 committed
30
        $passed  = $this->authRouter($applicationName, $route, $method, $token);
秦俊坤's avatar
秦俊坤 committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
        if ($passed)  {
            return $handler->handle($request);
        }

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

    }


    /**
     * 获取对应路由的权限,调用 RPC 服务
     * @param $applicationName
     * @param $route
     * @param $token
     * @return bool
     */
秦俊坤's avatar
秦俊坤 committed
48
    protected function authRouter($applicationName, $route, $method, $token):  bool
秦俊坤's avatar
秦俊坤 committed
49 50 51
    {
        $userId = $this->getUserIdByToken($token);

秦俊坤's avatar
秦俊坤 committed
52
        return $this->authorizationService->authByRouter($applicationName, $route, $method, $userId);
秦俊坤's avatar
秦俊坤 committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    }


    /**
     * 根据 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;
    }
}