Why my postman hang forever with with GuzzleHttp\Client request? - lumen

Working with lumen-passport in lumen 8 I
got client_secret and client_id and make a request with GuzzleHttp\Client and my postman hang forever:
My postman : https://imgur.com/a/LbtUIVi
In routes/web.php :
$router->group(['prefix'=>'api/v1'], function() use($router){
$router->post('/register','AuthController#register');
$router->post('/login', 'AuthController#login');
In my control :
$client = new Client();
try {
$clientResponse = $client->post( 'http://localhost:8000/api/v1/oauth/token' /* config('service.passport.login_endpoint' ) */ , [
"form_params" => [
"client_secret" => 'DfiXey63ABDjgX7upuNaGmGvvASzhGq9kjZTV9nm', //config('service.passport.client_secret'),
"client_id" => 2, //config('service.passport.client_id'),
"grant_type" => "client_credentials",
"username" => $request->email,
"password" => $request->password
]
]);
\Log::info( varDump(-3, ' -3 login $clientResponse::') );
return $clientResponse;
} catch (BadResponseException $e) {
\Log::info( varDump(-4, ' -4 login ::') );
\Log::info( varDump($e->getMessage(), ' -4 login $e->getMessage()::') );
return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
}
In bootstrap/app.php I have :
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
//$app->configure('app');
$app->register(App\Providers\AppServiceProvider::class);
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
//$app->configure('app');
$app->register(App\Providers\AppServiceProvider::class);
// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
...
\Dusterio\LumenPassport\LumenPassport::routes($app, ['prefix' => 'api/v1/oauth']);
Under console I see :
ProjectName$ php -S localhost:8000 -t public
[Tue Jun 1 07:27:23 2021] PHP 7.4.18 Development Server (http://localhost:8000) started
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 Accepted
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45944 Accepted
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 [200]: GET /
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 Closing
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45948 Accepted
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45944 [200]: GET /
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45944 Closing
[Tue Jun 1 07:27:41 2021] 127.0.0.1:45956 Accepted
I tried to debug guzzle source and found that it hang in file /vendor/guzzlehttp/guzzle/src/Client.php,
in method:
private function transfer(RequestInterface $request, array $options): PromiseInterface
{
$request = $this->applyOptions($request, $options);
/** #var HandlerStack $handler */
$handler = $options['handler'];
\Log::info( varDump(-21, ' -21 transfer::') );
\Log::info( varDump($handler, ' $handler transfer::') );
try {
return P\Create::promiseFor($handler($request, $options)); // I suppose it hang forever here
} catch (\Exception $e) {
return P\Create::rejectionFor($e);
}
}
Checking content of $handler in log file I see :
[2021-06-01 04:54:47] local.INFO: (Object of GuzzleHttp\HandlerStack) : $handler transfer:: : Array
(
[ GuzzleHttp\HandlerStack handler] => Closure Object
(
[static] => Array
(
[default] => Closure Object
(
[static] => Array
(
[default] => GuzzleHttp\Handler\CurlMultiHandler Object
(
[factory:GuzzleHttp\Handler\CurlMultiHandler:private] => GuzzleHttp\Handler\CurlFactory Object
(
[handles:GuzzleHttp\Handler\CurlFactory:private] => Array
(
)
[maxHandles:GuzzleHttp\Handler\CurlFactory:private] => 50
)
[selectTimeout:GuzzleHttp\Handler\CurlMultiHandler:private] => 1
[active:GuzzleHttp\Handler\CurlMultiHandler:private] =>
[handles:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
[delays:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
[options:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
)
[sync] => GuzzleHttp\Handler\CurlHandler Object
(
[factory:GuzzleHttp\Handler\CurlHandler:private] => GuzzleHttp\Handler\CurlFactory Object
(
[handles:GuzzleHttp\Handler\CurlFactory:private] => Array
(
)
[maxHandles:GuzzleHttp\Handler\CurlFactory:private] => 3
)
)
)
[parameter] => Array
(
[$request] => <required>
[$options] => <required>
)
)
[streaming] => GuzzleHttp\Handler\StreamHandler Object
(
[lastHeaders:GuzzleHttp\Handler\StreamHandler:private] => Array
(
)
)
)
[parameter] => Array
(
[$request] => <required>
[$options] => <required>
)
)
[ GuzzleHttp\HandlerStack stack] => Array
(
[0] => Array
(
[0] => Closure Object
(
[static] => Array
(
[bodySummarizer] =>
)
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => http_errors
)
[1] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => allow_redirects
)
[2] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => cookies
)
[3] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => prepare_body
)
)
[ GuzzleHttp\HandlerStack cached] =>
)
Any idea what is wrong? Local server misconfig ?
PHP 7.4.18 under kubuntu
"dusterio/lumen-passport": "^0.3.4",
"guzzlehttp/guzzle": "^7.3",
"laravel/lumen-framework": "^8.0",
Thanks in advance!

I don't have so experience in lumen, but I am using in environment develop this solution without Guzzle.
public function login(Request $request){
$email = $request->email;
$password = $request->password;
//Check if field is not empty
if (empty($email) or empty($password)) {
return response()->json(['status' => 'error', 'message' => 'You must fill all fields']);
}
$user = User::where('email', '=', $email)->exists();
if ($user === false) {
return response()->json(['status' => 'error', 'message' => 'User doesnt exist']);
}
//$client = new \GuzzleHttp\Client();
try{
$tokenRequest = $request->create(
env('PASSPORT_LOGIN_ENDPOINT'),
'POST'
);
$tokenRequest->request->add([
"grant_type" => "password",
"username" => $request->email,
"password" => $request->password,
"client_id" => env('PASSPORT_CLIENT_ID'),
"client_secret" => env('PASSPORT_CLIENT_SECRET'),
]);
$response = app()->handle($tokenRequest);
return $response;
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
}
}

Related

How to connect to suite CRM REST API using Guzzle

I'm trying to connect to suite CRM REST API using Guzzle
$res = $client->request('GET','http://crm.demo.com/service/v4_1/rest.php/login', [ "auth" => [ 'myadmin', md5('mypswd') ]]);
print_r($res);
The result I'm getting is this
GuzzleHttp\Psr7\Response Object
(
[reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK
[statusCode:GuzzleHttp\Psr7\Response:private] => 200
[headers:GuzzleHttp\Psr7\Response:private] => Array
(
[Date] => Array
(
[0] => Mon, 03 Apr 2017 06:26:17 GMT
)
[Content-Type] => Array
(
[0] => text/html; charset=UTF-8
)
[Transfer-Encoding] => Array
(
[0] => chunked
)
[Connection] => Array
(
[0] => keep-alive
)
[Set-Cookie] => Array
(
[0] => __cfduid=daace974785b1e202e7535232346958d111491200776; expires=Tue, 03-Apr-18 06:26:16 GMT; path=/; domain=.demo.com; HttpOnly
)
[X-Powered-By] => Array
(
[0] => PHP/5.4.16
)
[X-Varnish] => Array
(
[0] => 2592144
)
[Age] => Array
(
[0] => 0
)
[Via] => Array
(
[0] => 1.1 varnish-v4
)
[Server] => Array
(
[0] => cloudflare-nginx
)
[CF-RAY] => Array
(
[0] => 3499f497d6bd17a4-SIN
)
)
[headerNames:GuzzleHttp\Psr7\Response:private] => Array
(
[date] => Date
[content-type] => Content-Type
[transfer-encoding] => Transfer-Encoding
[connection] => Connection
[set-cookie] => Set-Cookie
[x-powered-by] => X-Powered-By
[x-varnish] => X-Varnish
[age] => Age
[via] => Via
[server] => Server
[cf-ray] => CF-RAY
)
[protocol:GuzzleHttp\Psr7\Response:private] => 1.1
[stream:GuzzleHttp\Psr7\Response:private] => GuzzleHttp\Psr7\Stream Object
(
[stream:GuzzleHttp\Psr7\Stream:private] => Resource id #73
[size:GuzzleHttp\Psr7\Stream:private] =>
[seekable:GuzzleHttp\Psr7\Stream:private] => 1
[readable:GuzzleHttp\Psr7\Stream:private] => 1
[writable:GuzzleHttp\Psr7\Stream:private] => 1
[uri:GuzzleHttp\Psr7\Stream:private] => php://temp
[customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
(
)
)
)
Its showing the request was successful but I'm not getting the result. Is it really possible to connect it using Guzzle? Is there any other method to pass the login parameters?
I'm using CodeIgniter 3 and Guzzle to achieve this.
First of all, what's the issue? You code is correct, you get the response.
If you want to explore the response body, just do (string) $res->getBody() or $res->getBody()->getContents() (the body is a stream, as you can in your dump, so to get it as a string you have to do additional actions).
BTW, you are trying to access a site under CloudFlare, and usually it's not possible, because CloudFlare rejects robots. Try to get a different entry point (that is not under CloudFlare protection).

Yii2 Facebook Login issue: Error Validating Client Secret

I'm trying to activate Login via Facebook on my website that is built using Yii2 framework, but the Login is always failing, although the facebook app is authorizing the facebook account used in the login.
The response is always this error:
Request failed with code: 400, message: Error validating client
secret.
Im using yii2's authclient:
return [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'facebook.com/dialog/oauth',
//Prod
'clientId' => 'appidhere',
'clientSecret' => 'appsecrethere',
'scope' => 'email, user_friends, public_profile',
.....
The app id and app secret are correct, and the fb app settings are correct as well.
Here's what the request looks like:
yii\httpclient\Request Object ( [_url:yii\httpclient\Request:private]
=> graph.facebook.com/oauth/access_token [_fullUrl:yii\httpclient\Request:private] =>
[_method:yii\httpclient\Request:private] => POST
[_options:yii\httpclient\Request:private] => Array ( [userAgent] => My
Application OAuth 2.0 Client [timeout] => 30 [sslVerifyPeer] => )
[isPrepared:yii\httpclient\Request:private] => [client] =>
yii\httpclient\Client Object ( [baseUrl] => graph.facebook.com
[formatters] => Array ( ) [parsers] => Array ( ) [requestConfig] =>
Array ( ) [responseConfig] => Array ( ) [contentLoggingMaxSize] =>
2000 [_transport:yii\httpclient\Client:private] =>
yii\httpclient\StreamTransport [_events:yii\base\Component:private] =>
Array ( ) [_behaviors:yii\base\Component:private] => )
[_headers:yii\httpclient\Message:private] =>
[_cookies:yii\httpclient\Message:private] =>
[_content:yii\httpclient\Message:private] =>
[_data:yii\httpclient\Message:private] => Array ( [client_id] =>
realappidhere [client_secret] => ​realappsecrethere [code] =>
AQAr0KRC0m4V4lqD8LVcQLNjn76xkZS4skQYAvWf6O_DDeEclaj1LMQm_HoyCoZZezqDn7p9YfJm3qENabU8MKvmH1ffNJotMzgLW2XTbSqQEXlkg_sx7V-ibXRFagpfXTIqCp9Kr54O88bNYGikoOr4TM1ogGjViwS-qKLbvpR_vWgE_FPy9ecpgy86QOITpGrlVJaPAun2bzGaFXmU70Z4Kw3kBWUBPseWc_7ILGymZP-CIbRIIm_YZ8p7t9Vo7jZmieMSd-CMYfG0sgJcBjOgQNvsa3xtHNhPVa5BJNNTy89zulSpTAf3XB6HB_8eql0
[grant_type] => authorization_code [redirect_uri] =>
example.com/site/auth?role=influencer&authclient=facebook )
[_format:yii\httpclient\Message:private] =>
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => )
And the response is:
yii\httpclient\Response Object ( [client] => yii\httpclient\Client
Object ( [baseUrl] => graph.facebook.com [formatters] => Array
( [urlencoded] => yii\httpclient\UrlEncodedFormatter Object (
[encodingType] => 1 [charset] => ) ) [parsers] => Array ( )
[requestConfig] => Array ( ) [responseConfig] => Array ( )
[contentLoggingMaxSize] => 2000
[_transport:yii\httpclient\Client:private] =>
yii\httpclient\StreamTransport Object (
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => )
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => Array ( ) )
[_headers:yii\httpclient\Message:private] => Array ( [0] => HTTP/1.1
400 Bad Request [1] => WWW-Authenticate: OAuth "Facebook Platform"
"invalid_request" "Error validating client secret." [2] =>
Access-Control-Allow-Origin: * [3] => Pragma: no-cache [4] =>
Cache-Control: no-store [5] => facebook-api-version: v2.2 [6] =>
Expires: Sat, 01 Jan 2000 00:00:00 GMT [7] => Content-Type:
text/javascript; charset=UTF-8 [8] => x-fb-trace-id: Ek0PFIJ3B3N [9]
=> x-fb-rev: 2718923 [10] => Vary: Accept-Encoding [11] => X-FB-Debug: yaiIHJkwC4T3UZKrzXOJGJ2DmCTaDr8nIRB3jQnNeEiknx0Ph7i2IR5XmAbxpjM7cBhSEy44AcrglCYEdZEmeg==
[12] => Date: Sun, 04 Dec 2016 11:08:16 GMT [13] => Connection: close
[14] => Content-Length: 115 )
[_cookies:yii\httpclient\Message:private] =>
[_content:yii\httpclient\Message:private] =>
> {"error":{"message":"Error validating client
secret.","type":"OAuthException","code":1,"fbtrace_id":"Ek0PFIJ3B3N"}}
[_data:yii\httpclient\Message:private] =>
[_format:yii\httpclient\Message:private] =>
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => )
So any idea what's happening in there?
Note: I removed the http and https from the facebook links in the quotes because stackoverflow wouldn't let me post more than 2 links.
Try using Yii2 EAuth extension. This is the best extention which provides social login over 14 diff platforms with the easiest way.
reference url:
https://github.com/Nodge/yii2-eauth
demo url : http://nodge.ru/yii-eauth/demo2/login

Fetch protected data from object zend

I have response and I want to fetch referenceId from it, the response is
Application_Model_User Object
(
[_data:protected] => Array
(
[id] => 2
[email] => test#gmail.com
[password] => ef1dca60798e10a51e3b6201ae7c40fbe2a10887
[salt] => 87fc83906190d1e29b60c5813065af068e16459d
[name] => test
[creationDate] => 2011-07-05
[lastTimeStamp] => 2016-06-03 09:13:53
[enabled] => 1
[loginHash] =>
[employeeNumber] => 0007
[userphoneNumber] => +546546546545
[jobTitle] => Business Manager
)
[_references:protected] => Array
(
[role] => Array
(
[referenceClass] => Application_Model_Role
[referenceId] => 4
[mapperClass] => Application_Model_RoleMapper
[mapper] =>
)
[organisation] => Array
(
[referenceClass] => Application_Model_Organisation
[referenceId] => 1
[mapperClass] => Application_Model_OrganisationMapper
[mapper] =>
)
)
)
How can I fetch ?
In .phtml file in ajax after
success: function(response){
var data = jQuery.parseJSON(response);
for (var i in data)
{
var referenceId = data[i]['referenceId'];
}
}
You can use a getter. You can create a method to return the referenceId.

Illuminate returns results in JSON - why?

I'm using Illuminate to access my database
<body>
<?php
$edges = Edge::all();
foreach ($edges as $key => $value) {
print $value;
}
?>
</body>
browser returns:
{"childID":"A","parentID":"C","updated_at":null,"created_at":null}{"childID":"B","parentID":"E","updated_at":null,"created_at":null}{"childID":"C","parentID":"D","updated_at":null,"created_at":null}{"childID":"C","parentID":"F","updated_at":null,"created_at":null}{"childID":"Y","parentID":"Z","updated_at":"2014-08-07 10:26:54","created_at":"2014-08-07 10:26:54"}
What's odd or unexpected for me at least is that my results are returned in JSON. If you could
shine some light on this, i.e. why this might be, or the reason is...I'd be grateful.
If I dump the results in the browser with:
<?php
print '<pre>';print_r($edges);
?>
produces:
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => Edge Object
(
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[childID] => A
[parentID] => C
[updated_at] =>
[created_at] =>
)
[original:protected] => Array
(
[childID] => A
[parentID] => C
[updated_at] =>
[created_at] =>
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
[1] => Edge Object
(...)
...
)
In terms of the front-end results - I'm really only interested in the:
[childID] => A
[parentID] => C
[updated_at] =>
[created_at] =>
part of the object; only NOT in JSON; in plain text.

Post custom actions to timeline with publish_stream permission?

I'm trying the following to post custom action on to my timeline. The same effect has been achieved with the Graph API Explorer.
$facebook = new Facebook(array('appId' => '123456789',
'secret' => '123456789',
'cookie' => true));
$access_token = $facebook->getAccessToken();
if($access_token != "")
{
$user = $facebook->getUser();
if($user != 0)
{
$queries = array(array("method" => "POST", "relative_url" => "/me/namespace:action?object=http://www.mysite.com/url/parameters"));
try
{
$postResponseA = $facebook->api("?batch=".json_encode($queries), "POST");
} catch (FacebookApiException $e)
{
echo 'AF error: '.$e;
}
}
}
No errors are thrown. Nothing is ever posted though.
print_r($postResponseA) shows the following:
Array ( [0] => Array ( [code] => 400 [headers] => Array ( [0] => Array ( [name] => Access-Control-Allow-Origin [value] => * ) [1] => Array ( [name] => Cache-Control [value] => no-store ) [2] => Array ( [name] => Connection [value] => close ) [3] => Array ( [name] => Content-Type [value] => text/javascript; charset=UTF-8 ) [4] => Array ( [name] => Expires [value] => Sat, 01 Jan 2000 00:00:00 GMT ) [5] => Array ( [name] => Pragma [value] => no-cache ) [6] => Array ( [name] => WWW-Authenticate [value] => OAuth "Facebook Platform" "invalid_request" "An active access token must be used to query information about the current user." ) ) [body] => {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}} ) )