AdminHandler.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\webscoket\handler;
  12. use app\common\repositories\system\admin\AdminRepository;
  13. use crmeb\services\JwtTokenService;
  14. use Firebase\JWT\ExpiredException;
  15. use Swoole\Server;
  16. use think\db\exception\DataNotFoundException;
  17. use think\db\exception\DbException;
  18. use think\db\exception\ModelNotFoundException;
  19. use Throwable;
  20. /**
  21. * Class Handler
  22. * @package app\webscoket
  23. * @author xaboy
  24. * @day 2020-04-29
  25. */
  26. class AdminHandler
  27. {
  28. /**
  29. * @var Server
  30. */
  31. protected $server;
  32. /**
  33. * AdminHandler constructor.
  34. * @param Server $server
  35. */
  36. public function __construct(Server $server)
  37. {
  38. $this->server = $server;
  39. }
  40. /**
  41. * @param array $data
  42. * @return mixed
  43. * @author xaboy
  44. * @day 2020-05-06
  45. */
  46. public function test(array $data)
  47. {
  48. return app('json')->success($data);
  49. }
  50. /**
  51. * @param array $data
  52. * @return mixed
  53. * @throws DataNotFoundException
  54. * @throws DbException
  55. * @throws ModelNotFoundException
  56. * @author xaboy
  57. * @day 2020-05-06
  58. */
  59. public function login(array $data)
  60. {
  61. $token = $data['token'] ?? '';
  62. if (!$token) return app('json')->fail('token 无效');
  63. /**
  64. * @var AdminRepository $repository
  65. */
  66. $repository = app()->make(AdminRepository::class);
  67. $service = new JwtTokenService();
  68. try {
  69. $payload = $service->parseToken($token);
  70. } catch (ExpiredException $e) {
  71. $repository->checkToken($token);
  72. $payload = $service->decode($token);
  73. } catch (Throwable $e) {//Token 过期
  74. return app('json')->fail('token 已过期');
  75. }
  76. if ('admin' != $payload->jti[1])
  77. return app('json')->fail('无效的 token');
  78. $admin = $repository->get($payload->jti[0]);
  79. if (!$admin)
  80. return app('json')->fail('账号不存在');
  81. if (!$admin['status'])
  82. return app('json')->fail('账号已被禁用');
  83. return app('json')->success(['uid' => $admin->admin_id, 'data' => $admin->toArray()]);
  84. }
  85. }