AuthTokenMiddleware.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace app\api\middleware;
  3. use app\models\merchant\MerchantMiniprogram;
  4. use app\models\user\User;
  5. use app\models\user\UserToken;
  6. use app\Request;
  7. use crmeb\exceptions\AuthException;
  8. use crmeb\interfaces\MiddlewareInterface;
  9. use crmeb\repositories\UserRepository;
  10. use think\db\exception\DataNotFoundException;
  11. use think\db\exception\ModelNotFoundException;
  12. use think\exception\DbException;
  13. class AuthTokenMiddleware implements MiddlewareInterface
  14. {
  15. public function handle(Request $request, \Closure $next, bool $force = true)
  16. {
  17. $authInfo = null;
  18. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  19. $app_id = strtolower(trim($request->header('App-id', '')));
  20. if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  21. try {
  22. $authInfo = UserRepository::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. if (!in_array($authInfo['user']->mer_id, [0, $request->mer_id()])) {
  29. if ($force)
  30. return app('json')->make(410000, '账号异常');
  31. }
  32. Request::macro('user', function () use (&$authInfo) {
  33. return $authInfo['user'];
  34. });
  35. Request::macro('tokenData', function () use (&$authInfo) {
  36. return $authInfo['tokenData'];
  37. });
  38. }
  39. Request::macro('isLogin', function () use (&$authInfo) {
  40. return !is_null($authInfo);
  41. });
  42. Request::macro('uid', function () use (&$authInfo) {
  43. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  44. });
  45. return $next($request);
  46. }
  47. }