AuthTokenMiddleware.php 2.3 KB

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