Auth.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\data\controller\api;
  3. use app\data\service\UserAdminService;
  4. use app\data\service\UserTokenService;
  5. use think\admin\Controller;
  6. use think\exception\HttpResponseException;
  7. /**
  8. * 接口授权认证基类
  9. * Class Auth
  10. * @package app\store\controller\api
  11. */
  12. abstract class Auth extends Controller
  13. {
  14. /**
  15. * 当前接口请求终端类型
  16. * --- 手机浏览器访问 wap
  17. * --- 电脑浏览器访问 web
  18. * --- 微信小程序访问 wxapp
  19. * --- 微信服务号访问 wechat
  20. * --- 苹果应用接口访问 isoapp
  21. * --- 安卓应用接口访问 android
  22. * @var string
  23. */
  24. protected $type;
  25. /**
  26. * 当前用户编号
  27. * @var integer
  28. */
  29. protected $uuid;
  30. /**
  31. * 当前用户数据
  32. * @var array
  33. */
  34. protected $user;
  35. /**
  36. * 控制器初始化
  37. */
  38. protected function initialize()
  39. {
  40. // 接收接口类型
  41. $this->type = $this->request->request('api');
  42. $this->type = $this->type ?: $this->request->header('api-name');
  43. $this->type = $this->type ?: $this->request->header('api-type');
  44. // 检查接口类型
  45. if (empty($this->type)) {
  46. $this->error("未获取到接口类型字段!");
  47. }
  48. if (isset(UserAdminService::TYPES[$this->type])) {
  49. $this->error("接口类型[{$this->type}]未定义!");
  50. }
  51. // 获取用户数据
  52. $this->user = $this->getUser();
  53. $this->uuid = $this->user['id'] ?? '';
  54. if (empty($this->uuid)) {
  55. $this->error('用户登录失败!', '{-null-}', 401);
  56. }
  57. }
  58. /**
  59. * 获取用户数据
  60. * @return array
  61. */
  62. protected function getUser(): array
  63. {
  64. try {
  65. if (empty($this->uuid)) {
  66. $token = input('token') ?: $this->request->header('api-token');
  67. if (empty($token)) $this->error('登录认证TOKEN不能为空!');
  68. [$state, $info, $this->uuid] = UserTokenService::instance()->check($this->type, $token);
  69. if (empty($state)) $this->error($info, '{-null-}', 401);
  70. }
  71. return UserAdminService::instance()->get($this->uuid, $this->type);
  72. } catch (HttpResponseException $exception) {
  73. throw $exception;
  74. } catch (\Exception $exception) {
  75. $this->error($exception->getMessage());
  76. }
  77. }
  78. /**
  79. * 显示用户禁用提示
  80. */
  81. protected function checkUserStatus()
  82. {
  83. if (empty($this->user['status'])) {
  84. $this->error('账户已被冻结!');
  85. }
  86. }
  87. }