Base.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. public function __construct()
  35. {
  36. parent::__construct();
  37. $this->loadUniShopLang();
  38. $this->limitVisit();
  39. }
  40. /**
  41. * 限制接口访问频率
  42. * @param int $millisecond
  43. * @ApiInternal
  44. */
  45. public function limitVisit_bak($millisecond = 200) {
  46. //$millisecond = $this->request->request('millisecond', $millisecond);
  47. // 限制200毫秒 防止1秒两刀 (双击甚至三击,同一时间导致接口请求两次以上)
  48. $action = $this->request->action();
  49. if (!in_array($action, $this->frequently) && $this->auth && $this->auth->isLogin() && $millisecond > 0) {
  50. $controller = $this->request->controller();
  51. if (Cache::has($controller.'_'.$action.'_'.$this->auth->id)) {
  52. if (Cache::get($controller.'_'.$action.'_'.$this->auth->id) + $millisecond > \addons\unishop\model\Config::getMillisecond()) {
  53. $this->error(__('Frequent interface requests'));
  54. }
  55. }
  56. Cache::set($controller.'_'.$action.'_'.$this->auth->id, \addons\unishop\model\Config::getMillisecond(), 1);
  57. }
  58. }
  59. public function limitVisit($millisecond = 200) {
  60. $action = $this->request->action();
  61. if (!in_array($action, $this->frequently) && $this->auth && $this->auth->isLogin() && $millisecond > 0) {
  62. $apilimit = $this->apiLimit();
  63. if(!$apilimit){
  64. $this->error('操作过于频繁');
  65. }
  66. }
  67. }
  68. /**
  69. * 加载语言文件
  70. */
  71. protected function loadUniShopLang()
  72. {
  73. $route = $this->request->route();
  74. $lang = $this->request->header('lang') ?: 'zh-cn';
  75. $path = ADDON_PATH . $route['addon'] . '/lang/' . $lang . '/' . str_replace('.', '/', $route['controller']) . '.php';
  76. Lang::load(ADDON_PATH . $route['addon'] . '/lang/'.$lang.'.php'); // 默认语言包
  77. Lang::load($path);
  78. }
  79. }