ClientMiddleware.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\interfaces\MiddlewareInterface;
  15. /**
  16. * 客户身份验证中间件
  17. * Class ClientMiddleware
  18. * @package app\http\middleware\api
  19. */
  20. class ClientMiddleware implements MiddlewareInterface
  21. {
  22. public function handle(Request $request, \Closure $next)
  23. {
  24. $userId = trim(ltrim($request->param('userid')));
  25. if (!$userId) {
  26. return app('json')->fail('缺少Userid');
  27. }
  28. try {
  29. /** @var UserAuthServices $service */
  30. $service = app()->make(UserAuthServices::class);
  31. $authInfo = $service->parseClient($userId);
  32. } catch (\Throwable $e) {
  33. return app('json')->fail($e->getMessage());
  34. }
  35. $request->macro('clientInfo', function (string $key = null) use ($authInfo) {
  36. if ($key) {
  37. return $authInfo[$key] ?? null;
  38. } else {
  39. return $authInfo;
  40. }
  41. });
  42. $request->macro('userid', function () use ($userId) {
  43. return $userId;
  44. });
  45. return $next($request);
  46. }
  47. }