AuthTokenMiddleware.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace app\http\middleware;
  3. use app\models\user\User;
  4. use app\models\user\UserToken;
  5. use app\Request;
  6. use crmeb\exceptions\AuthException;
  7. use crmeb\interfaces\MiddlewareInterface;
  8. use crmeb\repositories\UserRepository;
  9. use think\db\exception\DataNotFoundException;
  10. use think\db\exception\ModelNotFoundException;
  11. use think\exception\DbException;
  12. /**
  13. * token验证中间件
  14. * Class AuthTokenMiddleware
  15. * @package app\http\middleware
  16. */
  17. class AuthTokenMiddleware implements MiddlewareInterface
  18. {
  19. public function handle(Request $request, \Closure $next, bool $force = true)
  20. {
  21. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  22. $authInfo = null;
  23. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  24. if(!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  25. try {
  26. $authInfo = UserRepository::parseToken($token);
  27. } catch (AuthException $e) {
  28. if ($force)
  29. return app('json')->make($e->getCode(), $e->getMessage());
  30. }
  31. if (isset($authInfo['user']['status'])){
  32. if ($authInfo['user']['status'] == 0){
  33. return app('json')->fail('用户已被禁用');
  34. }
  35. }
  36. if (!is_null($authInfo)) {
  37. Request::macro('user', function () use (&$authInfo) {
  38. return $authInfo['user'];
  39. });
  40. Request::macro('tokenData', function () use (&$authInfo) {
  41. return $authInfo['tokenData'];
  42. });
  43. }
  44. Request::macro('isLogin', function () use (&$authInfo) {
  45. return !is_null($authInfo);
  46. });
  47. Request::macro('uid', function () use (&$authInfo) {
  48. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  49. });
  50. return $next($request);
  51. }
  52. }