Yii2 AuthClient Facebook - php

I have a problem with FB login in my Yii application. When I try to get the user attributes, application returns internal server error. I checked all logs and found nothing.
This is my config
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => 'xxxxxxxx',
'clientSecret' => 'xxxxxxxxx',
],
],
],
Controller actions
public function actions()
{
return
[
'auth' =>
[
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'authSuccess'],
],
];
}
and the app crashes when it reaches this statement inside the callback
$attributes = $client->getUserAttributes();
this is the $client object
object(yii\authclient\clients\Facebook)#115 (20) {
["authUrl"]=>
string(51) "https://www.facebook.com/dialog/oauth?display=popup"
["tokenUrl"]=>
string(45) "https://graph.facebook.com/oauth/access_token"
["apiBaseUrl"]=>
string(26) "https://graph.facebook.com"
["scope"]=>
string(5) "email"
["attributeNames"]=>
array(2) {
[0]=>
string(4) "name"
[1]=>
string(5) "email"
}
["version"]=>
string(3) "2.0"
["clientId"]=>
string(15) "xxxxxxxxxx"
["clientSecret"]=>
string(32) "xxxxxxxxxx"
["_returnUrl":"yii\authclient\BaseOAuth":private]=>
string(49) "http://xxxxxx.xx/auth?authclient=facebook"
["_curlOptions":"yii\authclient\BaseOAuth":private]=>
array(0) {
}
["_accessToken":"yii\authclient\BaseOAuth":private]=>
object(yii\authclient\OAuthToken)#117 (5) {
["tokenParamKey"]=>
string(12) "access_token"
["tokenSecretParamKey"]=>
string(18) "oauth_token_secret"
["createTimestamp"]=>
int(1461360063)
["_expireDurationParamKey":"yii\authclient\OAuthToken":private]=>
NULL
["_params":"yii\authclient\OAuthToken":private]=>
array(2) {
["access_token"]=>
string(175) "EAACZCvJlBssYBAF1vwxq7PMgKAsEz5GueWEpBTf3OZAGEHPrONRKVXLGggRudgsNcpHiWD2IWDlEwnVmku9qmyYvUWh2VYVPShOK6VfsQ7TID1dEozVUMgYU01raFK3IBJ2mvi5PNztnqgQ12d0yBZBYnZCVloft4FmkkYyjvwZDZD"
["expires"]=>
string(7) "5181417"
}
}
["_signatureMethod":"yii\authclient\BaseOAuth":private]=>
array(0) {
}
["_id":"yii\authclient\BaseClient":private]=>
string(8) "facebook"
["_name":"yii\authclient\BaseClient":private]=>
NULL
["_title":"yii\authclient\BaseClient":private]=>
NULL
["_userAttributes":"yii\authclient\BaseClient":private]=>
NULL
["_normalizeUserAttributeMap":"yii\authclient\BaseClient":private]=>
NULL
["_viewOptions":"yii\authclient\BaseClient":private]=>
NULL
["_events":"yii\base\Component":private]=>
array(0) {
}
["_behaviors":"yii\base\Component":private]=>
NULL
}
EDIT: I just found out that it must be some problem with Yii's AuthClient (maybe FB changed response?), because I used this in another project, about a year ago and it worked just fine. Now i tried to login to that project and it does the same thing

sorry, I haven't qualification for comment...
please post your function content
function authSuccess($client) {
...
}
extra:
check your user model has implements IdentityInterface and yii\web\User it's set user attribute at login function.
you could set breakpoint on there.

Related

Request URI Too Long with POST REST

I have the following peice of PHP code, using to access a POST method REST web service :
$PJS = isset($_REQUEST['arrayFile']) ? $_REQUEST['arrayFile'] : array();
foreach ($PJS as $PJ) {
$ext = explode('/', $PJ['type'])[1];
$storeAttachmentResourceParams = array(
'encodedFile' => $PJ['content'],
'resId' => $resId,
'data' => json_encode(
array(
array('column' => 'title', 'value' => 'PJ', 'type' => 'string'),
array('column' => 'attachment_type', 'value' => 'simple_attachment', 'type' => 'string'),
array('column' => 'status', 'value' => 'A_TRA', 'type' => 'string'),
)
),
'collId' => 'letterbox_coll',
'collIdMaster' => 'letterbox_coll',
'table' => 'res_attachments',
'fileFormat' => $ext
);
$storeAttachmentResource = Requests::post($cfg['url'] . '/attachments', array(), $storeAttachmentResourceParams, $options);
This piece of PHP code is call under a wordpress PHP snippet like the following :
$url = 'https://XXXX.XXX.fr/interface/iface.php';
$options = array(
'http' => array(
'header' => "",
'proxy' => "tcp://192.168.X.X:3128",
'timeout' => 100,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$returnIface = json_decode($return);
I modify my Apache2.conf like the following to add the LimitRequestLine:
AccessFileName .htaccess
LimitRequestLine 10000000
LimitRequestFieldSize 10000000
Restarted the Apache2 server but still have the following error in my browser :
Request-URI Too Long
The requested URL's length exceeds the capacity
limit for this server.
Apache/2.4.25 (Debian) Server at infosv47.sartrouville.lan Port 80
"
["headers"]=>
object(Requests_Response_Headers)#23 (1) {
["data":protected]=>
array(4) {
["date"]=>
array(1) {
[0]=>
string(29) "Fri, 06 Jul 2018 13:03:25 GMT"
}
["server"]=>
array(1) {
[0]=>
string(22) "Apache/2.4.25 (Debian)"
}
["content-length"]=>
array(1) {
[0]=>
string(3) "339"
}
["content-type"]=>
array(1) {
[0]=>
string(29) "text/html; charset=iso-8859-1"
}
}
}
["status_code"]=>
int(414)
["protocol_version"]=>
float(1.1)
["success"]=>
bool(false)
["redirects"]=>
int(0)
["url"]=>
string(46) "http://10.10.XX.XX/cs_maarch/rest/attachments"
["history"]=>
array(0) {
}
["cookies"]=>
object(Requests_Cookie_Jar)#20 (1) {
["cookies":protected]=>
array(0) {
}
}
}
It's under a Debian 9

IAM Role Name considred as Class in Yii 1

I have attached the policy to EC2 IAM role to access AWS services. After that i have have used below code in Yii 1 controller file:
ExampleController.php
class ExampleController extends Controller
{
public function init()
{
require_once dirname(dirname(__FILE__)) . '/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
//converting S3 private data to array to read
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
}
}
Output
PHP warning
include(TestRole.php): failed to open stream: No such file or directory
Note: TestRole is IAM Role Name.
I have used same code in Single PHP file (Not ties with Yii1)
test.php
require_once 'protected/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
//converting S3 private data to array to read
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
array(3) { ["Parameters"]=> array(1) { [0]=> array(3) { ["Name"]=> string(12) "host_name" ["Type"]=> string(6) "String" ["Value"]=> string(9) "localhost" } } ["InvalidParameters"]=> array(0) { } ["#metadata"]=> array(4) { ["statusCode"]=> int(200) ["effectiveUri"]=> string(35) "https://ssm.us-west-2.amazonaws.com" ["headers"]=> array(4) { ["x-amzn-requestid"]=> string(36) "d3fb85bc-da4e-494b-be4f-b31fe3814100" ["content-type"]=> string(26) "application/x-amz-json-1.1" ["content-length"]=> string(3) "182" ["date"]=> string(29) "Tue, 19 Jun 2018 12:28:50 GMT" } ["transferStats"]=> array(1) { ["http"]=> array(1) { [0]=> array(0) { } } } } } Exit
its working with single php file.
So question is how to fix it in Yii 1 and why its considering IAM Role Name as Class file?
Stack Trace
I was able to fix this out, Thanks to #javierfdezg.
So basically, Yii's auto loader and AWS's auto loader was got conflicted and may be due to Yii's assumption that class names must match file names.
So first i have unregistered the Yii's auto load then after the api call is finished registered it again.
class ExampleController extends Controller
{
public function init()
{
/* Unregister YiiBase */
spl_autoload_unregister(array('YiiBase', 'autoload'));
require_once dirname(dirname(__FILE__)) . '/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
/* Register YiiBase */
spl_autoload_register(array('YiiBase', 'autoload'));
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
}
}
You may set Yii::$enableIncludePath to false - it should improve compatibility with other autoloaders.
Yii::$enableIncludePath = false;
After this Yii will stop blindly including class files assuming that they're in one of the directories specified in include_path. If class cannot be loaded by Yii autoloader, next autoloader will get his chance.

PHPUnit - Guzzle: API calls not returning the desired response

I am using PHPUnit and Guzzle to test the REST api, which creates a new record in db, if the username(passed in request parameters) which is not already available in db and it sends response in JSON like below:
{
"success": true,
"id": "<unique_ID>"
}
And if the username is already available in db, then it sends response in JSON like below:
{
"success": false,
"error": "username is already available"
}
This is my PHPUnit testcase to test the above mentioned API along with Guzzle:
This is a setUp function is used to setup the Guzzle client
public function setUp()
{
$this->client = new GuzzleHttp\Client([
'base_uri' => 'http://localhost/test/'
]);
}
And this is the actual test function:
public function testActualResult()
{
$response = $this->client->post('service.php', [
'json' => [
'operation' => 'create_user',
'user_name' => 'testUser1'
]
]);
var_dump($response);
}
Whenever I test this, I get response like this:
class GuzzleHttp\Psr7\Response#99 (6) {
private $reasonPhrase =>
string(2) "OK"
private $statusCode =>
int(200)
private $headers =>
array(5) {
'Date' =>
array(1) {
[0] =>
string(29) "Tue, 21 Nov 2017 10:27:22 GMT"
}
'Server' =>
array(1) {
[0] =>
string(47) "Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31"
}
'X-Powered-By' =>
array(1) {
[0] =>
string(10) "PHP/5.6.31"
}
'Content-Length' =>
array(1) {
[0] =>
string(4) "1357"
}
'Content-Type' =>
array(1) {
[0] =>
string(16) "application/json"
}
}
private $headerNames =>
array(5) {
'date' =>
string(4) "Date"
'server' =>
string(6) "Server"
'x-powered-by' =>
string(12) "X-Powered-By"
'content-length' =>
string(14) "Content-Length"
'content-type' =>
string(12) "Content-Type"
}
private $protocol =>
string(3) "1.1"
private $stream =>
class GuzzleHttp\Psr7\Stream#86 (7) {
private $stream =>
resource(408) of type (stream)
private $size =>
NULL
private $seekable =>
bool(true)
private $readable =>
bool(true)
private $writable =>
bool(true)
private $uri =>
string(10) "php://temp"
private $customMetadata =>
array(0) {
}
}
}
But I am not getting the desired response sent back by an API call itself.
If I test my above mentioned API with POSTMAN, it works perfectly and gives back desired responses.
Have you read the GuzzlePHP documentation? Under 'Quickstart' -> 'Using Responses' it is described that when you want to get the body of the response you'll need to use the getBody() function on the $response.
What you are doing is just dumping the whole request variable, which contains way more information then you'll need for what you want to do.
See Using Responses for an example:
$response = $client->post('your parameters here');
$body = $response->getBody();
echo $body;

Asana upload error with Asana/php-asana

trying to test provided sample code:
$attachment = $client->attachments->createOnTask(
$enquiry->id,
'hello word',
'upload.txt',
'text/plain'
);
Error:
400 File is not an object
The client definitely works (able to create task just before).
The taskId ($enquiry->id) is correct (checked by going to the url etc).
Using v0.4.0 of the library and PHP 5.6.18-1 off a Homestead virtual machine.
Similar questions on SO talk about bad encoding but everything seems ok in my case.
Below is the response:
class Httpful\Response#961 (13) {
public $body =>
class stdClass#964 (1) {
public $errors =>
array(1) {
[0] =>
class stdClass#973 (2) {
...
}
}
}
public $raw_body =>
string(219) "{"errors":[{"message":"file: File is not an object","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}"
public $headers =>
class Httpful\Response\Headers#963 (1) {
private $headers =>
array(11) {
'server' =>
string(5) "nginx"
'date' =>
string(29) "Sat, 27 Feb 2016 02:36:49 GMT"
'content-type' =>
string(31) "application/json; charset=UTF-8"
'transfer-encoding' =>
string(7) "chunked"
'connection' =>
string(10) "keep-alive"
'x-asana-content-string-length' =>
string(3) "219"
'pragma' =>
string(8) "no-cache"
'set-cookie' =>
string(22) "TooBusyRedirectCount=0"
'cache-control' =>
string(8) "no-store"
'x-asana-preferred-release-revision' =>
string(56) "20160226_220201_ce3e88b3589d50e067532bbd0e824a44148e6738"
'x-robots-tag' =>
string(4) "none"
}
}
public $raw_headers =>
string(404) "HTTP/1.1 400 Bad Request
Server: nginx
Date: Sat, 27 Feb 2016 02:36:49 GMT
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Asana-Content-String-Length: 219
Pragma: no-cache
Set-Cookie: TooBusyRedirectCount=0
Cache-Control: no-store
X-Asana-Preferred-Release-Revision: 20160226_220201_ce3e88b3589d50e067532bbd0e824a44148e6738
X-Robots-Tag: none"
public $request =>
class Httpful\Request#962 (22) {
public $uri =>
string(62) "https://app.asana.com/api/1.0/tasks/(task_id)/attachments"
public $method =>
string(4) "POST"
public $headers =>
array(2) {
'X-Asana-Client-Lib' =>
string(118) "version=0.4.0&language=PHP&language_version=5.6.18-1%2Bdeb.sury.org%7Etrusty%2B1&os=Linux&os_version=3.19.0-25-generic"
'Authorization' =>
string(41) "Bearer (valid bearer)"
}
public $raw_headers =>
string(487) "POST /api/1.0/tasks/(task_id)/attachments HTTP/1.1
Host: app.asana.com
Expect:
User-Agent: Httpful/0.2.20 (cURL/7.35.0 PHP/5.6.18-1+deb.sury.org~trusty+1 (Linux))
Content-Type: multipart/form-data
Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;q=0.9, application/json
X-Asana-Client-Lib: version=0.4.0&language=PHP&language_version=5.6.18-1%2Bdeb.sury.org%7Etrusty%2B1&os=Linux&os_version=3.19.0-25-generic
Authorization: Bearer 0/88eebe64d4af7bd966936bbe346be679
"
public $strict_ssl =>
bool(false)
public $content_type =>
string(19) "multipart/form-data"
public $expected_type =>
string(16) "application/json"
public $additional_curl_opts =>
array(0) {
}
public $auto_parse =>
bool(true)
public $serialize_payload_method =>
int(0)
public $username =>
NULL
public $password =>
NULL
public $serialized_payload =>
array(1) {
'file' =>
string(48) "#/tmp/YCRYJd;filename=upload.txt;type=text/plain"
}
public $payload =>
array(1) {
'file' =>
string(48) "#/tmp/YCRYJd;filename=upload.txt;type=text/plain"
}
public $parse_callback =>
NULL
public $error_callback =>
NULL
public $send_callback =>
NULL
public $follow_redirects =>
bool(false)
public $max_redirects =>
int(25)
public $payload_serializers =>
array(0) {
}
public $_ch =>
resource(652) of type (Unknown)
public $_debug =>
NULL
}
public $code =>
int(400)
public $content_type =>
string(16) "application/json"
public $parent_type =>
string(16) "application/json"
public $charset =>
string(5) "UTF-8"
public $meta_data =>
array(26) {
'url' =>
string(62) "https://app.asana.com/api/1.0/tasks/(task_id)/attachments"
'content_type' =>
string(31) "application/json; charset=UTF-8"
'http_code' =>
int(400)
'header_size' =>
int(408)
'request_size' =>
int(552)
'filetime' =>
int(-1)
'ssl_verify_result' =>
int(0)
'redirect_count' =>
int(0)
'total_time' =>
double(3.435421)
'namelookup_time' =>
double(2.1E-5)
'connect_time' =>
double(0.29363)
'pretransfer_time' =>
double(2.023479)
'size_upload' =>
double(187)
'size_download' =>
double(219)
'speed_download' =>
double(63)
'speed_upload' =>
double(54)
'download_content_length' =>
double(-1)
'upload_content_length' =>
double(187)
'starttransfer_time' =>
double(2.023485)
'redirect_time' =>
double(0)
'redirect_url' =>
string(0) ""
'primary_ip' =>
string(12) "52.70.61.144"
'certinfo' =>
array(0) {
}
'primary_port' =>
int(443)
'local_ip' =>
string(9) "10.0.2.15"
'local_port' =>
int(49537)
}
public $is_mime_vendor_specific =>
bool(false)
public $is_mime_personal =>
bool(false)
private $parsers =>
NULL
}
[Asana\Errors\InvalidRequestError]
Invalid Request
Looked into it and Asana/php-asana uploadFile code is not compatible with php 5.6+.
Pull request: here

PayPal Billing Plan Key Response Error

function testing(){
$headers_array_sub_new = array("X-PAYPAL-SECURITY-USERID" => 'testing',
"X-PAYPAL-SECURITY-PASSWORD" => '12345645',
"X-PAYPAL-SECURITY-SIGNATURE" => 'Ab2145sdfd-IhWqUntNLtS4AWDawDzjOUVWjw6nXIcMtyOrkmDu',
"X-PAYPAL-APPLICATION-ID" => 'APP-80W284485P519543T',
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "JSON",
"Authorization" =>array('clientId'=>'testing','secret'=>'testing'),
"Accept" =>'application/json',
);
$url = "https://api.sandbox.paypal.com/v1/payments/billing-plans";
$subscriptionplan = array(
'name'=>'T shirt Plan',
'description'=> 'welcome plan',
'type'=> 'INFINITE' ,
'payment_definitions'=>array('name'=>'welcome','type'=>'REGULAR','frequency_interval'=>'2','frequency'=>'Month','cycles'=>'10','amount'=>'100'),
'merchant_preferences'=>''
);
$pay_result_trial = wp_remote_request($url, array('method' => 'POST', 'timeout' => 20, 'headers' => $headers_array_sub_new, 'body' => $subscriptionplan));
//$pay_result_trial2 = wp_remote_request($url2, array('method' => 'POST', 'timeout' => 20, 'headers' => $headers_array_sub1, 'body' =>$subscriptionplan));
var_dump($pay_result_trial);
here is the response error
array(5) { ["headers"]=> array(7) { ["server"]=> string(17) "Apache-Coyote/1.1" ["proxy_server_info"]=> string(57) "host=slcsbplatformapiserv3002.slc.paypal.com;threadId=322" ["paypal-debug-id"]=> string(13) "c764b1af30167" ["content-type"]=> string(16) "application/json" ["content-length"]=> string(1) "0" ["date"]=> string(29) "Fri, 20 Mar 2015 05:25:30 GMT" ["connection"]=> string(5) "close" } ["body"]=> string(0) "" ["response"]=> array(2) { ["code"]=> int(401) ["message"]=> string(12) "Unauthorized" } ["cookies"]=> array(0) { } ["filename"]=> NULL ?>
}
Can any one help me?
You are not using the right credentials for the call. You are using your API User/Pwd/Signature which are used for the Classic APIs. The Billing Plans you are attempting to use are part of the RESTful APIs which use standard oAuth credentials of Client ID and Client Secret. The REST API reference can be found here and contains information regarding Authentication/Headers as well as other useful information.

Categories