You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthTokenMiddleware.php 1.7KB

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