clientIp() public method

Get the IP the client is using, or says they are using.
public clientIp ( boolean $safe = true ) : string
$safe boolean Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
return string The client IP.
 protected function _findUser($username, $password)
 {
     $clientIp = $this->request->clientIp(false);
     try {
         $this->_initializeAPI();
         $userToken = $this->Api->authenticatePrincipal($username, $password, $this->settings['app_name'], $clientIp);
         $this->user = array();
         $this->user['User'] = $this->_getPrincipalAttributes($username);
         $this->user['User']['token'] = $userToken;
         $this->user['Group'] = $this->_getPrincipalGroups($username);
         return $this->user;
     } catch (CrowdAuthException $e) {
         return false;
     }
 }
 /**
  * Get the current user.
  *
  * Will prefer the static user cache over sessions. The static user
  * cache is primarily used for stateless authentication. For stateful authentication,
  * cookies + sessions will be used.
  *
  * @param string $key field to retrieve. Leave null to get entire User record
  * @return array|null User record. or null if no user is logged in.
  * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  */
 public static function user($key = null)
 {
     $user = array();
     $request = new CakeRequest();
     if (($authorization = $request->header('Authorization')) && preg_match('/^Bearer (.*?)$/', $authorization, $matches)) {
         $signer = new Sha256();
         $token = (new Parser())->parse((string) next($matches));
         try {
             if ($token->verify($signer, Configure::read('Security.salt'))) {
                 $data = new ValidationData(Configure::read('Security.timeout') > 0 ? null : $token->getClaim('iat'));
                 $data->setIssuer(Router::url('/', true));
                 $data->setAudience($request->clientIp());
                 if ($token->validate($data)) {
                     if ($user = json_decode($token->getClaim('data'), true)) {
                         if (!empty($user['id'])) {
                             if (!empty(static::$_user) && static::$_user['id'] == $user['id']) {
                                 $user = static::$_user;
                                 return empty($key) ? $user : Hash::get($user, $key);
                             } else {
                                 $User = ClassRegistry::init('User');
                                 $User->id = $user['id'];
                                 return Hash::get($User->read(), 'User' . (empty($key) ? '' : '.' . $key));
                             }
                         }
                     }
                 }
             }
         } catch (Exception $ex) {
         }
     }
     return false;
 }
Esempio n. 3
0
 /**
  * append some more infos to better track down the error
  * @return string
  * 2011-12-21 ms
  */
 public static function traceDetails()
 {
     App::uses('CommonComponent', 'Tools.Controller/Component');
     $currentUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'n/a';
     $refererUrl = CommonComponent::getReferer();
     //Router::getRequest()->url().'
     App::uses('CakeSession', 'Model/Datasource');
     $uid = CakeSession::read('Auth.User.id');
     if (empty($uid)) {
         $uid = !empty($_SESSION) && !empty($_SESSION['Auth']['User']['id']) ? $_SESSION['Auth']['User']['id'] : null;
     }
     $data = array(@CakeRequest::clientIp(), $currentUrl . (!empty($refererUrl) ? ' (' . $refererUrl . ')' : ''), $uid, env('HTTP_USER_AGENT'));
     return implode(' - ', $data);
 }
Esempio n. 4
0
 public function saveLoginHistory($user_id, CakeRequest $request)
 {
     if (empty($user_id) || !is_numeric($user_id)) {
         return false;
     }
     $loginData = array('user_id' => $user_id, 'ip_address' => $request->clientIp(false), 'user_agent' => $request->header('User-Agent'), 'created' => date('Y-m-d H:i:s'));
     $this->create();
     $this->save($loginData);
     //ユーザーのログイン回数の更新
     $this->User = ClassRegistry::init('User');
     $user = $this->User->findById($user_id);
     if (empty($user['User']['login_count'])) {
         $login_count = 1;
     } else {
         $login_count = $user['User']['login_count'] + 1;
     }
     $this->User->id = $user_id;
     $this->User->saveField('login_count', $login_count);
 }
Esempio n. 5
0
 /**
  * @param $data
  *
  * @return mixed
  */
 protected function _get_request($data)
 {
     $request = new CakeRequest();
     $data['request_user_agent'] = $request::header('User-Agent');
     $data['request_client_ip'] = $request->clientIp();
     $data['request_method'] = $request->method();
     $data['request_referer'] = $request->referer();
     $data['request_url'] = Router::url(null, true);
     return $data;
 }
Esempio n. 6
0
 /**
  * Queries the http:BL service.
  *
  * @param string $client IP address to query for.
  * @param string $apiKey Security service quey.
  * @return array
  * @throws Exception If any of the `$client` or `$apiKey` is empty.
  * @throws Exception If no record found in the http:BL database.
  * @throws Exception If request query malformed.
  */
 public function query($client = null, $apiKey = null)
 {
     if (empty($client) && empty($this->client)) {
         $request = new CakeRequest();
         $client = $request->clientIp(true);
     }
     foreach (array('apiKey', 'client') as $var) {
         if (!is_null(${$var})) {
             $this->{$var} = ${$var};
         }
         if (empty($this->{$var})) {
             throw new Exception(__d('security', "Missing the '%s' for the http:BL database to be queried.", $var));
         }
     }
     if ($this->cacheResponses && isset($this->responsesCache[$this->client])) {
         return $this->responsesCache[$this->client];
     }
     $query = $this->_buildQuery();
     $this->rawResponse = gethostbyname($query);
     if (in_array($this->rawResponse, array($query, self::NO_RECORD))) {
         throw new Exception(__d('security', "No record found in the http:BL database for '%s'.", $this->client));
     }
     list($result, $age, $level, $type) = explode('.', $this->rawResponse);
     if (127 != $result) {
         throw new Exception(__d('security', "Malformed http:BL query (%s) for '%s'.", $query, $this->client));
     }
     $this->lastResponse = compact('age', 'level', 'type');
     $this->responsesCache[$client] = $this->lastResponse;
     return $this->lastResponse;
 }
Esempio n. 7
0
 private function __getIpAddress()
 {
     return CakeRequest::clientIp();
 }
Esempio n. 8
0
 public function setUserIp(Model $Model, $userIP = null)
 {
     if ($userIP === null) {
         //App::uses();
         $userIP = CakeRequest::clientIp();
     }
     $this->userIP = $userIP;
 }
Esempio n. 9
0
 /**
  * Hurad configuration step
  */
 public function finalize()
 {
     $this->set('title_for_layout', __d('hurad', 'Hurad Configuration'));
     $dataSource = ConnectionManager::getDataSource('default');
     if ($this->request->is('post')) {
         $this->Installer->set($this->request->data);
         if ($this->Installer->validates()) {
             $search = [];
             $search['$[prefix]'] = $dataSource->config['prefix'];
             App::uses('CakeTime', 'Utility');
             $search['$[created]'] = CakeTime::format('Y-m-d H:i:s', strtotime('now'));
             $search['$[modified]'] = CakeTime::format('Y-m-d H:i:s', strtotime('now'));
             $request = new CakeRequest();
             $search['$[client_ip]'] = $request->clientIp();
             $search['$[user_agent]'] = $request::header('USER_AGENT');
             $search['$[username]'] = $this->request->data['Installer']['site_username'];
             $search['$[email]'] = $this->request->data['Installer']['email'];
             $search['$[password]'] = Security::hash($this->request->data['Installer']['site_password'], null, true);
             $search['$[title]'] = $this->request->data['Installer']['site_title'];
             $serverName = env("SERVER_NAME");
             $url = Router::url('/');
             $search['$[site_url]'] = rtrim("http://" . $serverName . $url, '/');
             if ($dataSource->connected) {
                 if ($this->__executeSQL("hurad_defaults.sql", $dataSource, $search)) {
                     $this->Session->setFlash(__d('hurad', 'Hurad successfully installed.'), 'flash_message', array('class' => 'success'));
                     $this->redirect(array('action' => 'welcome'));
                 }
             } else {
                 $this->Session->setFlash(__d('hurad', 'Not connected to database.'), 'flash_message', array('class' => 'danger'));
             }
         }
     }
 }
 /**
  * Test the clientIp method.
  *
  * @return void
  */
 public function testclientIp()
 {
     $_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.5, 10.0.1.1, proxy.com';
     $_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2';
     $_SERVER['REMOTE_ADDR'] = '192.168.1.3';
     $request = new CakeRequest('some/path');
     $this->assertEquals('192.168.1.3', $request->clientIp(), 'Use remote_addr in safe mode');
     $this->assertEquals('192.168.1.5', $request->clientIp(false), 'Use x-forwarded');
     unset($_SERVER['HTTP_X_FORWARDED_FOR']);
     $this->assertEquals('192.168.1.3', $request->clientIp(), 'safe uses remote_addr');
     $this->assertEquals('192.168.1.2', $request->clientIp(false), 'unsafe reads from client_ip');
     unset($_SERVER['HTTP_CLIENT_IP']);
     $this->assertEquals('192.168.1.3', $request->clientIp(), 'use remote_addr');
     $this->assertEquals('192.168.1.3', $request->clientIp(false), 'use remote_addr');
 }
Esempio n. 11
0
 /**
  * Check wether request is from a whitelisted IP address
  *
  * @see CakeRequest::addDetector()
  * @param $request CakeRequest Request object
  * @return boolean True when request is from a whitelisted IP Address
  */
 public static function isWhitelistedRequest(CakeRequest $request)
 {
     if (!$request) {
         return false;
     }
     $clientIp = $request->clientIp();
     $whitelist = array_map('trim', (array) explode(',', Configure::read('Site.ipWhitelist')));
     return in_array($clientIp, $whitelist);
 }
Esempio n. 12
0
 /**
  * beforeSave method
  *
  * @param mixed $Model
  * @return void
  * @access public
  */
 public function beforeSave(&$Model)
 {
     if (!$Model->useTable) {
         return false;
     }
     $this->__defaults($Model);
     foreach ($Model->data[$Model->alias] as $key => $value) {
         if (is_array($value)) {
             $Model->data[$Model->alias][$key] = serialize($value);
         }
     }
     if (!$Model->id) {
         App::uses('CakeRequest', 'Utility');
         $Model->data[$Model->alias]['ip'] = ip2long(CakeRequest::clientIp());
     }
     return true;
 }
Esempio n. 13
0
 /**
  * Append some more infos to better track down the error
  *
  * @return string
  */
 public static function traceDetails()
 {
     if (empty($_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'], '/test.php?') === 0) {
         return null;
     }
     $currentUrl = Router::url();
     //isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'n/a';
     $refererUrl = Utility::getReferer();
     //Router::getRequest()->url().'
     $uid = !empty($_SESSION) && !empty($_SESSION['Auth']['User']['id']) ? $_SESSION['Auth']['User']['id'] : null;
     $data = array(@CakeRequest::clientIp(), $currentUrl . (!empty($refererUrl) ? ' (' . $refererUrl . ')' : ''), $uid, env('HTTP_USER_AGENT'));
     return implode(' - ', $data);
 }
Esempio n. 14
0
 /**
  * Add comment
  */
 public function add()
 {
     if ($this->request->is('post')) {
         $this->Comment->create();
         if ($this->Auth->loggedIn()) {
             $user = $this->Comment->User->getUser($this->Auth->user('id'));
             $this->request->data['Comment']['user_id'] = $user['User']['id'];
             $this->request->data['Comment']['author'] = $user['UserMeta']['display_name'];
             $this->request->data['Comment']['author_email'] = $user['User']['email'];
             $this->request->data['Comment']['author_url'] = $user['User']['url'];
         }
         if ($this->Auth->user('role') == 'administrator') {
             $this->request->data['Comment']['author_url'];
         }
         $request = new CakeRequest();
         $this->request->data['Comment']['author_ip'] = $request->clientIp();
         $this->request->data['Comment']['agent'] = env('HTTP_USER_AGENT');
         $this->request->data['Comment']['author_url'] = HuradSanitize::url($this->request->data['Comment']['author_url']);
         if ($this->Comment->save($this->request->data)) {
             $this->Hurad->sendEmail($this->request->data['Comment']['author_email'], __d('hurad', 'Comment Submit'), 'add_comment', __d('hurad', 'Your comment submit in blog waiting to approve by admin.'));
             $this->Session->setFlash(__d('hurad', 'The comment has been saved'), 'flash_message', ['class' => 'success'], 'comment-flash');
             $this->redirect($this->referer());
         } else {
             $this->Session->setFlash(__d('hurad', 'The comment could not be saved. Please, try again.'), 'flash_message', ['class' => 'danger'], 'comment-flash');
             $this->redirect($this->referer());
         }
     }
 }
 protected function _getUserIpAddr()
 {
     $ip = '0.0.0.0';
     $CakeRequest = new CakeRequest();
     return $CakeRequest->clientIp();
 }
 /**
  * Gets remote client IP
  *
  * @param boolean $safe
  * @return string Client IP address
  * @deprecated use $this->request->clientIp() from your,  controller instead.
  */
 public function getClientIP($safe = true)
 {
     return $this->request->clientIp($safe);
 }
 /**
  * Test the clientIp method.
  *
  * @return void
  */
 public function testclientIp()
 {
     $_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.5, 10.0.1.1, proxy.com';
     $_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2';
     $_SERVER['REMOTE_ADDR'] = '192.168.1.3';
     $request = new CakeRequest('some/path');
     $this->assertEquals('192.168.1.5', $request->clientIp(false));
     $this->assertEquals('192.168.1.2', $request->clientIp());
     unset($_SERVER['HTTP_X_FORWARDED_FOR']);
     $this->assertEquals('192.168.1.2', $request->clientIp());
     unset($_SERVER['HTTP_CLIENT_IP']);
     $this->assertEquals('192.168.1.3', $request->clientIp());
     $_SERVER['HTTP_CLIENTADDRESS'] = '10.0.1.2, 10.0.1.1';
     $this->assertEquals('10.0.1.2', $request->clientIp());
 }
 /**
  * Unused since this a stateless authentication
  *
  * @param CakeRequest  $request  The request object
  * @param CakeResponse $response response object.
  *
  * @return mixed.  Always false
  */
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     //handle json post
     $userLoginInfo = json_decode(utf8_encode(trim(file_get_contents('php://input'))), TRUE);
     if (empty($userLoginInfo) || !isset($userLoginInfo['data']) || !isset($userLoginInfo['data']['username']) || !isset($userLoginInfo['data']['password'])) {
         throw new ApiAuthenticateException(ErrorConstants::$API_MESSAGES['lOGIN']['403'], 403);
     }
     $userModel = $this->settings['userModel'];
     $tokenModel = $this->settings['tokenModel'];
     list($plugin, $model) = pluginSplit($userModel);
     $fields = $this->settings['fields'];
     $conditions = array($model . '.' . $fields['username'] => $userLoginInfo['data']['username'], $model . '.' . $fields['password'] => Security::hash($userLoginInfo['data']['password'], 'sha256', TRUE));
     if (!empty($this->settings['scope'])) {
         $conditions = array_merge($conditions, $this->settings['scope']);
     }
     $userModelObj = ClassRegistry::init($userModel);
     $userQueryResult = $userModelObj->find('first', array('conditions' => $conditions, 'recursive' => (int) $this->settings['recursive'], 'contain' => $this->settings['contain']));
     if (empty($userQueryResult) || empty($userQueryResult[$model])) {
         return FALSE;
     }
     $tokenModelObj = ClassRegistry::init($tokenModel);
     $tokenEndcodeData = $userQueryResult[$model];
     unset($tokenEndcodeData[$fields['password']]);
     unset($tokenEndcodeData['display_name']);
     unset($tokenEndcodeData['created']);
     unset($tokenEndcodeData['modified']);
     $tokenData = array("user_id" => $userQueryResult[$model][$userModelObj->primaryKey], "token" => JWT::encode($tokenEndcodeData, Configure::read('Security.salt')), "client_ip" => $request->clientIp(), "expired" => $this->currentDateTime->add(new DateInterval('P1D'))->getTimestamp());
     if (!$tokenModelObj->save($tokenData)) {
         return FALSE;
     }
     $user = $userQueryResult[$model];
     $user['api_access_key'] = $tokenData['token'];
     unset($userQueryResult[$model]);
     return array_merge($user, $userQueryResult);
 }