Генерация Tokne может использовать JWT
Не используйте return для возврата информации в __construct
<?php
namespace app\api\controller;
use think\Cache;
use think\Controller;
use think\Request;
class Base extends Controller
{
//将你控制器中不需要验证的方法写在此数组中即可不用token验证
protected $url = [''];
protected $params;
protected $userInfo;
function __construct(Request $request = null)
{
$ip = request()->ip();//获取ip地址
$num = Cache::get($ip . 'times');//获取请求次数
$lastTime = Cache::get($ip . 'time');//获取上次请求的时间
if (time() - $lastTime < 1) {//正式上线时改为60
if ($num >= 5)//每分钟请求大于等于5次的时候限制请求
{
$res = [
'code' => 511,
'msg' => '操作过于频繁!'
];
echo json($res)->send();
die;//返回信息阻止继续请求
}
}
if ($num >= 5) {
Cache::rm($ip . 'times');
}
parent::__construct($request);
$route = strtolower(request()->controller() . '/' . request()->action());//获取请求控制器和方法
$header = Request::instance()->header();
if (!in_array($route, $this->url))//判断请求的控制器方法是否在数组中,没有则需要登录验证
{
if (empty($header['token'])) {
$this->fail('token不存在!', 403);
die;
}
//令牌验证
$res = \app\api\model\User::where('token', $header['token'])->find();
if (!$res) {
$this->fail('token无效!', 500);
die;
}
}
$this->params = input();
$this->userInfo = \app\api\model\User::where('token', $header['token'])->find();
Cache::set($ip . 'time', time());//将同一ip地址的第一次请求时间存入缓存
Cache::inc($ip . 'times');//请求次数存入Redis做自增
}
protected function response($code = 200, $msg = 'success', $data = [])
{
$res = [
'code' => $code,
'msg' => $msg,
'data' => $data
];
//框架写法
json($res)->send();
}
/**
* 成功的响应
* @param array $data 返回数据
* @param int $code 错误码
* @param string $msg 错误信息
*/
protected function ok($data = [], $code = 200, $msg = 'success')
{
$this->response($code, $msg, $data);
}
/**
* 失败的响应
* @param $msg 错误信息
* @param int $code 错误码
* @param array $data 返回数据
*/
protected function fail($msg, $code = 500, $data = [])
{
$this->response($code, $msg, $data);
}
}