AuthTokenMiddleware.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. public function handle(Request $request, \Closure $next, bool $force = true)
  23. {
  24. $authInfo = null;
  25. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  26. if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  27. try {
  28. /** @var UserAuthServices $service */
  29. $service = app()->make(UserAuthServices::class);
  30. $authInfo = $service->parseToken($token);
  31. } catch (AuthException $e) {
  32. if ($force)
  33. return app('json')->make($e->getCode(), $e->getMessage());
  34. }
  35. if (!is_null($authInfo)) {
  36. $request->macro('user', function (string $key = null) use (&$authInfo) {
  37. if ($key) {
  38. return $authInfo['user'][$key] ?? '';
  39. }
  40. return $authInfo['user'];
  41. });
  42. $request->macro('tokenData', function () use (&$authInfo) {
  43. return $authInfo['tokenData'];
  44. });
  45. }
  46. $request->macro('isLogin', function () use (&$authInfo) {
  47. return !is_null($authInfo);
  48. });
  49. $request->macro('uid', function () use (&$authInfo) {
  50. return is_null($authInfo) ? 0 : (int)$authInfo['user']->uid;
  51. });
  52. return $next($request);
  53. }
  54. }