/** * Performs an authentication attempt * * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed * @return Zend_Auth_Result */ public function authenticate() { if (empty($this->_request) || empty($this->_response)) { require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling ' . 'authenticate()'); } $header = $this->_request->getHeader('Authorization'); if (empty($header)) { return $this->_challengeClient(); } $parts = array_filter(explode(' ', $header)); if ($parts < 2) { return $this->_challengeClient(); } $scheme = array_shift($parts); $creds = implode(' ', $parts); if (empty($this->_schemes[$scheme])) { throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme (' . $scheme . ')'); } $result = call_user_func($this->_schemes[$scheme], trim($creds), $this->_request); if (empty($result)) { \App::log()->debug("Authentication failed using scheme: " . @$this->_schemes[$scheme]); \App::log()->debug("Authentication failed using creds: " . @$creds); return $this->_challengeClient(); } else { if ($result instanceof Zend_Auth_Result) { return $result; } else { return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $result); } } }
/** * Get api id from TransactionInfo header * * @return string */ protected function _getAuthToken() { $token = $this->_request->getHeader(static::HEADER); if (empty($token)) { throw new Zend_Auth_Adapter_Exception("M2M-3rdparty-token header is missing"); } return $token; }
public function testGetHeaderThrowsExceptionWithNoInput() { try { // Suppressing warning $header = @$this->_request->getHeader(); $this->fail('getHeader() should fail with no arguments)'); } catch (Exception $e) { // success } }
/** * {@inheritdoc} * * Added CGI environment support. */ public function getHeader($header) { $headerValue = parent::getHeader($header); if ($headerValue == false) { /** Workaround for php-fpm environment */ $header = strtoupper(str_replace('-', '_', $header)); if (isset($_SERVER[$header]) && in_array($header, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $headerValue = $_SERVER[$header]; } } return $headerValue; }
protected function _getAccessToken() { $request = new Zend_Controller_Request_Http(); $authorization = $request->getHeader('authorization'); if ($authorization) { $token = explode(' ', $authorization); $token = $token[1]; if (isset($token) && is_string($token)) { return $token; } Mage::throwException($this->__('Authentication header format is invalid.')); } Mage::throwException($this->__('Authentication header is absent.')); }
/** * Get api id from TransactionInfo header * * @return string */ protected function _getApiId() { // Get the API Id and try to obtain organization Id mapping $transactionInfo = $this->_request->getHeader('TransactionInfo'); if (empty($transactionInfo)) { throw new Zend_Auth_Adapter_Exception("TransactionInfo header is missing"); } if (!preg_match('/appid=\\"(?P<apiId>[^\\"]+)\\"/', $transactionInfo, $matches)) { throw new Zend_Auth_Adapter_Exception("TransactionInfo appid parameter is missing"); } $apiId = (string) $matches['apiId']; if (empty($apiId)) { throw new Zend_Auth_Adapter_Exception("TransactionInfo appid parameter is empty"); } return $apiId; }
/** * Autoriza el servicio */ protected function _chequearKey() { $request = new Request(); $parametros = $request->getParametros(); $key_public = $this->_zend_request->getHeader("X-Public"); $hash_private = $this->_zend_request->getHeader("X-Hash"); $content = json_encode($parametros); $servicio = $this->_DAOService->getByPublicKey($key_public); if (!is_null($servicio)) { $hash = hash_hmac('sha256', $content, $servicio->key_private); if ($hash != $hash_private) { $this->_autorizado = false; } } else { $this->_autorizado = false; } }
/** * Match the user submitted path. * * Via Omeka_Application_Resource_Router, this is the only available route * for API requests. * * @throws Omeka_Controller_Exception_Api * @param Zend_Controller_Request_Http $request * @return array|false */ public function match($request) { $front = Zend_Controller_Front::getInstance(); // Extract URL components. preg_match('#^/api/([a-z_]+)(.+)?$#', $request->getPathInfo(), $matches); if (!$matches) { return false; } // Throw an error if a key was given but there is no user identity. if (isset($_GET['key']) && !Zend_Auth::getInstance()->hasIdentity()) { throw new Omeka_Controller_Exception_Api('Invalid key.', 403); } // The API must be enabled. if (!get_option('api_enable')) { throw new Omeka_Controller_Exception_Api('API is disabled', 403); } $resource = $matches[1]; // Extract path parameters. Not to be confused with request parameters. $params = array(); if (isset($matches[2]) && '/' != $matches[2]) { $params = explode('/', $matches[2]); array_shift($params); } // Allow clients to override the HTTP method. This is helpful if the // server is configured to reject certain methods. if (!($method = $request->getHeader('X-HTTP-Method-Override'))) { $method = $request->getMethod(); } // Get all available API resources. $apiResources = $front->getParam('api_resources'); // Get and validate resource, record_type, module, controller, and action. $resource = $this->_getResource($resource, $apiResources); $recordType = $this->_getRecordType($resource, $apiResources); $module = $this->_getModule($resource, $apiResources); $controller = $this->_getController($resource, $apiResources); $action = $this->_getAction($method, $params, $resource, $apiResources); // Validate the GET parameters. $this->_validateParams($action, $resource, $apiResources); // Set the route variables. Namespace the API parameters to prevent // collisions with the request parameters. $routeVars = array('module' => $module, 'controller' => $controller, 'action' => $action, 'api_resource' => $resource, 'api_record_type' => $recordType, 'api_params' => $params); return $routeVars; }
/** * Return the value of the given HTTP header. Pass the header name as the * plain, HTTP-specified header name. Ex.: Ask for 'Accept' to get the * Accept header, 'Accept-Encoding' to get the Accept-Encoding header. * * @param string $header HTTP header name * @return string|false HTTP header value, or false if not found * @throws Zend_Controller_Request_Exception */ public function getHeader($header) { $temp = strtoupper(str_replace('-', '_', $header)); if (isset($_SERVER['HTTP_' . $temp])) { return $_SERVER['HTTP_' . $temp]; } if (strpos($temp, 'CONTENT_') === 0 && isset($_SERVER[$temp])) { return $_SERVER[$temp]; } return parent::getHeader($header); }
/** * @group ZF-10577 */ public function testGetHeaderWithEmptyValueReturnsEmptyString() { $_SERVER['HTTP_X_FOO'] = ''; $this->assertSame('', $this->_request->getHeader('X-Foo')); }
/** * Отдать файл в поток * * @param Zend_Controller_Request_Http $request Объект запроса для поддержки докачки и кеша 304 * @param string $headersFileName Отображаемое имя файла или null - оставить оргинальное имя * @param string $mime MIME-тип или null - определить по расширению * @param bool $isAttachment Как вложение - отобразит в браузере окно сохранения файла * @param bool $sendMTime Отдавать дату последней модификации * @return void */ public function output($request = null, $headersFileName = null, $mime = 'application/octet-stream', $isAttachment = true, $sendMTime = false) { set_time_limit(0); $path = $this->getFullPath(); $fsize = $this->getSize(); $fd = @fopen($path, 'rb'); if ($fsize && $request instanceof Zend_Controller_Request_Http && ($range = $request->getServer('HTTP_RANGE'))) { $range = str_replace('bytes=', '', $range); $t = explode('-', $range); $range = @$t[0] ?: 0; //$end = @$t[1] ?: $fsize; if (!empty($range)) { fseek($fd, $range); } } else { $range = 0; } $protocol = 'HTTP/1.1'; if ($request instanceof Zend_Controller_Request_Http && $request->getServer('SERVER_PROTOCOL')) { $protocol = $request->getServer('SERVER_PROTOCOL'); } //ob_end_clean(); $mtime = false; if ($sendMTime) { $mtime = $this->getModifiedTime(); } //$headersFileNameConv = iconv('CP1251', 'UTF-8', $headersFileName ?: $this->getBaseName()); $headersFileNameConv = $headersFileName ?: $this->getBaseName(); if ($isAttachment) { header('Content-Disposition: attachment; filename="' . $headersFileNameConv . '"'); } //header('Content-Disposition: ' . ($isAttachment ? 'attachment' : 'inline') . '; filename="' . $headersFileNameConv . '"'); if (!$mime) { $mime = $this->getFileMimeTypeByExt(); } header('Content-Disposition: attachment; filename="' . $headersFileNameConv . '"'); header('Content-Type: ' . $mime . '; name="' . $headersFileNameConv . '"'); if ($mtime) { $ifModSince = strtotime($request->getHeader('If-Modified-Since')); if ($ifModSince >= $mtime) { header($protocol . ' 304 Not Modified'); exit; } } if ($range) { header($protocol . ' 206 Partial Content'); } else { header($protocol . ' 200 OK'); } if ($mtime) { header('Last-Modified: ' . date('D, d M Y H:i:s T', $mtime)); } header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); if ($fsize !== false) { if ($range) { header('Content-Length: ' . ($fsize - $range)); header("Content-Range: bytes " . $range . "-" . ($fsize - 1) . '/' . $fsize); } else { header('Content-Length: ' . $fsize); } } ob_end_clean(); flush(); //fpassthru($fd); while (!feof($fd) && !connection_status()) { echo fread($fd, 1048576); flush(); } fclose($fd); exit; /* ob_end_clean(); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . iconv('CP1251', 'UTF-8', basename($path)) . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); $fsize = App_File::getSize($path, true); if ($fsize !== false) { header('Content-Length: ' . $fsize); } ob_clean(); flush(); readfile($path); exit; */ }
public function __construct(\Zend_Controller_Request_Http $request) { $this->request = $request; $this->header = new Header($request->getHeader('authorization')); }
/** * Retrieve protocol and request parameters from request object * * @param string $authHeaderValue * @link http://tools.ietf.org/html/rfc5849#section-3.5 * @return Mage_Oauth_Model_Server */ protected function _fetchParams($authHeaderValue = null) { if (is_null($authHeaderValue)) { $authHeaderValue = $this->_request->getHeader('Authorization'); } if ($authHeaderValue && 'oauth' === strtolower(substr($authHeaderValue, 0, 5))) { $authHeaderValue = substr($authHeaderValue, 6); // ignore 'OAuth ' at the beginning foreach (explode(',', $authHeaderValue) as $paramStr) { $nameAndValue = explode('=', trim($paramStr), 2); if (count($nameAndValue) < 2) { continue; } if ($this->_isProtocolParameter($nameAndValue[0])) { $this->_protocolParams[rawurldecode($nameAndValue[0])] = rawurldecode(trim($nameAndValue[1], '"')); } } } $contentTypeHeader = $this->_request->getHeader(Zend_Http_Client::CONTENT_TYPE); if ($contentTypeHeader && 0 === strpos($contentTypeHeader, Zend_Http_Client::ENC_URLENCODED)) { $protocolParamsNotSet = !$this->_protocolParams; parse_str($this->_request->getRawBody(), $bodyParams); foreach ($bodyParams as $bodyParamName => $bodyParamValue) { if (!$this->_isProtocolParameter($bodyParamName)) { $this->_params[$bodyParamName] = $bodyParamValue; } elseif ($protocolParamsNotSet) { $this->_protocolParams[$bodyParamName] = $bodyParamValue; } } } $protocolParamsNotSet = !$this->_protocolParams; $url = $this->_request->getScheme() . '://' . $this->_request->getHttpHost() . $this->_request->getRequestUri(); if ($queryString = Zend_Uri_Http::fromString($url)->getQuery()) { foreach (explode('&', $queryString) as $paramToValue) { $paramData = explode('=', $paramToValue); if (2 === count($paramData) && !$this->_isProtocolParameter($paramData[0])) { $this->_params[rawurldecode($paramData[0])] = rawurldecode($paramData[1]); } } } if ($protocolParamsNotSet) { $this->_fetchProtocolParamsFromQuery(); } return $this; }
public static function initiate($namespace) { $request = new Zend_Controller_Request_Http(); $sso = false; if ($request->getPathInfo() == '/sso') { $sso = true; if (isset($_GET['sid'])) { Zend_Session::setId($_GET['sid']); $referer = $request->getHeader('Referer'); } elseif (isset($_GET['csid']) && !Zend_Session::sessionExists()) { Zend_Session::setId($_GET['csid']); $dieGotIt = true; } } Zend_Registry::set('csession', new Zend_Session_Namespace('cosmosclient')); Zend_Registry::set('cartsess', new Zend_Session_Namespace($namespace)); $sessionID = Zend_Session::getId(); if (isset($dieGotIt) && $dieGotIt == true) { die("// Got it: {$sessionID}"); } // Invalid session ID somehow.... Give them one. if (Zend_Session::sessionExists() && !Zend_Registry::get('csession')->sessionExists) { unset($_COOKIE[session_name()]); Zend_Session::regenerateId(); Zend_Registry::get('csession')->sessionExists = true; } if (Zend_Session::sessionExists()) { if (isset($referer)) { header("Location: {$referer}"); die; } elseif ($sso == true && isset($_GET['csid'])) { if ($sessionID == $_GET['csid']) { die('// No SID update needed.'); } $cookieName = session_name(); $js = <<<js window.stop(); function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); } function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } setCookie("{$cookieName}","{$sessionID}"); cookieValue = getCookie("{$cookieName}"); if(cookieValue == "{$sessionID}"){ location.reload(true); } else { window.location = '/sso?sid={$sessionID}'; } js; die($js); } } else { Zend_Registry::get('csession')->sessionExists = true; } }
/** * Process HTTP request object and prepare for token validation * * @param \Zend_Controller_Request_Http $httpRequest * @return array */ public function prepareRequest($httpRequest) { $oauthParams = $this->_processRequest($httpRequest->getHeader('Authorization'), $httpRequest->getHeader(\Zend_Http_Client::CONTENT_TYPE), $httpRequest->getRawBody(), $this->getRequestUrl($httpRequest)); return $oauthParams; }
/** * Parse Digest Authorization header * * @param string $header Client's Authorization: HTTP header * @return array|false Data elements from header, or false if any part of * the header is invalid */ protected function _parseDigestAuth($header) { $temp = null; $data = array(); // See ZF-1052. Detect invalid usernames instead of just returning a // 400 code. $ret = preg_match('/username="******"]+)"/', $header, $temp); if (!$ret || empty($temp[1]) || !ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { $data['username'] = '******'; } else { $data['username'] = $temp[1]; } $temp = null; $ret = preg_match('/realm="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { return false; } else { $data['realm'] = $temp[1]; } $temp = null; $ret = preg_match('/nonce="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_xdigit($temp[1])) { return false; } else { $data['nonce'] = $temp[1]; } $temp = null; $ret = preg_match('/uri="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } // Section 3.2.2.5 in RFC 2617 says the authenticating server must // verify that the URI field in the Authorization header is for the // same resource requested in the Request Line. $rUri = @parse_url($this->_request->getRequestUri()); $cUri = @parse_url($temp[1]); if (false === $rUri || false === $cUri) { return false; } else { // Make sure the path portion of both URIs is the same if ($rUri['path'] != $cUri['path']) { return false; } // Section 3.2.2.5 seems to suggest that the value of the URI // Authorization field should be made into an absolute URI if the // Request URI is absolute, but it's vague, and that's a bunch of // code I don't want to write right now. $data['uri'] = $temp[1]; } $temp = null; $ret = preg_match('/response="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { return false; } else { $data['response'] = $temp[1]; } $temp = null; // The spec says this should default to MD5 if omitted. OK, so how does // that square with the algo we send out in the WWW-Authenticate header, // if it can easily be overridden by the client? $ret = preg_match('/algorithm="?(' . $this->_algo . ')"?/', $header, $temp); if ($ret && !empty($temp[1]) && in_array($temp[1], $this->_supportedAlgos)) { $data['algorithm'] = $temp[1]; } else { $data['algorithm'] = 'MD5'; // = $this->_algo; ? } $temp = null; // Not optional in this implementation $ret = preg_match('/cnonce="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_print($temp[1])) { return false; } else { $data['cnonce'] = $temp[1]; } $temp = null; // If the server sent an opaque value, the client must send it back if ($this->_useOpaque) { $ret = preg_match('/opaque="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { // Big surprise: IE isn't RFC 2617-compliant. if (false !== strpos($this->_request->getHeader('User-Agent'), 'MSIE')) { $temp[1] = ''; $this->_ieNoOpaque = true; } else { return false; } } // This implementation only sends MD5 hex strings in the opaque value if (!$this->_ieNoOpaque && (32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) { return false; } else { $data['opaque'] = $temp[1]; } $temp = null; } // Not optional in this implementation, but must be one of the supported // qop types $ret = preg_match('/qop="?(' . implode('|', $this->_supportedQops) . ')"?/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!in_array($temp[1], $this->_supportedQops)) { return false; } else { $data['qop'] = $temp[1]; } $temp = null; // Not optional in this implementation. The spec says this value // shouldn't be a quoted string, but apparently some implementations // quote it anyway. See ZF-1544. $ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { return false; } else { $data['nc'] = $temp[1]; } $temp = null; return $data; }
* For handling the HTTP connection through the cURL * @see Zend_Http_Client_Adapter_Curl */ require_once 'Zend/Http/Client/Adapter/Curl.php'; $request = new Zend_Controller_Request_Http(); iconv_set_encoding('input_encoding', 'UTF-8'); iconv_set_encoding('output_encoding', 'UTF-8'); iconv_set_encoding('internal_encoding', 'UTF-8'); $http = new Zend_Http_Client(); $http->setAdapter('Zend_Http_Client_Adapter_Curl'); if ($http->getUri() === null) { $http->setUri($proxyingUrl . '/' . $request->getParam('proxyingUri')); unset($_GET['proxyingUri']); } $headers = array(); $headers[] = 'Accept-encoding: ' . $request->getHeader('Accept-encoding'); $headers[] = 'User-Agent: ' . $request->getHeader('User-Agent'); $headers[] = 'Accept: ' . $request->getHeader('Accept'); $headers[] = 'Cache-Control: ' . $request->getHeader('Cache-Control'); $headers[] = 'Connection: ' . $request->getHeader('Connection'); $headers[] = 'Keep-Alive: ' . $request->getHeader('Keep-Alive'); $headers[] = 'Accept-Charset: ' . $request->getHeader('Accept-Charset'); $headers[] = 'Accept-Language: ' . $request->getHeader('Accept-Language'); $http->setHeaders($headers); $request->getHeader('Content-Type') == 'application/x-www-form-urlencoded' ? $http->setEncType(Zend_Http_Client::ENC_URLENCODED) : $http->setEncType(Zend_Http_Client::ENC_FORMDATA); if ($request->getMethod() == 'PUT') { $fh = fopen('php://input', 'r'); if (!$fh) { echo 'Can\'t load PUT data'; die; }