Auth.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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->uuid = $this->user['id'] ?? '';
  53. }
  54. /**
  55. * 获取用户数据
  56. * @return array
  57. */
  58. protected function getUser(): array
  59. {
  60. try {
  61. if (empty($this->uuid)) {
  62. $token = $this->request->header('api-token','');
  63. if($this->needLogin()) {
  64. if (empty($token)) $this->error('登录认证不能为空!');
  65. }
  66. [$state, $info, $this->uuid] = UserTokenService::check($this->type, $token);
  67. if($this->needLogin()) {
  68. if (empty($state)) $this->error($info, '{-null-}', 401);
  69. }
  70. }
  71. if($this->uuid) {
  72. return UserAdminService::get($this->uuid, $this->type);
  73. }
  74. return [];
  75. } catch (HttpResponseException $exception) {
  76. throw $exception;
  77. } catch (\Exception $exception) {
  78. trace_file($exception);
  79. $this->error($exception->getMessage());
  80. }
  81. }
  82. /**
  83. * 显示用户禁用提示
  84. */
  85. protected function checkUserStatus()
  86. {
  87. if (empty($this->user['status'])) {
  88. $this->error('账户已被冻结!');
  89. }
  90. }
  91. /**
  92. * @return bool
  93. */
  94. protected function needLogin(): bool
  95. {
  96. return !in_array($this->app->request->action(),$this->noNeedLogin,true);
  97. }
  98. }