From 3a1f888c5d7f8cedf27e5cf6313f75b07e2dcff7 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Mon, 7 Nov 2022 16:38:48 +0800 Subject: [PATCH 01/15] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/JsonRpc/UserExternalServiceInterface.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/JsonRpc/UserExternalServiceInterface.php b/app/JsonRpc/UserExternalServiceInterface.php index c6a7e2b..a38371e 100644 --- a/app/JsonRpc/UserExternalServiceInterface.php +++ b/app/JsonRpc/UserExternalServiceInterface.php @@ -7,8 +7,8 @@ interface UserExternalServiceInterface /** * 通过微信授权新建用户 * - * @param string $open_id + * @param string $openid * @return array */ - public function wechatNewUser(string $open_id) : array; + public function wechatNewUser(string $openid) : array; } \ No newline at end of file From 936eb10eeca70f5337cc58cd95f601f15922df07 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Mon, 7 Nov 2022 17:02:38 +0800 Subject: [PATCH 02/15] =?UTF-8?q?RPC=E8=B0=83=E7=94=A8=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=B1=A0=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/autoload/dependencies.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index f46bd96..f8d6b69 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -9,5 +9,9 @@ declare(strict_types=1); * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ +use Hyperf\JsonRpc\JsonRpcPoolTransporter; +use Hyperf\JsonRpc\JsonRpcTransporter; + return [ + JsonRpcTransporter::class => JsonRpcPoolTransporter::class, ]; From c5f301b9ada04e2188641cb264fc4d5d8c39bd5d Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Tue, 8 Nov 2022 11:38:31 +0800 Subject: [PATCH 03/15] =?UTF-8?q?=E5=A4=84=E7=90=86=E7=BD=91=E5=85=B3?= =?UTF-8?q?=E7=9A=84=E8=80=83=E5=8B=A4=E7=B3=BB=E7=BB=9F=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E5=89=8D=E7=BC=80=EF=BC=8C=E5=8F=8A=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E8=AF=B7=E6=B1=82=E5=A4=84=E7=90=86=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=B1=BB=E7=9A=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => PunchCard}/Wechat/AuthController.php | 8 +-- app/Helper/Curl.php | 58 +++++++++++++++++-- app/Service/Wechat/AuthService.php | 23 ++++++++ 3 files changed, 81 insertions(+), 8 deletions(-) rename app/Controller/{ => PunchCard}/Wechat/AuthController.php (79%) diff --git a/app/Controller/Wechat/AuthController.php b/app/Controller/PunchCard/Wechat/AuthController.php similarity index 79% rename from app/Controller/Wechat/AuthController.php rename to app/Controller/PunchCard/Wechat/AuthController.php index 76a0123..fa8ee32 100644 --- a/app/Controller/Wechat/AuthController.php +++ b/app/Controller/PunchCard/Wechat/AuthController.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Controller\Wechat; +namespace App\Controller\PunchCard\Wechat; use App\Controller\BaseController; use App\Exception\BusinessException; @@ -10,12 +10,12 @@ use app\Constants\Wechat\AuthErrorCode; use App\Service\Wechat\AuthService; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; -use Hyperf\HttpServer\Annotation\PostMapping; +use Hyperf\HttpServer\Annotation\RequestMapping; /** * 微信授权处理控制器 */ -#[Controller] +#[Controller(prefix: "kq")] class AuthController extends BaseController { #[Inject] @@ -26,7 +26,7 @@ class AuthController extends BaseController * * @return array */ - #[PostMapping(path: "auth/code2OpenID")] + #[RequestMapping(path: "auth/code2OpenID", methods: "get,post")] public function code2OpenID() : array { $code = $this->request->input('code', ''); diff --git a/app/Helper/Curl.php b/app/Helper/Curl.php index 06f1c14..309cac1 100644 --- a/app/Helper/Curl.php +++ b/app/Helper/Curl.php @@ -7,19 +7,46 @@ namespace App\Helper; use GuzzleHttp\Client; use Hyperf\Guzzle\HandlerStackFactory; +/** + * 请求处理公共类 + */ class Curl { - public static function get(string $url) : array + /** + * 获取Guzzle客户端实例(使用连接池) + * + * @return Client + */ + protected static function getClient() : Client { $factory = new HandlerStackFactory(); $stack = $factory->create(); - $client = make(Client::class, [ + return make(Client::class, [ 'config' => [ 'handler' => $stack, ] ]); - $response = $client->get($url, ['timeout' => 2]); + } + + /** + * 发送Get请求 + * + * @param string $url + * @param array $headers + * @return array + * @throws \GuzzleHttp\Exception\GuzzleException + */ + public static function get(string $url, array $headers = []) : array + { + $client = self::getClient(); + $options = ['timeout' => 2, 'verify' => false]; + + if (!empty($headers)) { + $options['headers'] = $headers; + } + + $response = $client->get($url, $options); if ($response->getStatusCode() === 200) { return json_decode($response->getBody()->getContents(), true); @@ -28,7 +55,30 @@ class Curl return []; } - public static function post(string $url, array $data = []) + /** + * 发送POST请求(application/x-www-form-urlencoded) + * + * @param string $url + * @param array $data + * @param array $headers + * @return array + * @throws \GuzzleHttp\Exception\GuzzleException + */ + public static function post(string $url, array $data = [], array $headers = []) : array { + $client = self::getClient(); + $options = ['timeout' => 2, 'verify' => false, 'form_params' => $data]; + + if (!empty($headers)) { + $options['headers'] = $headers; + } + + $response = $client->post($url, $options); + + if ($response->getStatusCode() === 200) { + return json_decode($response->getBody()->getContents(), true); + } + + return []; } } \ No newline at end of file diff --git a/app/Service/Wechat/AuthService.php b/app/Service/Wechat/AuthService.php index 6889db9..3bd2605 100644 --- a/app/Service/Wechat/AuthService.php +++ b/app/Service/Wechat/AuthService.php @@ -8,17 +8,40 @@ use App\JsonRpc\UserExternalServiceInterface; use Hyperf\Config\Annotation\Value; use Hyperf\Di\Annotation\Inject; +/** + * 微信授权处理服务层 + */ class AuthService { + /** + * 考勤系统小程序APPID + * + * @var string + */ #[Value("app.wechat_punch_card_appid")] protected string $appid; + /** + * 考勤系统小程序APPSecret + * + * @var string + */ #[Value("app.wechat_punch_card_secret")] protected string $secret; + /** + * 用户中心对外RPC服务 + * + * @var UserExternalServiceInterface + */ #[Inject] protected UserExternalServiceInterface $userExternalService; + /** + * 微信通过code获取session信息请求地址 + * + * @var string + */ protected string $wechat_auth_url = 'https://api.weixin.qq.com/sns/jscode2session'; /** From f769f7ec024b3c8dd22566ff99964079423a3fef Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Tue, 8 Nov 2022 15:45:26 +0800 Subject: [PATCH 04/15] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=8F=8ARPC=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/TestController.php | 87 ++++++++++++++++++++ app/JsonRpc/UserExternalServiceInterface.php | 8 ++ 2 files changed, 95 insertions(+) create mode 100644 app/Controller/TestController.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php new file mode 100644 index 0000000..021cd3d --- /dev/null +++ b/app/Controller/TestController.php @@ -0,0 +1,87 @@ +request->input('page', 1); + $perPage = (int) $this->request->input('per_page', 2); + + // 这里根据 $currentPage 和 $perPage 进行数据查询,以下使用 Collection 代替 + $collection = new Collection([ + ['id' => 1, 'name' => 'Tom'], + ['id' => 2, 'name' => 'Sam'], + ['id' => 3, 'name' => 'Tim'], + ['id' => 4, 'name' => 'Joe'], + ]); + + $users = array_values($collection->forPage($currentPage, $perPage)->toArray()); + + return new Paginator($users, $perPage, $currentPage); + } + + /** + * RPC调用示例 + * + * @return array + */ + public function user_info() + { + return $this->getServiceResult($this->userService->getUserInfo()); + } +} \ No newline at end of file diff --git a/app/JsonRpc/UserExternalServiceInterface.php b/app/JsonRpc/UserExternalServiceInterface.php index a38371e..d582f86 100644 --- a/app/JsonRpc/UserExternalServiceInterface.php +++ b/app/JsonRpc/UserExternalServiceInterface.php @@ -4,6 +4,14 @@ namespace App\JsonRpc; interface UserExternalServiceInterface { + /** + * 获取用户信息 + * + * @param string $name + * @return array + */ + public function getUserInfo(string $name = 'test') : array; + /** * 通过微信授权新建用户 * From 3b327a585a1d05f5b2ac9b88a95d3f1e87362576 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Fri, 11 Nov 2022 16:54:07 +0800 Subject: [PATCH 05/15] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=AB=AF=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/autoload/server.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/autoload/server.php b/config/autoload/server.php index 0d82114..e2b0858 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -21,7 +21,7 @@ return [ 'name' => 'http', 'type' => Server::SERVER_HTTP, 'host' => '0.0.0.0', - 'port' => 9901, + 'port' => 8401, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'], @@ -31,7 +31,7 @@ return [ 'name' => 'jsonrpc-http', 'type' => Server::SERVER_HTTP, 'host' => '0.0.0.0', - 'port' => 9902, + 'port' => 8402, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'], From 1ff1dceab75ef14ff6b595c782c380bab0f36ee8 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Fri, 11 Nov 2022 17:40:27 +0800 Subject: [PATCH 06/15] =?UTF-8?q?=E6=9B=B4=E6=94=B9dockerfile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index c9d0f87..67d71da 100644 --- a/Dockerfile +++ b/Dockerfile @@ -49,6 +49,6 @@ WORKDIR /opt/www COPY . /opt/www RUN composer install --no-dev -o && php bin/hyperf.php -EXPOSE 9901 +EXPOSE 8401 ENTRYPOINT ["php", "/opt/www/bin/hyperf.php", "start"] From 144caadd3fa86fd905fc0a692930005fa6b9c1b2 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Mon, 14 Nov 2022 14:17:01 +0800 Subject: [PATCH 07/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=85=AC=E5=85=B1=E7=B1=BB=E7=9A=84=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Helper/Curl.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/app/Helper/Curl.php b/app/Helper/Curl.php index 309cac1..43d97ca 100644 --- a/app/Helper/Curl.php +++ b/app/Helper/Curl.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Helper; +use App\Exception\BusinessException; use GuzzleHttp\Client; use Hyperf\Guzzle\HandlerStackFactory; @@ -35,7 +36,6 @@ class Curl * @param string $url * @param array $headers * @return array - * @throws \GuzzleHttp\Exception\GuzzleException */ public static function get(string $url, array $headers = []) : array { @@ -46,7 +46,11 @@ class Curl $options['headers'] = $headers; } - $response = $client->get($url, $options); + try { + $response = $client->get($url, $options); + } catch (\Throwable $throwable) { + throw new BusinessException($throwable->getCode(), $throwable->getMessage()); + } if ($response->getStatusCode() === 200) { return json_decode($response->getBody()->getContents(), true); @@ -62,7 +66,6 @@ class Curl * @param array $data * @param array $headers * @return array - * @throws \GuzzleHttp\Exception\GuzzleException */ public static function post(string $url, array $data = [], array $headers = []) : array { @@ -73,7 +76,11 @@ class Curl $options['headers'] = $headers; } - $response = $client->post($url, $options); + try { + $response = $client->post($url, $options); + } catch (\Throwable $throwable) { + throw new BusinessException($throwable->getCode(), $throwable->getMessage()); + } if ($response->getStatusCode() === 200) { return json_decode($response->getBody()->getContents(), true); From 0b6f55b429d3766de579b1ccef1febe60e916d39 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Tue, 15 Nov 2022 16:33:33 +0800 Subject: [PATCH 08/15] =?UTF-8?q?=E5=AE=8C=E5=96=84RPC=E6=89=8B=E5=8A=A8?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=B6=88=E8=B4=B9=E8=80=85=E7=B1=BB=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=97=AE=E9=A2=98=E5=8F=8D=E9=A6=88=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PunchCard/User/UserController.php | 71 +++++++++++++++++++ app/Controller/TestController.php | 10 --- ...PunchCardSystemExternalServiceConsumer.php | 26 +++++++ ...unchCardSystemExternalServiceInterface.php | 16 +++++ app/JsonRpc/UserExternalServiceInterface.php | 5 +- app/Model/Model.php | 5 +- config/autoload/dependencies.php | 1 + config/autoload/services.php | 1 + 8 files changed, 119 insertions(+), 16 deletions(-) create mode 100644 app/Controller/PunchCard/User/UserController.php create mode 100644 app/JsonRpc/PunchCardSystemExternalServiceConsumer.php create mode 100644 app/JsonRpc/PunchCardSystemExternalServiceInterface.php diff --git a/app/Controller/PunchCard/User/UserController.php b/app/Controller/PunchCard/User/UserController.php new file mode 100644 index 0000000..9c41627 --- /dev/null +++ b/app/Controller/PunchCard/User/UserController.php @@ -0,0 +1,71 @@ +request->input('openid', ''); + return $this->getServiceResult($this->userExternalService->getUserInfo($openid, [ + 'user_name', + 'user_phone', + ])); + } + + /** + * 保存个人资料 + * + * @return void + */ + #[PostMapping(path: "user/save_information")] + public function saveInformation() : void + { + $phone = $this->request->input('phone', ''); + // TODO 逻辑完善 + } + + /** + * 保存问题反馈 + * + * @return array + */ + #[PostMapping(path: "user/save_feedback")] + public function saveFeedback() : array + { + return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request)); + } +} diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 021cd3d..674b454 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -74,14 +74,4 @@ class TestController extends BaseController return new Paginator($users, $perPage, $currentPage); } - - /** - * RPC调用示例 - * - * @return array - */ - public function user_info() - { - return $this->getServiceResult($this->userService->getUserInfo()); - } } \ No newline at end of file diff --git a/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php new file mode 100644 index 0000000..913e4b1 --- /dev/null +++ b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php @@ -0,0 +1,26 @@ +__request(__FUNCTION__, $request->all()); + } +} \ No newline at end of file diff --git a/app/JsonRpc/PunchCardSystemExternalServiceInterface.php b/app/JsonRpc/PunchCardSystemExternalServiceInterface.php new file mode 100644 index 0000000..ce993cc --- /dev/null +++ b/app/JsonRpc/PunchCardSystemExternalServiceInterface.php @@ -0,0 +1,16 @@ + JsonRpcPoolTransporter::class, + App\JsonRpc\PunchCardSystemExternalServiceInterface::class => App\JsonRpc\PunchCardSystemExternalServiceConsumer::class, ]; diff --git a/config/autoload/services.php b/config/autoload/services.php index a7df251..39c28f4 100644 --- a/config/autoload/services.php +++ b/config/autoload/services.php @@ -19,6 +19,7 @@ return [ // 这里示例自动创建代理消费者类的配置形式,顾存在 name 和 service 两个配置项,这里的做法不是唯一的,仅说明可以通过 PHP 代码来生成配置 $services = [ 'UserExternalService' => App\JsonRpc\UserExternalServiceInterface::class, + 'PunchCardSystemExternalService' => '' ]; foreach ($services as $name => $interface) { $consumers[] = [ From e6266edc0775bf0d175f65c6f45bb03e56420c1a Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Wed, 16 Nov 2022 11:21:53 +0800 Subject: [PATCH 09/15] =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=8A=A0=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Model/Model.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/Model/Model.php b/app/Model/Model.php index fe03061..fc074c3 100644 --- a/app/Model/Model.php +++ b/app/Model/Model.php @@ -12,7 +12,10 @@ declare(strict_types=1); namespace App\Model; use Hyperf\DbConnection\Model\Model as BaseModel; +use Hyperf\ModelCache\Cacheable; +use Hyperf\ModelCache\CacheableInterface; -abstract class Model extends BaseModel +abstract class Model extends BaseModel implements CacheableInterface { + use Cacheable; } From fe656375b41f5d23bb84c57bd8369674215f401e Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Wed, 16 Nov 2022 15:41:43 +0800 Subject: [PATCH 10/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E4=B8=AD=E5=BF=83=E7=B4=A7=E6=80=A5=E8=81=94=E7=B3=BB=E4=BA=BA?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PunchCard/User/UserController.php | 22 +++++++ app/JsonRpc/UserExternalServiceConsumer.php | 59 +++++++++++++++++++ app/JsonRpc/UserExternalServiceInterface.php | 17 ++++++ config/autoload/dependencies.php | 1 + config/autoload/services.php | 2 +- 5 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 app/JsonRpc/UserExternalServiceConsumer.php diff --git a/app/Controller/PunchCard/User/UserController.php b/app/Controller/PunchCard/User/UserController.php index 9c41627..cbf85af 100644 --- a/app/Controller/PunchCard/User/UserController.php +++ b/app/Controller/PunchCard/User/UserController.php @@ -68,4 +68,26 @@ class UserController extends BaseController { return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request)); } + + /** + * 获取紧急联系人关系列表 + * + * @return array + */ + #[GetMapping(path: "user/emergency_contact_kinship")] + public function getEmergencyContactKinshipList() : array + { + return $this->getServiceResult($this->userExternalService->getEmergencyContactKinshipList()); + } + + /** + * 保存紧急联系人 + * + * @return array + */ + #[PostMapping(path: "user/add_emergency_contact")] + public function addEmergencyContact() : array + { + return $this->getServiceResult($this->userExternalService->addEmergencyContact($this->request)); + } } diff --git a/app/JsonRpc/UserExternalServiceConsumer.php b/app/JsonRpc/UserExternalServiceConsumer.php new file mode 100644 index 0000000..5c96fa1 --- /dev/null +++ b/app/JsonRpc/UserExternalServiceConsumer.php @@ -0,0 +1,59 @@ +__request(__FUNCTION__, compact('openid', 'field')); + } + + /** + * 通过微信授权新建用户 + * + * @param string $openid + * @return array + */ + public function wechatNewUser(string $openid) : array + { + return $this->__request(__FUNCTION__, compact('openid')); + } + + /** + * 获取紧急联系人关系列表 + * + * @return array + */ + public function getEmergencyContactKinshipList() : array + { + return $this->__request(__FUNCTION__, []); + } + + /** + * 保存紧急联系人 + * + * @param RequestInterface $request + * @return array + */ + public function addEmergencyContact(RequestInterface $request) : array + { + return $this->__request(__FUNCTION__, $request->all()); + } +} \ No newline at end of file diff --git a/app/JsonRpc/UserExternalServiceInterface.php b/app/JsonRpc/UserExternalServiceInterface.php index 928966e..1ba1e1e 100644 --- a/app/JsonRpc/UserExternalServiceInterface.php +++ b/app/JsonRpc/UserExternalServiceInterface.php @@ -2,6 +2,8 @@ namespace App\JsonRpc; +use Hyperf\HttpServer\Contract\RequestInterface; + interface UserExternalServiceInterface { /** @@ -20,4 +22,19 @@ interface UserExternalServiceInterface * @return array */ public function wechatNewUser(string $openid) : array; + + /** + * 获取紧急联系人关系列表 + * + * @return array + */ + public function getEmergencyContactKinshipList() : array; + + /** + * 保存紧急联系人 + * + * @param RequestInterface $request + * @return array + */ + public function addEmergencyContact(RequestInterface $request) : array; } \ No newline at end of file diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 6699c29..e1b5ebf 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -14,5 +14,6 @@ use Hyperf\JsonRpc\JsonRpcTransporter; return [ JsonRpcTransporter::class => JsonRpcPoolTransporter::class, + App\JsonRpc\UserExternalServiceInterface::class => App\JsonRpc\UserExternalServiceConsumer::class, App\JsonRpc\PunchCardSystemExternalServiceInterface::class => App\JsonRpc\PunchCardSystemExternalServiceConsumer::class, ]; diff --git a/config/autoload/services.php b/config/autoload/services.php index 39c28f4..e54b759 100644 --- a/config/autoload/services.php +++ b/config/autoload/services.php @@ -18,7 +18,7 @@ return [ $consumers = []; // 这里示例自动创建代理消费者类的配置形式,顾存在 name 和 service 两个配置项,这里的做法不是唯一的,仅说明可以通过 PHP 代码来生成配置 $services = [ - 'UserExternalService' => App\JsonRpc\UserExternalServiceInterface::class, + 'UserExternalService' => '', 'PunchCardSystemExternalService' => '' ]; foreach ($services as $name => $interface) { From 6b2eb3cff8847f98c70640b4885340aed1b84dc2 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Wed, 16 Nov 2022 15:57:58 +0800 Subject: [PATCH 11/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E5=8F=8D=E9=A6=88=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PunchCard/User/UserController.php | 11 +++++++++++ .../PunchCardSystemExternalServiceConsumer.php | 10 ++++++++++ .../PunchCardSystemExternalServiceInterface.php | 7 +++++++ 3 files changed, 28 insertions(+) diff --git a/app/Controller/PunchCard/User/UserController.php b/app/Controller/PunchCard/User/UserController.php index cbf85af..5606f02 100644 --- a/app/Controller/PunchCard/User/UserController.php +++ b/app/Controller/PunchCard/User/UserController.php @@ -58,6 +58,17 @@ class UserController extends BaseController // TODO 逻辑完善 } + /** + * 获取问题反馈类型列表 + * + * @return array + */ + #[GetMapping(path: "user/feedback_type")] + public function getFeedbackTypeList() : array + { + return $this->getServiceResult($this->punchCardSystemExternalService->getFeedbackTypeList()); + } + /** * 保存问题反馈 * diff --git a/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php index 913e4b1..b80a063 100644 --- a/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php +++ b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php @@ -13,6 +13,16 @@ class PunchCardSystemExternalServiceConsumer extends AbstractServiceClient imple */ protected $serviceName = 'PunchCardSystemExternalService'; + /** + * 获取问题反馈类型列表 + * + * @return array + */ + public function getFeedbackTypeList() : array + { + return $this->__request(__FUNCTION__, []); + } + /** * 保存问题反馈 * diff --git a/app/JsonRpc/PunchCardSystemExternalServiceInterface.php b/app/JsonRpc/PunchCardSystemExternalServiceInterface.php index ce993cc..8657788 100644 --- a/app/JsonRpc/PunchCardSystemExternalServiceInterface.php +++ b/app/JsonRpc/PunchCardSystemExternalServiceInterface.php @@ -6,6 +6,13 @@ use Hyperf\HttpServer\Contract\RequestInterface; interface PunchCardSystemExternalServiceInterface { + /** + * 获取问题反馈类型列表 + * + * @return array + */ + public function getFeedbackTypeList() : array; + /** * 保存问题反馈 * From 4ec5166f50e3033baf50f7695ae6e1f26f136b6d Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Thu, 17 Nov 2022 10:14:12 +0800 Subject: [PATCH 12/15] =?UTF-8?q?=E5=AE=8C=E5=96=84JWT=E8=AE=A4=E8=AF=81?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 2 +- app/Constants/Wechat/AuthErrorCode.php | 7 +- app/Controller/AuthController.php | 11 ++ .../PunchCard/User/UserController.php | 4 +- .../WechatAuthController.php} | 28 ++- .../WechatAuthService.php} | 57 +++++- composer.json | 3 +- composer.lock | 184 +++++++++++++++++- config/autoload/jwt.php | 93 +++++++++ 9 files changed, 376 insertions(+), 13 deletions(-) create mode 100644 app/Controller/AuthController.php rename app/Controller/PunchCard/{Wechat/AuthController.php => User/WechatAuthController.php} (53%) rename app/Service/{Wechat/AuthService.php => User/WechatAuthService.php} (51%) create mode 100644 config/autoload/jwt.php diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index 015ae77..f59d55f 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -25,5 +25,5 @@ class ErrorCode extends AbstractConstants /** * @Message("Something went wrong!") */ - public const COMMON_ERROR = 1000000; + public const COMMON_ERROR = 1200000; } diff --git a/app/Constants/Wechat/AuthErrorCode.php b/app/Constants/Wechat/AuthErrorCode.php index 0df037d..9455c0f 100644 --- a/app/Constants/Wechat/AuthErrorCode.php +++ b/app/Constants/Wechat/AuthErrorCode.php @@ -13,5 +13,10 @@ class AuthErrorCode extends AbstractConstants /** * @Message("请传入微信Code") */ - public const CODE_EMPTY_ERROR = 2000001; + public const CODE_EMPTY_ERROR = 1200001; + + /** + * @Message("授权失败") + */ + public const CODE_TO_AUTH_FAIL = 1200002; } \ No newline at end of file diff --git a/app/Controller/AuthController.php b/app/Controller/AuthController.php new file mode 100644 index 0000000..8f04c28 --- /dev/null +++ b/app/Controller/AuthController.php @@ -0,0 +1,11 @@ +service->codeToOpenID($code); } + + /** + * 刷新token + * + * @return array + */ + #[Middleware(JWTAuthDefaultSceneMiddleware::class)] + #[GetMapping(path: "auth/refresh_token")] + public function refreshToken() : array + { + return $this->service->refreshToken(); + } } diff --git a/app/Service/Wechat/AuthService.php b/app/Service/User/WechatAuthService.php similarity index 51% rename from app/Service/Wechat/AuthService.php rename to app/Service/User/WechatAuthService.php index 3bd2605..1c5fafc 100644 --- a/app/Service/Wechat/AuthService.php +++ b/app/Service/User/WechatAuthService.php @@ -1,17 +1,20 @@ $result['data']['openid']]; + if (empty($res['data']['user'])) { + throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); + } + + $user_data = [ + 'user_id' => $res['data']['user']['user_id'], + 'nickname' => $res['data']['user']['user_nickname'], + 'openid' => $res['data']['user']['user_openid'] + ]; + + try { + $token = $this->jwt->getToken('default', $user_data); + } catch (InvalidArgumentException) { + // TODO 记录日志 + throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); + } + + return [ + 'token' => $token->toString(), + 'exp' => $this->jwt->getTTL($token->toString()) + ]; + } + + /** + * 刷新token + * + * @return array + */ + public function refreshToken() : array + { + try { + $token = $this->jwt->refreshToken(); + } catch (InvalidArgumentException) { + // TODO 记录日志 + throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); + } + + return [ + 'token' => $token->toString(), + 'exp' => $this->jwt->getTTL($token->toString()) + ]; } } \ No newline at end of file diff --git a/composer.json b/composer.json index c173c71..3cb3b87 100644 --- a/composer.json +++ b/composer.json @@ -34,7 +34,8 @@ "hyperf/rpc-client": "~2.2.0", "hyperf/rpc-server": "~2.2.0", "hyperf/service-governance-consul": "~2.2.0", - "hyperf/validation": "^2.2" + "hyperf/validation": "^2.2", + "phper666/jwt-auth": "~4.0.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.0", diff --git a/composer.lock b/composer.lock index 86116f6..847f76a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "7cc40bd39d6d590a4e06bfb1d56c0abb", + "content-hash": "7f8915491bc01099466689096453ac63", "packages": [ { "name": "doctrine/annotations", @@ -2515,6 +2515,101 @@ ], "time": "2022-10-10T19:10:24+00:00" }, + { + "name": "lcobucci/clock", + "version": "2.2.0", + "dist": { + "type": "zip", + "url": "https://mirrors.cloud.tencent.com/repository/composer/lcobucci/clock/2.2.0/lcobucci-clock-2.2.0.zip", + "reference": "fb533e093fd61321bfcbac08b131ce805fe183d3", + "shasum": "" + }, + "require": { + "php": "^8.0", + "stella-maris/clock": "^0.1.4" + }, + "require-dev": { + "infection/infection": "^0.26", + "lcobucci/coding-standard": "^8.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-deprecation-rules": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/phpunit": "^9.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Lcobucci\\Clock\\": "src" + } + }, + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Luís Cobucci", + "email": "lcobucci@gmail.com" + } + ], + "description": "Yet another clock abstraction", + "time": "2022-04-19T19:34:17+00:00" + }, + { + "name": "lcobucci/jwt", + "version": "4.1.5", + "dist": { + "type": "zip", + "url": "https://mirrors.cloud.tencent.com/repository/composer/lcobucci/jwt/4.1.5/lcobucci-jwt-4.1.5.zip", + "reference": "fe2d89f2eaa7087af4aa166c6f480ef04e000582", + "shasum": "" + }, + "require": { + "ext-hash": "*", + "ext-json": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "ext-sodium": "*", + "lcobucci/clock": "^2.0", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "infection/infection": "^0.21", + "lcobucci/coding-standard": "^6.0", + "mikey179/vfsstream": "^1.6.7", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-deprecation-rules": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/php-invoker": "^3.1", + "phpunit/phpunit": "^9.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Lcobucci\\JWT\\": "src" + } + }, + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Luís Cobucci", + "email": "lcobucci@gmail.com", + "role": "Developer" + } + ], + "description": "A simple library to work with JSON Web Token and JSON Web Signature", + "keywords": [ + "JWS", + "jwt" + ], + "time": "2021-09-28T19:34:56+00:00" + }, { "name": "markrogoyski/math-php", "version": "v2.6.0", @@ -3020,6 +3115,56 @@ ], "time": "2020-10-12T12:39:22+00:00" }, + { + "name": "phper666/jwt-auth", + "version": "v4.0.7", + "dist": { + "type": "zip", + "url": "https://mirrors.cloud.tencent.com/repository/composer/phper666/jwt-auth/v4.0.7/phper666-jwt-auth-v4.0.7.zip", + "reference": "c42e1ef968d300e7e74e449e5e93cda7d22de33f", + "shasum": "" + }, + "require": { + "ext-swoole": ">=4.4", + "lcobucci/jwt": "4.1.5", + "nesbot/carbon": "^1.0 || ^2.0", + "php": ">=7.4" + }, + "suggest": { + "hyperf/cache": "required hyperf/cache ~2.2.0", + "hyperf/command": "required hyperf/command ~2.2.0", + "hyperf/config": "required hyperf/config ~2.2.0", + "hyperf/di": "required hyperf/di ~2.2.0" + }, + "type": "library", + "extra": { + "hyperf": { + "config": "Phper666\\JWTAuth\\ConfigProvider" + } + }, + "autoload": { + "psr-4": { + "Phper666\\JWTAuth\\": "src/" + } + }, + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Li Yuzhao", + "email": "562405704@qq.com", + "homepage": "https://github.com/phper666/jwt-auth", + "role": "Developer" + } + ], + "description": "jwt-auth Component", + "keywords": [ + "hyperf", + "php" + ], + "time": "2022-04-19T11:54:50+00:00" + }, { "name": "phpoption/phpoption", "version": "1.9.0", @@ -3628,6 +3773,43 @@ "description": "A polyfill for getallheaders.", "time": "2019-03-08T08:55:37+00:00" }, + { + "name": "stella-maris/clock", + "version": "0.1.6", + "dist": { + "type": "zip", + "url": "https://mirrors.cloud.tencent.com/repository/composer/stella-maris/clock/0.1.6/stella-maris-clock-0.1.6.zip", + "reference": "a94228dac03c9a8411198ce8c8dacbbe99c930c3", + "shasum": "" + }, + "require": { + "php": "^7.0|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "StellaMaris\\Clock\\": "src" + } + }, + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Andreas Heigl", + "role": "Maintainer" + } + ], + "description": "A pre-release of the proposed PSR-20 Clock-Interface", + "homepage": "https://gitlab.com/stella-maris/clock", + "keywords": [ + "clock", + "datetime", + "point in time", + "psr20" + ], + "time": "2022-09-27T15:03:11+00:00" + }, { "name": "symfony/console", "version": "v5.4.11", diff --git a/config/autoload/jwt.php b/config/autoload/jwt.php new file mode 100644 index 0000000..eb21313 --- /dev/null +++ b/config/autoload/jwt.php @@ -0,0 +1,93 @@ + [ + ["**", "/**"], + ], + + 'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录 + + /** + * 单点登录自定义数据中必须存在uid的键值,这个key你可以自行定义,只要自定义数据中存在该键即可 + */ + 'sso_key' => 'user_id', + + /** + * 只能用于Hmac包下的加密非对称算法,其它的都会使用公私钥 + */ + 'secret' => env('JWT_SECRET', 'juzhongGroup'), + + /** + * JWT 权限keys + * 对称算法: HS256, HS384 & HS512 使用 `JWT_SECRET`. + * 非对称算法: RS256, RS384 & RS512 / ES256, ES384 & ES512 使用下面的公钥私钥,需要自己去生成. + */ + 'keys' => [ + 'public' => env('JWT_PUBLIC_KEY'), // 公钥,例如:'file:///path/to/public/key' + 'private' => env('JWT_PRIVATE_KEY'), // 私钥,例如:'file:///path/to/private/key' + + /** + * 你的私钥的密码。不需要密码可以不用设置 + */ + 'passphrase' => env('JWT_PASSPHRASE'), + ], + + 'ttl' => env('JWT_TTL', 7200), // token过期时间,单位为秒 + + /** + * 支持的对称算法:HS256、HS384、HS512 + * 支持的非对称算法:RS256、RS384、RS512、ES256、ES384、ES512 + */ + 'alg' => env('JWT_ALG', 'HS256'), // jwt的hearder加密算法 + + /** + * jwt使用到的缓存前缀 + * 建议使用独立的redis做缓存,这样比较好做分布式 + */ + 'cache_prefix' => 'juzhong:jwt', + + /** + * 是否开启黑名单,单点登录和多点登录的注销、刷新使原token失效,必须要开启黑名单,目前黑名单缓存只支持hyperf缓存驱动 + */ + 'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true), + + /** + * 黑名单的宽限时间 单位为:秒,注意:如果使用单点登录,该宽限时间无效 + */ + 'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0), + + /** + * 签发者 + */ + 'issued_by' => 'phper666/jwt', + + /** + * 区分不同场景的token,比如你一个项目可能会有多种类型的应用接口鉴权,下面自行定义,我只是举例子 + * 下面的配置会自动覆盖根配置,比如application1会里面的数据会覆盖掉根数据 + * 下面的scene会和根数据合并 + * scene必须存在一个default + * 什么叫根数据,这个配置的一维数组,除了scene都叫根配置 + */ + 'scene' => [ + 'default' => [ + 'secret' => 'juzhongGroup', // 非对称加密使用字符串,请使用自己加密的字符串 + 'login_type' => 'mpop', // 登录方式,sso为单点登录,mpop为多点登录 + 'ttl' => 7200, // token过期时间,单位为秒 + ] + ] +]; From 463487b9399354e00ae2715bf3c611cbefe512a5 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Thu, 17 Nov 2022 11:22:55 +0800 Subject: [PATCH 13/15] =?UTF-8?q?=E7=BB=A7=E7=BB=AD=E5=AE=8C=E5=96=84JWT?= =?UTF-8?q?=E8=AE=A4=E8=AF=81=E9=80=BB=E8=BE=91=EF=BC=8C=E5=8F=8A=E8=B0=83?= =?UTF-8?q?=E6=95=B4=E5=BC=82=E5=B8=B8=E8=BF=94=E5=9B=9E=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/AuthController.php | 11 ----------- app/Controller/PunchCard/User/UserController.php | 4 ++-- app/Exception/Handler/AppExceptionHandler.php | 12 +++++++++--- config/autoload/jwt.php | 3 ++- config/autoload/middlewares.php | 1 + 5 files changed, 14 insertions(+), 17 deletions(-) delete mode 100644 app/Controller/AuthController.php diff --git a/app/Controller/AuthController.php b/app/Controller/AuthController.php deleted file mode 100644 index 8f04c28..0000000 --- a/app/Controller/AuthController.php +++ /dev/null @@ -1,11 +0,0 @@ -logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile())); - $this->logger->error($throwable->getTraceAsString()); - return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.')); + $message = $throwable->getMessage(); + $error = explode('|', $message, 2); + $code = $error[1] ?? $throwable->getCode() ?: ErrorCode::COMMON_ERROR; + $data = Result::error($code, $error[0]); + $responseStr = json_encode($data, JSON_UNESCAPED_UNICODE); + + return $response->withHeader('Content-Type', 'application/json')->withBody(new SwooleStream($responseStr)); } public function isValid(Throwable $throwable): bool diff --git a/config/autoload/jwt.php b/config/autoload/jwt.php index eb21313..52853bf 100644 --- a/config/autoload/jwt.php +++ b/config/autoload/jwt.php @@ -17,7 +17,8 @@ return [ * 正则写法:["**", "/api/{name:.+}"] 支持模块化不做jwt token的校验,例如:/api/login/login */ 'no_check_route' => [ - ["**", "/**"], +// ["**", "/**"], + ["**", "/kq/auth/code2OpenID"] ], 'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录 diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 49bdec2..b4ad4af 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,5 +11,6 @@ declare(strict_types=1); */ return [ 'http' => [ + Phper666\JWTAuth\Middleware\JWTAuthDefaultSceneMiddleware::class ], ]; From 779237afcda41aed38953062f3a4b5c2c27264d4 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Fri, 18 Nov 2022 16:56:20 +0800 Subject: [PATCH 14/15] =?UTF-8?q?=E5=AE=8C=E5=96=84JWT=E8=AE=A4=E8=AF=81?= =?UTF-8?q?=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PunchCard/User/UserController.php | 21 ++++++-- app/Controller/TestController.php | 27 ++++++++-- ...PunchCardSystemExternalServiceConsumer.php | 2 +- app/Middleware/AuthMiddleware.php | 53 +++++++++++++++++++ app/Service/User/WechatAuthService.php | 23 +++++--- config/autoload/jwt.php | 1 - config/autoload/middlewares.php | 1 - 7 files changed, 112 insertions(+), 16 deletions(-) create mode 100644 app/Middleware/AuthMiddleware.php diff --git a/app/Controller/PunchCard/User/UserController.php b/app/Controller/PunchCard/User/UserController.php index 5606f02..27127f9 100644 --- a/app/Controller/PunchCard/User/UserController.php +++ b/app/Controller/PunchCard/User/UserController.php @@ -7,11 +7,14 @@ namespace App\Controller\PunchCard\User; use App\Controller\BaseController; use App\JsonRpc\PunchCardSystemExternalServiceInterface; use App\JsonRpc\UserExternalServiceInterface; +use App\Middleware\AuthMiddleware; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\GetMapping; +use Hyperf\HttpServer\Annotation\Middleware; use Hyperf\HttpServer\Annotation\PostMapping; +#[Middleware(AuthMiddleware::class)] #[Controller(prefix: "kq")] class UserController extends BaseController { @@ -39,8 +42,8 @@ class UserController extends BaseController #[GetMapping(path: "user/information")] public function information() : array { - $openid = $this->request->input('openid', ''); - return $this->getServiceResult($this->userExternalService->getUserInfo($openid, [ + $user = $this->request->getAttribute('AuthUser'); + return $this->getServiceResult($this->userExternalService->getUserInfo($user['openid'], [ 'user_name', 'user_phone', ])); @@ -77,7 +80,8 @@ class UserController extends BaseController #[PostMapping(path: "user/save_feedback")] public function saveFeedback() : array { - return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request)); + $user = $this->request->getAttribute('AuthUser'); + return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request, $user['user_id'])); } /** @@ -101,4 +105,15 @@ class UserController extends BaseController { return $this->getServiceResult($this->userExternalService->addEmergencyContact($this->request)); } + + /** + * 测试打印JWT认证信息 + * + * @return array + */ + #[GetMapping(path: "user/test")] + public function test() : array + { + return $this->request->getAttribute('AuthUser'); + } } diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 674b454..cca43c2 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -6,6 +6,7 @@ namespace App\Controller; use App\Exception\BusinessException; use App\JsonRpc\UserExternalServiceInterface; +use App\Service\User\WechatAuthService; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\AutoController; use Hyperf\Utils\Collection; @@ -28,7 +29,7 @@ class TestController extends BaseController * * @return array */ - public function index() + public function index() : array { $data['user_id'] = 'test'; return $data; @@ -39,7 +40,7 @@ class TestController extends BaseController * * @return void */ - public function empty() + public function empty() : void {} /** @@ -47,7 +48,7 @@ class TestController extends BaseController * * @return mixed */ - public function error() + public function error(): mixed { throw new BusinessException(500, 'error'); } @@ -57,7 +58,7 @@ class TestController extends BaseController * * @return Paginator */ - public function page() + public function page() : Paginator { $currentPage = (int) $this->request->input('page', 1); $perPage = (int) $this->request->input('per_page', 2); @@ -74,4 +75,22 @@ class TestController extends BaseController return new Paginator($users, $perPage, $currentPage); } + + /** + * 获取token(用于测试) + * + * @param WechatAuthService $wechatAuthService + * @return array + */ + public function token(WechatAuthService $wechatAuthService) : array + { + $openid = $this->request->input('openid', '1111111'); + $user = $this->getServiceResult($this->userService->getUserInfo($openid, ['user_id', 'user_nickname'])); + + if (!empty($user)) { + return $wechatAuthService->getToken($user['user_id'], $user['user_nickname'], $openid); + } + + return []; + } } \ No newline at end of file diff --git a/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php index b80a063..9195be0 100644 --- a/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php +++ b/app/JsonRpc/PunchCardSystemExternalServiceConsumer.php @@ -31,6 +31,6 @@ class PunchCardSystemExternalServiceConsumer extends AbstractServiceClient imple */ public function saveFeedback(RequestInterface $request) : array { - return $this->__request(__FUNCTION__, $request->all()); + return $this->__request(__FUNCTION__, [...$request->all(), ...['user_id' => $request->getAttribute('AuthUser')['user_id']]]); } } \ No newline at end of file diff --git a/app/Middleware/AuthMiddleware.php b/app/Middleware/AuthMiddleware.php new file mode 100644 index 0000000..2c56bad --- /dev/null +++ b/app/Middleware/AuthMiddleware.php @@ -0,0 +1,53 @@ +getHeaderLine('Authorization') ?? ''; + if ($token === "") { + throw new JWTException('Missing token', ErrorCode::COMMON_ERROR); + } + + $token = JWTUtil::handleToken($token); + if ($token !== false && $this->jwt->verifyTokenAndScene('default', $token)) { + // 封装认证用户信息 + $request = $request->withAttribute('AuthUser', JWTUtil::getParserData($request)); + Context::set(ServerRequestInterface::class, $request); + + return $handler->handle($request); + } + + throw new TokenValidException('Token authentication does not pass', ErrorCode::COMMON_ERROR); + } +} \ No newline at end of file diff --git a/app/Service/User/WechatAuthService.php b/app/Service/User/WechatAuthService.php index 1c5fafc..439fb3b 100644 --- a/app/Service/User/WechatAuthService.php +++ b/app/Service/User/WechatAuthService.php @@ -81,14 +81,25 @@ class WechatAuthService throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); } - $user_data = [ - 'user_id' => $res['data']['user']['user_id'], - 'nickname' => $res['data']['user']['user_nickname'], - 'openid' => $res['data']['user']['user_openid'] - ]; + return $this->getToken($res['data']['user']['user_id'], $res['data']['user']['user_nickname'], $res['data']['user']['user_openid']); + } + /** + * 获取JWT认证token + * + * @param int $user_id + * @param string $nickname + * @param string $openid + * @return array + */ + public function getToken(int $user_id, string $nickname, string $openid) + { try { - $token = $this->jwt->getToken('default', $user_data); + $token = $this->jwt->getToken('default', [ + 'user_id' => $user_id, + 'nickname' => $nickname, + 'openid' => $openid + ]); } catch (InvalidArgumentException) { // TODO 记录日志 throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL); diff --git a/config/autoload/jwt.php b/config/autoload/jwt.php index 52853bf..037292a 100644 --- a/config/autoload/jwt.php +++ b/config/autoload/jwt.php @@ -18,7 +18,6 @@ return [ */ 'no_check_route' => [ // ["**", "/**"], - ["**", "/kq/auth/code2OpenID"] ], 'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录 diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index b4ad4af..49bdec2 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,6 +11,5 @@ declare(strict_types=1); */ return [ 'http' => [ - Phper666\JWTAuth\Middleware\JWTAuthDefaultSceneMiddleware::class ], ]; From 5c203379d748b8893b2acc297353c640149490fe Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Fri, 18 Nov 2022 17:06:02 +0800 Subject: [PATCH 15/15] =?UTF-8?q?=E5=AE=8C=E5=96=84JWT=E8=AE=A4=E8=AF=81?= =?UTF-8?q?=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PunchCard/User/WechatAuthController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Controller/PunchCard/User/WechatAuthController.php b/app/Controller/PunchCard/User/WechatAuthController.php index 4b27208..c9e075e 100644 --- a/app/Controller/PunchCard/User/WechatAuthController.php +++ b/app/Controller/PunchCard/User/WechatAuthController.php @@ -7,6 +7,7 @@ namespace App\Controller\PunchCard\User; use App\Controller\BaseController; use App\Exception\BusinessException; use app\Constants\Wechat\AuthErrorCode; +use App\Middleware\AuthMiddleware; use App\Service\User\WechatAuthService; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; @@ -51,7 +52,7 @@ class WechatAuthController extends BaseController * * @return array */ - #[Middleware(JWTAuthDefaultSceneMiddleware::class)] + #[Middleware(AuthMiddleware::class)] #[GetMapping(path: "auth/refresh_token")] public function refreshToken() : array {