审查视图

application/common/controller/Api.php 8.5 KB
Karson authored
1 2 3 4
<?php

namespace app\common\controller;
5
use app\common\library\Auth;
6
use think\Config;
7 8
use think\exception\HttpResponseException;
use think\exception\ValidateException;
9
use think\Hook;
10 11 12 13
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
Karson authored
14
15 16 17 18
/**
 * API控制器基类
 */
class Api
Karson authored
19 20
{
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];
52
53 54
    /**
     * 权限Auth
55
     * @var Auth
56 57 58 59
     */
    protected $auth = null;

    /**
60
     * 默认响应输出类型,支持json/xml
61
     * @var string
62 63 64 65
     */
    protected $responseType = 'json';

    /**
66 67 68 69 70 71 72 73 74 75 76 77
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
78 79
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
80
                is_numeric($method) ?
81 82
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
83 84 85 86 87 88 89 90 91 92
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
93
        //移除HTML标签
94
        $this->request->filter('trim,strip_tags,htmlspecialchars');
95
96 97 98 99 100
        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());
101
102
        // token
103
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
104 105 106 107 108

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
109
        if (!$this->auth->match($this->noNeedLogin)) {
110 111 112
            //初始化
            $this->auth->init($token);
            //检测是否登录
113
            if (!$this->auth->isLogin()) {
114
                $this->error(__('Please login first'), null, 401);
115 116
            }
            // 判断是否需要验证权限
117
            if (!$this->auth->match($this->noNeedRight)) {
118
                // 判断控制器和方法判断是否有对应权限
119
                if (!$this->auth->check($path)) {
120
                    $this->error(__('You have no permission'), null, 403);
121 122
                }
            }
123
        } else {
124
            // 如果有传递token才验证是否登录状态
125
            if ($token) {
126 127 128
                $this->auth->init($token);
            }
        }
Karson authored
129 130 131 132 133 134 135 136

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));
137 138 139 140 141 142 143 144 145 146
        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
147
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
148 149 150 151
    }

    /**
     * 操作成功返回的数据
152 153 154 155 156
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
157
     */
158
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
159
    {
160
        $this->result($msg, $data, $code, $type, $header);
161 162 163 164
    }

    /**
     * 操作失败返回的数据
165 166 167 168 169
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
170
     */
171
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
Karson authored
172
    {
173
        $this->result($msg, $data, $code, $type, $header);
174 175 176 177 178
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
179
     * @param mixed  $msg    提示信息
180
     * @param mixed  $data   要返回的数据
181 182
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型,支持json/xml/jsonp
183 184 185 186
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
187
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
188 189 190 191 192 193 194
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
195 196 197
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
198
        if (isset($header['statuscode'])) {
199 200
            $code = $header['statuscode'];
            unset($header['statuscode']);
201
        } else {
202 203
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
204 205
        }
        $response = Response::create($result, $type, $code)->header($header);
206 207 208 209 210 211 212 213 214 215 216 217
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param  string $method  前置操作方法名
     * @param  array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
218 219
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
220 221 222
                $options['only'] = explode(',', $options['only']);
            }
223
            if (!in_array($this->request->action(), $options['only'])) {
224 225
                return;
            }
226 227
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
228 229 230
                $options['except'] = explode(',', $options['except']);
            }
231
            if (in_array($this->request->action(), $options['except'])) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                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    是否批量验证
     * @param  mixed        $callback 回调方法(闭包)
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
265
        if (is_array($validate)) {
266 267
            $v = Loader::validate();
            $v->rule($validate);
268
        } else {
269
            // 支持场景
270
            if (strpos($validate, '.')) {
271 272 273 274 275 276 277 278 279
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
280
        if ($batch || $this->batchValidate) {
281
            $v->batch(true);
282
        }
283
        // 设置错误信息
284
        if (is_array($message)) {
285
            $v->message($message);
286
        }
287
        // 使用回调验证
288
        if ($callback && is_callable($callback)) {
289 290 291
            call_user_func_array($callback, [$v, &$data]);
        }
292 293
        if (!$v->check($data)) {
            if ($this->failException) {
294 295 296 297 298
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }
Karson authored
299
300
        return true;
Karson authored
301 302
    }
}