Exemple #1
0
 /**
  * 检查 token 对应的用户是否有权限访问接口
  *
  * @param  string            $token  用于API权限验证的 token
  * @param  string            $action 控制器类名及方法(不包含命名空间)
  * @param  \App\Http\Request $req    HTTP 请求对象
  * @return array
  */
 public function valid_token($token, $action, &$req = null) : array
 {
     if (!$token || strlen($token) !== 32) {
         return [-101, '请提供有效的 token'];
     }
     $dateline = time();
     $uid = mem_get('api_' . $token);
     if ($uid === false) {
         $m_al = new ApiLogin();
         $api_login = $m_al->find(['token' => $token, 'dateline >=' => $dateline - self::CACHE_TIME], 'uid, token, dateline');
         if ($api_login) {
             $uid = $api_login['uid'];
             mem_set('api_' . $token, $uid, self::CACHE_TIME);
         } else {
             return [-102, 'token不匹配'];
         }
     }
     // 检查权限
     $key_rights = 'api_rights_' . $uid;
     $key_allowed_ip = 'api_allowed_ip_' . $uid;
     $uid_rights = mem_get($key_rights);
     $allowed_ip = mem_get($key_allowed_ip);
     if ($uid_rights === false) {
         $m_au = new ApiUser();
         $api_user = $m_au->find(['uid' => $uid], 'rights, allowed_ip');
         if (!$api_user) {
             return [-103, 'token 对应的用户不存在'];
         }
         $uid_rights = $api_user['rights'];
         $allowed_ip = $api_user['allowed_ip'];
         mem_set($key_rights, $uid_rights, self::CACHE_TIME);
         mem_set($key_allowed_ip, $allowed_ip, self::CACHE_TIME);
     }
     list($controller, $method) = explode(':', $action, 2);
     if (!$this->check_rights($uid_rights, $controller, $method)) {
         return [-104, '您没有权限访问该接口'];
     }
     // 检查IP是否允许
     $ip = $_SERVER['REMOTE_ADDR'];
     if ($allowed_ip && strpos($allowed_ip, $ip) === false) {
         return [-105, '您的IP无权限访问接口'];
     }
     $req = $this->set_extra_args($req, $uid_rights, $action);
     return [0, $uid];
 }
Exemple #2
0
 /**
  * How much time the client must wait before it will be 
  * allowed to try to log-in next.
  * The return value is 0 if no wait is required.
  */
 private function getNextLoginTimeout()
 {
     global $wgMemc;
     $val = $wgMemc->get($this->getMemCacheKey());
     $elapse = time() - $val['lastReqTime'];
     // in seconds
     $canRetryIn = ApiLogin::calculateDelay($val['count']) - $elapse;
     return $canRetryIn < 0 ? 0 : $canRetryIn;
 }