Auth.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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\data\controller\api
  11. */
  12. abstract class Auth extends Controller
  13. {
  14. /**
  15. * 当前接口请求终端类型
  16. * >>>>>>>>>>>>>>>>>>>>>>
  17. * >>> api-name 接口类型
  18. * >>> api-token 接口认证
  19. * >>>>>>>>>>>>>>>>>>>>>>
  20. * --- 手机浏览器访问 wap
  21. * --- 电脑浏览器访问 web
  22. * --- 微信小程序访问 wxapp
  23. * --- 微信服务号访问 wechat
  24. * --- 苹果应用接口访问 isoapp
  25. * --- 安卓应用接口访问 android
  26. * @var string
  27. */
  28. protected $type;
  29. /**
  30. * 当前用户编号
  31. * @var integer
  32. */
  33. protected $uuid;
  34. /**
  35. * 当前用户数据
  36. * @var array
  37. */
  38. protected $user;
  39. protected $noNeedLogin=[];
  40. /**
  41. * 控制器初始化
  42. */
  43. protected function initialize()
  44. {
  45. // 检查接口类型
  46. $this->type = $this->request->header('api-name');
  47. if (empty($this->type)||!isset(UserAdminService::TYPES[$this->type])) {
  48. $this->error("接口类型未定义!header中增加api-name,值为手机浏览器访问wap电脑浏览器访问web微信小程序访问wxapp微信服务号访问wechat苹果应用接口访问isoapp安卓应用接口访问android");
  49. }
  50. // 读取用户数据
  51. $this->user = $this->getUser();
  52. $this->checkUserStatus();
  53. $this->uuid = $this->user['id'] ?? '';
  54. }
  55. /**
  56. * 获取用户数据
  57. * @return array
  58. */
  59. protected function getUser(): array
  60. {
  61. try {
  62. if (empty($this->uuid)) {
  63. $token = $this->request->header('api-token','');
  64. if($this->needLogin()) {
  65. if (empty($token)) $this->error('登录认证不能为空!');
  66. }
  67. [$state, $info, $this->uuid] = UserTokenService::check($this->type, $token);
  68. if($this->needLogin()) {
  69. if (empty($state)) $this->error($info, '{-null-}', 401);
  70. }
  71. }
  72. if($this->uuid) {
  73. return UserAdminService::get($this->uuid, $this->type);
  74. }
  75. return [];
  76. } catch (HttpResponseException $exception) {
  77. throw $exception;
  78. } catch (\Exception $exception) {
  79. trace_file($exception);
  80. $this->error($exception->getMessage());
  81. }
  82. }
  83. /**
  84. * 显示用户禁用提示
  85. */
  86. protected function checkUserStatus()
  87. {
  88. if (empty($this->user['status'])) {
  89. $this->error('账户已被冻结!');
  90. }
  91. }
  92. /**
  93. * @return bool
  94. */
  95. protected function needLogin(): bool
  96. {
  97. return !in_array($this->app->request->action(),$this->noNeedLogin,true);
  98. }
  99. }