Api.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use think\Config;
  5. use think\exception\HttpResponseException;
  6. use think\exception\ValidateException;
  7. use think\Hook;
  8. use think\Lang;
  9. use think\Loader;
  10. use think\Request;
  11. use think\Response;
  12. use think\Route;
  13. use think\Validate;
  14. /**
  15. * API控制器基类
  16. */
  17. class Api
  18. {
  19. /**
  20. * @var Request Request 实例
  21. */
  22. protected $request;
  23. /**
  24. * @var bool 验证失败是否抛出异常
  25. */
  26. protected $failException = false;
  27. /**
  28. * @var bool 是否批量验证
  29. */
  30. protected $batchValidate = false;
  31. /**
  32. * @var array 前置操作方法列表
  33. */
  34. protected $beforeActionList = [];
  35. /**
  36. * 无需登录的方法,同时也就不需要鉴权了
  37. * @var array
  38. */
  39. protected $noNeedLogin = [];
  40. /**
  41. * 无需鉴权的方法,但需要登录
  42. * @var array
  43. */
  44. protected $noNeedRight = [];
  45. /**
  46. * 权限Auth
  47. * @var Auth
  48. */
  49. protected $auth = null;
  50. /**
  51. * 默认响应输出类型,支持json/xml
  52. * @var string
  53. */
  54. protected $responseType = 'json';
  55. /**
  56. * 构造方法
  57. * @access public
  58. * @param Request $request Request 对象
  59. */
  60. public function __construct(Request $request = null)
  61. {
  62. $this->request = is_null($request) ? Request::instance() : $request;
  63. // 控制器初始化
  64. $this->_initialize();
  65. // 前置操作方法
  66. if ($this->beforeActionList) {
  67. foreach ($this->beforeActionList as $method => $options) {
  68. is_numeric($method) ?
  69. $this->beforeAction($options) :
  70. $this->beforeAction($method, $options);
  71. }
  72. }
  73. }
  74. /**
  75. * 初始化操作
  76. * @access protected
  77. */
  78. protected function _initialize()
  79. {
  80. //跨域请求检测
  81. check_cors_request();
  82. // 检测IP是否允许
  83. check_ip_allowed();
  84. //移除HTML标签
  85. $this->request->filter('trim,strip_tags,htmlspecialchars');
  86. $this->auth = Auth::instance();
  87. $modulename = $this->request->module();
  88. $controllername = Loader::parseName($this->request->controller());
  89. $actionname = strtolower($this->request->action());
  90. // token
  91. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  92. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  93. // 设置当前请求的URI
  94. $this->auth->setRequestUri($path);
  95. // 检测是否需要验证登录
  96. if (!$this->auth->match($this->noNeedLogin)) {
  97. //初始化
  98. $this->auth->init($token);
  99. //检测是否登录
  100. if (!$this->auth->isLogin()) {
  101. $this->error(__('Please login first'), null, 401);
  102. }
  103. // 判断是否需要验证权限
  104. if (!$this->auth->match($this->noNeedRight)) {
  105. // 判断控制器和方法判断是否有对应权限
  106. if (!$this->auth->check($path)) {
  107. $this->error(__('You have no permission'), null, 403);
  108. }
  109. }
  110. } else {
  111. // 如果有传递token才验证是否登录状态
  112. if ($token) {
  113. $this->auth->init($token);
  114. }
  115. }
  116. $upload = \app\common\model\Config::upload();
  117. // 上传信息配置后
  118. Hook::listen("upload_config_init", $upload);
  119. Config::set('upload', array_merge(Config::get('upload'), $upload));
  120. // 加载当前控制器语言包
  121. $this->loadlang($controllername);
  122. }
  123. /**
  124. * 加载语言文件
  125. * @param string $name
  126. */
  127. protected function loadlang($name)
  128. {
  129. $name = Loader::parseName($name);
  130. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  131. }
  132. /**
  133. * 操作成功返回的数据
  134. * @param string $msg 提示信息
  135. * @param mixed $data 要返回的数据
  136. * @param int $code 错误码,默认为1
  137. * @param string $type 输出类型
  138. * @param array $header 发送的 Header 信息
  139. */
  140. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  141. {
  142. if ($data && in_array(request()->action(), ['getUserInfo'])) {
  143. //手机号/微信号 私钥加密
  144. // $private_key = "-----BEGIN RSA PRIVATE KEY-----" .PHP_EOL.
  145. // wordwrap(config('private_key'), 64, PHP_EOL, true) .
  146. // PHP_EOL."-----END RSA PRIVATE KEY-----";
  147. $public_key = "-----BEGIN PUBLIC KEY-----" .PHP_EOL.
  148. wordwrap(config('public_key'), 64, PHP_EOL, true) .
  149. PHP_EOL."-----END PUBLIC KEY-----";
  150. if (isset($data['mobile']) && $data['mobile']) {
  151. $mobile = "";
  152. // openssl_private_encrypt($data['mobile'], $mobile, $private_key); // 使用私钥加密数据
  153. openssl_public_encrypt($data['mobile'], $mobile, $public_key);
  154. $data['mobile'] = base64_encode($mobile);
  155. }
  156. if (isset($data['wechat'])) {
  157. if ($data['wechat']) {
  158. $wechat = "";
  159. // openssl_private_encrypt($data['wechat'], $wechat, $private_key); // 使用私钥加密数据
  160. openssl_public_encrypt($data['wechat'], $wechat, $public_key);
  161. $data['wechat'] = base64_encode($wechat);
  162. } else {
  163. $data['wechat'] = '';
  164. }
  165. }
  166. if (isset($data['wechat_auth'])) {
  167. if ($data['wechat_auth']) {
  168. $wechat_auth = "";
  169. // openssl_private_encrypt($data['wechat_auth'], $wechat_auth, $private_key); // 使用私钥加密数据
  170. openssl_public_encrypt($data['wechat_auth'], $wechat_auth, $public_key);
  171. $data['wechat_auth'] = base64_encode($wechat_auth);
  172. } else {
  173. $data['wechat_auth'] = '';
  174. }
  175. }
  176. }
  177. $this->result($msg, $data, $code, $type, $header);
  178. }
  179. /**
  180. * 操作失败返回的数据
  181. * @param string $msg 提示信息
  182. * @param mixed $data 要返回的数据
  183. * @param int $code 错误码,默认为0
  184. * @param string $type 输出类型
  185. * @param array $header 发送的 Header 信息
  186. */
  187. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  188. {
  189. $this->result($msg, $data, $code, $type, $header);
  190. }
  191. /**
  192. * 返回封装后的 API 数据到客户端
  193. * @access protected
  194. * @param mixed $msg 提示信息
  195. * @param mixed $data 要返回的数据
  196. * @param int $code 错误码,默认为0
  197. * @param string $type 输出类型,支持json/xml/jsonp
  198. * @param array $header 发送的 Header 信息
  199. * @return void
  200. * @throws HttpResponseException
  201. */
  202. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  203. {
  204. $result = [
  205. 'code' => $code,
  206. 'msg' => $msg,
  207. 'time' => Request::instance()->server('REQUEST_TIME'),
  208. 'data' => $data,
  209. ];
  210. // 如果未设置类型则自动判断
  211. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  212. if (isset($header['statuscode'])) {
  213. $code = $header['statuscode'];
  214. unset($header['statuscode']);
  215. } else {
  216. //未设置状态码,根据code值判断
  217. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  218. }
  219. $response = Response::create($result, $type, $code)->header($header);
  220. throw new HttpResponseException($response);
  221. }
  222. /**
  223. * 前置操作
  224. * @access protected
  225. * @param string $method 前置操作方法名
  226. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  227. * @return void
  228. */
  229. protected function beforeAction($method, $options = [])
  230. {
  231. if (isset($options['only'])) {
  232. if (is_string($options['only'])) {
  233. $options['only'] = explode(',', $options['only']);
  234. }
  235. if (!in_array($this->request->action(), $options['only'])) {
  236. return;
  237. }
  238. } elseif (isset($options['except'])) {
  239. if (is_string($options['except'])) {
  240. $options['except'] = explode(',', $options['except']);
  241. }
  242. if (in_array($this->request->action(), $options['except'])) {
  243. return;
  244. }
  245. }
  246. call_user_func([$this, $method]);
  247. }
  248. /**
  249. * 设置验证失败后是否抛出异常
  250. * @access protected
  251. * @param bool $fail 是否抛出异常
  252. * @return $this
  253. */
  254. protected function validateFailException($fail = true)
  255. {
  256. $this->failException = $fail;
  257. return $this;
  258. }
  259. /**
  260. * 验证数据
  261. * @access protected
  262. * @param array $data 数据
  263. * @param string|array $validate 验证器名或者验证规则数组
  264. * @param array $message 提示信息
  265. * @param bool $batch 是否批量验证
  266. * @param mixed $callback 回调方法(闭包)
  267. * @return array|string|true
  268. * @throws ValidateException
  269. */
  270. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  271. {
  272. if (is_array($validate)) {
  273. $v = Loader::validate();
  274. $v->rule($validate);
  275. } else {
  276. // 支持场景
  277. if (strpos($validate, '.')) {
  278. list($validate, $scene) = explode('.', $validate);
  279. }
  280. $v = Loader::validate($validate);
  281. !empty($scene) && $v->scene($scene);
  282. }
  283. // 批量验证
  284. if ($batch || $this->batchValidate) {
  285. $v->batch(true);
  286. }
  287. // 设置错误信息
  288. if (is_array($message)) {
  289. $v->message($message);
  290. }
  291. // 使用回调验证
  292. if ($callback && is_callable($callback)) {
  293. call_user_func_array($callback, [$v, &$data]);
  294. }
  295. if (!$v->check($data)) {
  296. if ($this->failException) {
  297. throw new ValidateException($v->getError());
  298. }
  299. return $v->getError();
  300. }
  301. return true;
  302. }
  303. /**
  304. * 刷新Token
  305. */
  306. protected function token()
  307. {
  308. $token = $this->request->param('__token__');
  309. //验证Token
  310. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  311. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  312. }
  313. //刷新Token
  314. $this->request->token();
  315. }
  316. }