ApiCheckToken.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Niucloud-admin 企业快速开发的saas管理平台
  4. // +----------------------------------------------------------------------
  5. // | 官方网址:https://www.niucloud.com
  6. // +----------------------------------------------------------------------
  7. // | niucloud团队 版权所有 开源版本可自由商用
  8. // +----------------------------------------------------------------------
  9. // | Author: Niucloud Team
  10. // +----------------------------------------------------------------------
  11. namespace app\api\middleware;
  12. use app\dict\sys\AppTypeDict;
  13. use app\Request;
  14. use app\service\api\login\AuthService;
  15. use app\service\api\login\LoginService;
  16. use Closure;
  17. use Exception;
  18. use core\exception\AuthException;
  19. /**
  20. * 会员登录token验证
  21. * Class ApiCheckToken
  22. * @package app\api\middleware
  23. */
  24. class ApiCheckToken
  25. {
  26. /**
  27. * @param Request $request
  28. * @param Closure $next
  29. * @param bool $is_throw_exception 是否把错误抛出
  30. * @return mixed
  31. * @throws Exception
  32. */
  33. public function handle(Request $request, Closure $next, bool $is_throw_exception = false)
  34. {
  35. $request->appType(AppTypeDict::API);
  36. //通过配置来设置系统header参数
  37. try {
  38. $token = $request->apiToken();
  39. $token_info = ( new LoginService() )->parseToken($token);
  40. } catch (AuthException $e) {
  41. //是否将登录错误抛出
  42. if ($is_throw_exception)
  43. return fail($e->getMessage(), [], $e->getCode());
  44. }
  45. if (!empty($token_info)) {
  46. $request->memberId($token_info[ 'member_id' ]);
  47. }
  48. // 校验渠道
  49. ( new AuthService() )->checkChannel($request);
  50. return $next($request);
  51. }
  52. }