Auth.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace app\data\controller\api;
  3. use app\data\service\UserService;
  4. use think\admin\Controller;
  5. use think\exception\HttpResponseException;
  6. /**
  7. * 授权认证基类
  8. * Class Auth
  9. * @package app\store\controller\api
  10. */
  11. abstract class Auth extends Controller
  12. {
  13. /**
  14. * 当前接口类型
  15. * -- 应用接口访问 app
  16. * -- 手机浏览器访问 wap
  17. * -- 电脑浏览器访问 web
  18. * -- 微信小程序访问 wxapp
  19. * -- 微信服务号访问 wechat
  20. * @var string
  21. */
  22. protected $type;
  23. /**
  24. * 当前用户编号
  25. * @var integer
  26. */
  27. protected $uuid;
  28. /**
  29. * 当前用户数据
  30. * @var array
  31. */
  32. protected $user;
  33. /**
  34. * 控制器初始化
  35. */
  36. protected function initialize()
  37. {
  38. // 接口数据类型
  39. $this->type = input('api') ?: $this->request->header('api-type');
  40. $this->type = $this->type ?: UserService::APITYPE_WXAPP;
  41. if (empty(UserService::TYPES[$this->type])) {
  42. $this->error("接口通道[{$this->type}]未定义规则!");
  43. }
  44. // 获取用户数据
  45. $this->user = $this->getUser();
  46. $this->uuid = $this->user['id'];
  47. }
  48. /**
  49. * 获取用户数据
  50. * @return array
  51. */
  52. protected function getUser(): array
  53. {
  54. try {
  55. $user = UserService::instance();
  56. if (empty($this->uuid)) {
  57. $token = input('token') ?: $this->request->header('api-token');
  58. if (empty($token)) $this->error('登录认证TOKEN不能为空!');
  59. [$state, $info, $this->uuid] = $user->check($this->type, $token);
  60. if (empty($state)) $this->error($info, '{-null-}', 401);
  61. }
  62. return $user->get($this->type, $this->uuid);
  63. } catch (HttpResponseException $exception) {
  64. throw $exception;
  65. } catch (\Exception $exception) {
  66. $this->error($exception->getMessage());
  67. }
  68. }
  69. }