Sinatra on Thin: How to hide or change HTTP 'Server' response header - sinatra

What is the cleanest way to do this? Some Rack middleware? I tried to modify env['SERVER_SOFTWARE'] but I still get in response:
Server: thin 1.3.1 codename Triple Espresso
How to change the value of that header, or remove it completetly from response?
EDIT
Another try:
before do
headers 'Server' => 'ipm'
end
after do
headers 'Server' => 'ipm'
end
But still no changes.

This works here:
require 'sinatra'
get '/' do
[200, {'Server' => 'My Server'}, 'contents']
end
If you want to do it for all requests:
class ChangeServer
def initialize(app)
#app = app
end
def call(env)
res = #app.call(env)
res[1]['Server'] = 'My server'
return res
end
end
And then you use ChangeServer in your app.

Related

base_uri not being based from guzzle client instantiation

I'm using lumen trying to set up simple api requests via guzzle.
The problem is the base_uri parameter doesn't appear to be passed correctly on the initial new Client().
Simplified example:
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://siteurl.com/api/v2'
]);
Then calling the api via get
$res = $client->get('orders', [
'query' => [
'status' => 'completed'
]
]);
does not work. I've been careful not to use absolute urls like /orders. If I bypass base_uri entirely and just add it on the get method $client->get('https://siteurl.com/api/v2/orders'), it works.
I'm using:
"laravel/lumen-framework": "5.0.*",
"guzzlehttp/guzzle": "^6.0"
*Follow-up:
I added the debug flag so I could compare the headers, and the noticable difference is in the get request line.
Absolute url in the get method (bypassing base_uri):
GET /api/v2/orders?status=completed HTTP/1.1
Using base_uri (version is being stripped):
GET /api/orders?status=completed HTTP/1.1
You need to terminate your base_uri with a forward slash /
E.g.,
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://siteurl.com/api/v2/'
]);
Edit: Note that base_uri is for Guzzle 6+, whereas previous versions used base_url.

How to set 'grant type' with lwp

I'm trying to connect to a server with LWP::UserAgent. I have succeeded to do anonymous searches with LWP::UserAgent on that same server, but now I have to "secret" stuff and that requires to use authentication on that server. I have used the code:
my $ua = LWP::UserAgent->new;
$ua->default_header('Content-Type' => "application/x-www-form-urlencoded");
$ua->default_header('Authorization' => "Basic ".$Authent);
my $resp = $ua->post($uri);
The server reponds: error 400, Required param: grant_type
So, how do I set the grand type parameter with LWP?
I have not found any page concerning the grand type problem.
I have tried also:
$ua->default_header('grant_type' => "client_credentials");
and
my $resp = $ua->post($uri, grant_type => "client_credentials");
All three gives exactly the same error message.
I have no idea how to get things work.
TA-DAA! I found an answer.
The grant_type is not header stuff, it belongs to body.
So, the working way to do this is:
$ua->default_header('Content-Type' => "application/x-www-form-urlencoded");
$ua->default_header('Authorization' => "Basic ".$Authent);
my $resp = $ua->post($uri, Content => ['grant_type' => "client_credentials"]);
Thanks anyway!

Linkedin OAuth and Zend retrieving Acces Token returns 'Error in HTTP request'

Answer + new question
I found out that the code below works just fine on a LIVE server. LinkedIN blocked all requests from localhost.
That established; Does anybody know how to test an application from localhost with LinkedIN OAuth? Because doing this on a live server sucks!
Old Question
I'm trying to connect with Zend_OAuth to LinkedIN. This code used to work, but now it returns an error in http request while I'm trying to retrieve an access token.
Tried checking the LinkedIN api, but the code still seems valid. Tried several scripts but all with the same result.
The config is setup in the preDispatch of my controller
$this->configLinkedin = array(
'version' => '1.0',
'siteUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'callbackUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'XXX',
'consumerSecret' => 'XXX'
);
And the code in the action to connect to linkedIN is
$this->consumer = new Zend_Oauth_Consumer($this->configLinkedin);
if(!empty($_GET) && isset($_SESSION['LINKEDIN_REQUEST_TOKEN']))
{
$token = $this->consumer->getAccessToken($_GET, unserialize($_SESSION['LINKEDIN_REQUEST_TOKEN']));
// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($this->configLinkedin);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
$this->NewsService->TokenSocialMedia(
$token,
'linkedin',
serialize($response->getBody())
);
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = null;
$this->_helper->flashMessenger(array('message' => $this->view->translate('The CMS is successfully connected to your linkedin account'), 'status' => 'success'));
$this->_helper->redirector('settings#settingSocial', 'index');
}
else
{
$token = $this->consumer->getRequestToken();
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = serialize($token);
$this->consumer->redirect();
}
What am I missing or doing wrong? I use a similair setup for Twitter and that works fine.
UPDATE 20 September 211
I found out that this rule is returning the error:
$token = $this->consumer->getRequestToken();
I'm still clueless why, and reading the linkedin api doesn't help a bit. Will keep you posted.
I got similar problem and after adding openssl extension it was solved
try adding to php.ini this line:
extension=php_openssl.dll
I got the same issue, try to turn off ssl before asking the new consumer :
$httpConfig = array(
'adapter' => 'Zend\Http\Client\Adapter\Socket',
'sslverifypeer' => false
);
$httpClient = new HTTPClient(null, $httpConfig);
OAuth::setHttpClient($httpClient);

Set Timeout SOAP client (Zend Framework)

I'm requesting a webservice using SOAP for which I need to set a request timeout.
new Zend_Soap_Client(http://www.aaa.com/ws/Estimate.asmx?wsdl",
array('encoding' => 'UTF-8');
I have also tried passing 'connection_timeout'=>100 but it seems like "unknow SOAP client option". Please suggest a way I can set the set timeout.
Thanks
I found a solution to set the timeout with Zend_Framework:
If you have your SoapClient-Object like this:
$client = new Zend_Soap_Client(http://www.aaa.com/ws/Estimate.asmx?wsdl", array('encoding' => 'UTF-8');
You can set the timeout for HTTP-Requests. The default timeout in PHP is 30 seconds. With the following code you can e.g. set it to 1 minute.
$context = stream_context_create(
array(
'http' => array(
'timeout' => 1000
)
)
);
$client->setStreamContext($context);
Found on downlifesroad.com
Connection timeout option is not supported, the code is present in Zend_Soap_Client but commented
// Not used now
// case 'connection_timeout':
// $this->_connection_timeout = $value;
// break;
ini_set('default_socket_timeout',$seconds);
Here is a suggested solution using ZendHttpClient and Zend_Http_Client_Adapter_Curl.
$client = new Zend_Http_Client($location);
$adapter = new Zend_Http_Client_Adapter_Curl();
$client->setAdapter($adapter);
$adapter->setCurlOption(CURLOPT_TIMEOUT, $this->_timeout);
$client->setMethod(Zend_Http_Client::POST);
$client->setHeaders('Content-Type', $version == 2 ?
'application/soap+xml' : 'text/xml');
$client->setHeaders('SOAPAction', $action);
The idea is that you send an http request with the SOAP envelope as string at the request.
Full gist code here
I solved this issue by using native PHP SoapClient class...
$client = new SoapClient($url,
array(
'connection_timeout'=>'30'
));
$response = $client->wsMethod(array
('param'=>'value));
You can define the whole duration limit using
ini_set('default_socket_timeout', '30');
Before calling it.
Works like a charm... ;)

Image Upload with Zend_Service_Nirvanix

I can't seem to upload an image using Zend_Service_Nirvanix. Is it even possible?
I have a feeling that my problem has something to do with not being able to figure out how to set the UploadHost on the Transfer Service.
Any help is greatly appreciated! My deadline is July 16th!
Here is my code:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$options = array('sizeBytes' => filesize($source));
$storageNode = $NSImfs->getStorageNode($options);
$NSTransfer = $nirvanix->getService('Transfer');
$options = array('uploadToken' => $storageNode->getStorageNode->UploadToken,
'path' => $original,
'fileData' => file_get_contents($source));
$result = $NSTransfer->uploadFile($options);
Here is the error I keep getting:
Zend_Service_Nirvanix_Exception: XML
could not be parsed from response:
Server Error in '/' Application. The
resource cannot be found. Description:
HTTP 404. The resource you are looking
for (or one of its dependencies) could
have been removed, had its name
changed, or is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/ws/Transfer/UploadFile.ashx
in
/Applications/MAMP/bin/php5/lib/php/Zend/Service/Nirvanix/Response.php
on line 119
You're getting a 404?
Have you checked for an updated version of that library?
Try going into the libray and changing UploadFile.ashx to UploadFile.aspx. I don't think ashx is not a standard extension.
Maybe that will fix it.
There's a commercial upload tool from Aurigma that has support for file and image upload to Nirvanix. Here's the link (see Uploading to Nirvanix section there) to the help topic to check.
To do a local upload (rather than a web upload via the browser) you just have to call the putContents method passing the files data.
Example:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$response = $NSImfs->putContents($destination_file_and_path,
file_get_contents($source_file));
if($response->ResponseCode != 0)
{
echo 'Fail!';
}
You would only call GetStorageNode if you want to generate a token to pass a browser the upload token.