Base.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2019/10/22
  6. * Time: 9:34 下午
  7. */
  8. namespace addons\unishop\controller;
  9. use app\common\controller\Api;
  10. use think\Cache;
  11. use think\Lang;
  12. /**
  13. * 基础类
  14. * @ApiInternal
  15. */
  16. class Base extends Api
  17. {
  18. /**
  19. * 无需鉴权的方法,但需要登录
  20. * @var array
  21. */
  22. protected $noNeedRight = ['*'];
  23. /**
  24. * 允许频繁访问的接口(方法格式:小写)
  25. * @var array
  26. */
  27. protected $frequently = [];
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. $this->loadUniShopLang();
  32. $this->limitVisit();
  33. }
  34. /**
  35. * 限制接口访问频率
  36. * @param int $millisecond
  37. * @ApiInternal
  38. */
  39. public function limitVisit($millisecond = 200) {
  40. $millisecond = $this->request->request('millisecond', $millisecond);
  41. // 限制200毫秒 防止1秒两刀 (双击甚至三击,同一时间导致接口请求两次以上)
  42. $action = $this->request->action();
  43. if (!in_array($action, $this->frequently) && $this->auth && $this->auth->isLogin() && $millisecond > 0) {
  44. $controller = $this->request->controller();
  45. if (Cache::has($controller.'_'.$action.'_'.$this->auth->id)) {
  46. if (Cache::get($controller.'_'.$action.'_'.$this->auth->id) + $millisecond > \addons\unishop\model\Config::getMillisecond()) {
  47. $this->error(__('Frequent interface requests'));
  48. }
  49. }
  50. Cache::set($controller.'_'.$action.'_'.$this->auth->id, \addons\unishop\model\Config::getMillisecond(), 1);
  51. }
  52. }
  53. /**
  54. * 加载语言文件
  55. */
  56. protected function loadUniShopLang()
  57. {
  58. $route = $this->request->route();
  59. $lang = $this->request->header('lang') ?: 'zh-cn';
  60. $path = ADDON_PATH . $route['addon'] . '/lang/' . $lang . '/' . str_replace('.', '/', $route['controller']) . '.php';
  61. Lang::load(ADDON_PATH . $route['addon'] . '/lang/'.$lang.'.php'); // 默认语言包
  62. Lang::load($path);
  63. }
  64. }