| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- <?php
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // | Original reference: https://gitee.com/karson/fastadmin
- // +----------------------------------------------------------------------
- // +----------------------------------------------------------------------
- // | API控制器基类
- // +----------------------------------------------------------------------
- namespace app\common\controller;
- use app\common\library\Auth;
- use think\App;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\facade\Config;
- use think\facade\Event;
- use think\Response;
- use think\Validate;
- class Api
- {
- /**
- * @var Request Request 实例
- */
- protected $request;
- /**
- * 应用实例
- * @var \think\App
- */
- protected $app;
- /**
- * @var bool 验证失败是否抛出异常
- */
- protected $failException = true;
- /**
- * 是否批量验证
- * @var bool
- */
- protected $batchValidate = false;
- /**
- * @var array 前置操作方法列表
- */
- protected $beforeActionList = [];
- /**
- * 无需登录的方法,同时也就不需要鉴权了
- * @var array
- */
- protected $noNeedLogin = [];
- /**
- * 无需鉴权的方法,但需要登录
- * @var array
- */
- protected $noNeedRight = [];
- /**
- * 权限Auth
- * @var Auth
- */
- protected $auth = null;
- /**
- * 默认响应输出类型,支持json/xml
- * @var string
- */
- protected $responseType = 'json';
- /**
- * 构造方法
- * @access public
- * @param Request $request Request 对象
- */
- public function __construct(App $app)
- {
- $this->app = $app;
- $this->request = is_null($this->app->request) ? \think\facade\Request::instance() : $this->app->request;
- // 控制器初始化
- $this->initialize();
- // 前置操作方法
- if ($this->beforeActionList) {
- foreach ($this->beforeActionList as $method => $options) {
- is_numeric($method) ?
- $this->beforeAction($options) :
- $this->beforeAction($method, $options);
- }
- }
- }
- /**
- * 初始化操作
- * @access protected
- */
- protected function initialize()
- {
- //移除HTML标签
- $this->request->filter('trim,strip_tags,htmlspecialchars');
- $this->auth = Auth::instance();
- $modulename = $this->app->http->getName();
- $controller = preg_replace_callback('/\.[A-Z]/', function ($d) {
- return strtolower($d[0]);
- }, $this->request->controller());
- $controllername = parse_name($controller);
- $actionname = strtolower($this->request->action());
- // token
- $token = $this->request->server('HTTP_TOKEN', (string) $this->request->request('token', \think\facade\Cookie::get('token')));
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
- // 设置当前请求的URI
- $this->auth->setRequestUri($path);
- // 检测是否需要验证登录
- if (!$this->auth->match($this->noNeedLogin)) {
- //初始化
- $this->auth->init($token);
- //检测是否登录
- if (!$this->auth->isLogin()) {
- $this->error('请先登陆', null, 401);
- }
- // 判断是否需要验证权限
- if (!$this->auth->match($this->noNeedRight)) {
- // 判断控制器和方法判断是否有对应权限
- /*if (!$this->auth->check($path)) {
- $this->error(__('You have no permission'), null, 403);
- }*/
- }
- } else {
- // 如果有传递token才验证是否登录状态
- if ($token) {
- $this->auth->init($token);
- }
- }
- // 上传信息配置后
- $upload = array_merge(\app\common\model\Config::upload(), ...Event::trigger("upload_config_init"));
- Config::set(array_merge(Config::get('upload'), $upload), 'upload');
- }
- /**
- * 操作成功返回的数据
- * @param string $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为1
- * @param string $type 输出类型
- * @param array $header 发送的 Header 信息
- */
- protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
- {
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 操作失败返回的数据
- * @param string $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string $type 输出类型
- * @param array $header 发送的 Header 信息
- */
- protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
- {
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 返回封装后的 API 数据到客户端
- * @access protected
- * @param mixed $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string $type 输出类型,支持json/xml/jsonp
- * @param array $header 发送的 Header 信息
- * @return void
- * @throws HttpResponseException
- */
- protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
- {
- $result = [
- 'code' => $code,
- 'msg' => $msg,
- 'time' => $this->request->server('REQUEST_TIME'),
- 'data' => $data,
- ];
- // 如果未设置类型则自动判断
- $type = $type ?: $this->responseType;
- if (isset($header['statuscode'])) {
- $code = $header['statuscode'];
- unset($header['statuscode']);
- } else {
- //未设置状态码,根据code值判断
- $code = $code >= 1000 || $code < 200 ? 200 : $code;
- }
- $response = Response::create($result, $type, $code)->header($header);
- throw new HttpResponseException($response);
- }
- /**
- * 前置操作
- * @access protected
- * @param string $method 前置操作方法名
- * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
- * @return void
- */
- protected function beforeAction($method, $options = [])
- {
- if (isset($options['only'])) {
- if (is_string($options['only'])) {
- $options['only'] = explode(',', $options['only']);
- }
- if (!in_array($this->request->action(), $options['only'])) {
- return;
- }
- } elseif (isset($options['except'])) {
- if (is_string($options['except'])) {
- $options['except'] = explode(',', $options['except']);
- }
- if (in_array($this->request->action(), $options['except'])) {
- return;
- }
- }
- call_user_func([$this, $method]);
- }
- /**
- * 设置验证失败后是否抛出异常
- * @access protected
- * @param bool $fail 是否抛出异常
- * @return $this
- */
- protected function validateFailException($fail = true)
- {
- $this->failException = $fail;
- return $this;
- }
- /**
- * 验证数据
- * @access protected
- * @param array $data 数据
- * @param string|array $validate 验证器名或者验证规则数组
- * @param array $message 提示信息
- * @param bool $batch 是否批量验证
- * @return array|string|true
- * @throws ValidateException
- */
- protected function validate(array $data, string | array $validate, array $message = [], bool $batch = false)
- {
- if (is_array($validate)) {
- $v = new Validate();
- $v->rule($validate);
- } else {
- if (strpos($validate, '.')) {
- // 支持场景
- [$validate, $scene] = explode('.', $validate);
- }
- $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
- $v = new $class();
- if (!empty($scene)) {
- $v->scene($scene);
- }
- }
- $v->message($message);
- // 是否批量验证
- if ($batch || $this->batchValidate) {
- $v->batch(true);
- }
- return $v->failException($this->failException)->check($data);
- }
- //刷新Token
- protected function token()
- {
- $check = $this->request->checkToken('__token__');
- // 刷新token
- $token = $this->request->buildToken();
- if ($this->request->isAjax()) {
- header('__token__: ' . $token);
- }
- if (false === $check) {
- $this->error('令牌错误!', '', ['__token__' => $token]);
- }
- }
- }
|