AuthTokenMiddleware.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\api\middleware;
  12. use app\Request;
  13. use app\services\user\UserAuthServices;
  14. use crmeb\exceptions\AuthException;
  15. use crmeb\interfaces\MiddlewareInterface;
  16. /**
  17. * Class AuthTokenMiddleware
  18. * @package app\api\middleware
  19. */
  20. class AuthTokenMiddleware implements MiddlewareInterface
  21. {
  22. /**
  23. * @param Request $request
  24. * @param \Closure $next
  25. * @param bool $force
  26. * @return int|mixed|\think\Response
  27. * @throws \think\db\exception\DataNotFoundException
  28. * @throws \think\db\exception\DbException
  29. * @throws \think\db\exception\ModelNotFoundException
  30. * @author 吴汐
  31. * @email 442384644@qq.com
  32. * @date 2023/04/07
  33. */
  34. public function handle(Request $request, \Closure $next, bool $force = true)
  35. {
  36. $authInfo = null;
  37. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  38. if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  39. try {
  40. /** @var UserAuthServices $service */
  41. $service = app()->make(UserAuthServices::class);
  42. $authInfo = $service->parseToken($token);
  43. } catch (AuthException $e) {
  44. if ($force)
  45. return app('json')->make($e->getCode(), $e->getMessage());
  46. }
  47. if (!is_null($authInfo)) {
  48. $request->macro('user', function (string $key = null) use (&$authInfo) {
  49. if ($key) {
  50. return $authInfo['user'][$key] ?? '';
  51. }
  52. return $authInfo['user'];
  53. });
  54. $request->macro('tokenData', function () use (&$authInfo) {
  55. return $authInfo['tokenData'];
  56. });
  57. }
  58. $request->macro('isLogin', function () use (&$authInfo) {
  59. return !is_null($authInfo);
  60. });
  61. $request->macro('uid', function () use (&$authInfo) {
  62. return is_null($authInfo) ? 0 : (int)$authInfo['user']->uid;
  63. });
  64. return $next($request);
  65. }
  66. }