Trying to change the company (team) application status from Drupal 8 portal (APIGEE Edge) - drupal-8

I Can't change the company app status Approved/Revoked, I tried to load and update the team_app entity using EntityTypeManager, and the other values have been updated without any issues like (callback URL, Description, Dispalyname, and custom attributes) but still the app status won't change/update,
$app_storage = \Drupal::entityTypeManager()->getStorage('team_app');
$app_ids = $app_storage->getQuery()
->condition('companyName', $team->id())
->condition('name', $app_mame)
->execute();
if (!empty($app_ids)) {
$app_id = reset($app_ids);
$loaded_app = $app_storage->load($app_id);
$loaded_app->set('status', 'revoked');
$loaded_app->save();
}
Also, I tried to make a PUT API request to change the app status with the same results, No status value changed.
/** #var \Drupal\apigee_edge\SDKConnectorInterface $sdk_connector */
$sdk_connector = \Drupal::service('apigee_edge.sdk_connector');
try {
$sdk_connector->testConnection();
$client = $sdk_connector->getClient();
}
catch (\Exception $exception) {
dump('client is not defined');
die();
}
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}");
try {
$response = $client->get($client->getEndpoint() . $endpoint);
$results = json_decode((string) $response->getBody());
$results->status = 'revoked';
// PUT.
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}")
$response = $client->put($client->getEndpoint() . $endpoint, json_encode($results));
$results = (array) json_decode((string) $response->getBody());
}
catch (\Exception $exception) {
dump('error, not trigger');
}
Any help with this?

Related

How to fix "fb_exchange_token parameter not specified"?

I cannot find any documentation on this.
Here is my code:
I'm using Laravel 5.5 and Facbook graph. Im posting to a page but I got this error fb_exchange_token parameter not specified but I have successfully logged in.
Due to shoddy documentation I cannot find anything on fb_exchange_token on the Facebook's website nor elsewhere.
Can anyone help?
{
$facebook = Facebooks::findOrFail($id);
$fb = new Facebook([
'app_id' => 'my_id', // Replace {app-id} with your app id
'app_secret' => 'my_secret',
'default_graph_version' => 'v3.3',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach($pages as $key){
if($key['name'] == 'CloudGuest Test'){
if(isset($_POST['facebook_status'])){
$text1 = $_POST['facebook_status'];
$post = $fb->post('/' . $key['id'] . '/feed', array('message' =>$text1),$key['access_token']);
$post = $post->getGraphNode()->asArray();
print_r($post);
}
}
}
}

Facebook SDK returned an error: Cross-site request forgery validation failed. The state param from the URL and session do not match

I'm working with Laravel 5.2 and I'm using SammyK/laravel-facebook-sdk Package i Tried the code in the following link enter link description here
I keep on having this error : "Cross-site request forgery validation failed. The "state" param from the URL and session do not match."
this is my controller code :
public function callbackfbsdk(Facebook $fb){
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
var_dump($loginUrl);
try {
$token = $fb::getAccessTokenFromRedirect();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
if (! $token) {
// Get the redirect helper
$helper = $fb::getRedirectLoginHelper();
if (! $helper->getError()) {
abort(403, 'Unauthorized action.');
}
// User denied the request
dd(
$helper->getError(),
$helper->getErrorCode(),
$helper->getErrorReason(),
$helper->getErrorDescription()
);
}
if (! $token->isLongLived()) {
$oauth_client = $fb::getOAuth2Client();
try {
$token = $oauth_client->getLongLivedAccessToken($token);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}
$fb::setDefaultAccessToken($token);
Session::put('fb_user_access_token', (string) $token);
try {
$response = $fb::get('/me?fields=id,name,email');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
$facebook_user = $response->getGraphUser();
$user = App\User::createOrUpdateGraphNode($facebook_user);
// Log the user into Laravel
Auth::login($user);
return redirect('/')->with('message', 'Successfully logged in with Facebook');
}
Any Ideas about how can I solve this error??
why you are putting these line in callback
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
it will try to generate link again after redirect.seperate it, will solve the problem

Undefined index: action error in facebook api

I am using php api's in my website (to make a profile page)
I am using the below code:
$action = $_REQUEST["action"];
switch($action){
case "fblogin":
include 'facebook.php';
$appid = "**********";
$appsecret = "*************************";
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$user_profile = $facebook->api('/me');
}
catch (Exception $e) {
echo $e->getMessage();
exit();
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fnmae = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
$check_select = mysql_num_rows(mysql_query("SELECT * FROM `fblogin` WHERE email = '$user_email'"));
if($check_select > 0){
mysql_query("INSERT INTO `fblogin` (fb_id, name, email, image, postdate) VALUES ('$user_fbid', '$user_fnmae', '$user_email', '$user_image', '$now')");
}
}
break;
}
It gives an error saying : Undefined index: action
I am using wamp server as localhost. Please provide a solution

Prestashop 1.5 Webservice Updating Customer id_default_group PHP

I need to automatically update the prestashop->customers->customer->id_default_group value using PHP via the Prestashop webservice. The script knows the new value and it is done before/as the page loads.
I can get a customer record, or I can get just the "id_default_group" of a customer record but I run into trouble when I try changing the record value and updating the webservice. I get back "HTTP/1.1 400 Bad Request".
It seems like I am incorrectly trying to update the xml or object.
It would be preferable to do all this by only getting and updating the "id_default_group" and not having to retrieve the complete customer record.
I have:
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://www.site.com/');
define('PS_WS_AUTH_KEY', 'yuyiu');
require_once('../PSWebServiceLibrary.php');
// First : We always get the customer's list or a specific one
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers'); // Full customer record
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']'); // Customer id_default_group value
if (isset($_SESSION['iemIdCustomer'])){
$opt['id'] = $_SESSION['iemIdCustomer'];
}
$xml = $webService->get($opt);
// The elements from children
$resources = $xml->children()->children();
// $resources = $xml->children()->children()->children(); // If just getting id_default_group
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Second : We update the data and send it to the web service
if (isset($_SESSION['iemIdCustomer'])){
// Update XML with new values
$xml->customers->customer->id_default_group = 4;
//$resources = $xml->children()->children()->children();
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService succeeds
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
}
This is basic for those in the know so I hope you can help.
Thanks in advance,
Lance
Ok I go the following to work.
The following line seem to do the trick:
$xml->children()->children()->id_default_group = 4;
Follows is the line with the rest of the code to do the task.
// Get the customer's id_default_group
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers');
$opt['id'] = $_SESSION["iemIdCustomer"];
$xml = $webService->get($opt);
// Get the elements from children of customer
$resources = $xml->children()->children()->children();
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Update the data and send it to the web service
// Update XML with new value
$xml->children()->children()->id_default_group = 4;
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
Hope that it assists someone.
i think you have this error because you are editing the bad node ;)
try with
$xml->customer->id_default_group = 4;
That should be OK :)

Codeigniter web services

I'm using Codeigniter 1.7. Does anyone have any experience of creating web services with PHP, particularly within the CodeIgniter framework? What are security measures need to consider while implementing web services? How to provide authentication with API keys?
Any Ideas?
It depends on the kind of web service you are inquiring about. Is the web service going to be a daemon for example? or a typical online web service. For either of these you must implement a RESTful type. RESTful meaning a stateless connection. This is where API keys are used; to identity a user for example.
Luckily Codeigniter is one with many libraries and extensions. An example of such libraries can be here: https://github.com/philsturgeon/codeigniter-restserver
Now for security concerns: API keys would replace sessions or any state. You would have to make full checks on the api. Many sites that implement APIs offer different solutions to the same end result.
Authentication with API keys are simple. You would check it against a storage type(database).
Here is a tutorial using codeigniter and the library linked previously: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
This might be somewhat vague, but since you dont have any specific problems or apparent needs its hard to be specific.
EDIT:
In that case it would be better implementing a RESTful interface so that your iphone app can also use all of the user functionalities that your service provides. The best way would be to make everything accessible in one way. Meaning not having different controllers / models for the iphone connections and web connections.
So for example you could have the following controller:
<?php
class Auth extends CI_Controller{
public function login(){
//Check if their accessing using a RESTful interface;
$restful = $this->rest->check();
if($restful){
//Check for the API keys;
$apiKey = $this->input->get('apiKey');
$secretKey = $this->input->get('secretKey');
//If you have any rules apon the keys you may check it (i.e. their lengths,
//character restrictions, etc...)
if(strlen($apiKey) == 10 and strlen($secretKey) == 14)
{
//Now check against the database if the keys are acceptable;
$this->db->where('apiKey', $apiKey);
$this->db->where('secretKey', $secretKey);
$this->db->limit(1);
$query = $this->db->get('keys');
if($this->db->count_all_results() == 1)
{
//It's accepted the keys now authenticate the user;
foreach ($query->result() as $row)
{
$user_id = $row->user_id;
//Now generate a response key;
$response_key = $this->somemodel->response_key($user_id);
//Now return the response key;
die(json_encode( array(
'response_key' => $response_key,
'user_id' => $user_id
)
)
);
} //End of Foreach
}//End of Result Count
}//End of length / character check;
} else {
//Perform your usual session login here...;
}
}
}
?>
Now this is just a small example for performing these types of requests. This could apply to any type of controller. Though there are a few options here. You could make every request pass the apikey, and the secret each time and verify it at each request. Or you could have some sort of whitelist that once you have been verified the first time each request after that would be whitelisted, and or black listed on the opposite.
Hope this helps,
Daniel
<?php
//First Create Api file in controller name Api.php
/*
api call in postman
login :
email , password
http://localhost/demo/api/login
https://prnt.sc/pbs2do
register (user): :
fullname , email , password , recipeunit
http://localhost/demo/api/signup
https://prnt.sc/pbs3cc
profile and list (user profile and all user ) :
View Profile : email, if all then pass blank
http://localhost/demo/api/userlist
change password :
http://localhost/demo/api/change_password
email ,password ,newpassword , conformnewpassword (if needed)
https://prnt.sc/pbs3rt
*/
if(!defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH . '/libraries/BaseController.php'; // this file will download first and pest in library
class Api extends BaseController
{
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->load->model('api/signup_model','signup_model');
}
/**
* Index Page for this controller.
*/
public function index()
{
}
public function signup()
{
$this->signup_model->signup();
}
public function login()
{
$this->signup_model->login();
}
public function userlist()
{
$this->signup_model->userlist();
}
public function edit_user()
{
$this->signup_model->edit_user();
}
public function change_password()
{
$this->signup_model->change_password();
}
public function testpass()
{
$this->signup_model->testpass();
}
}
// then create model in model folder create api folder create signup_model.php file
//after that
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Signup_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database(); /* load database library */
}
// User register (signin) process
public function signup($data = array())
{
// another db field update like dt_createddate
if(!array_key_exists('dt_createddate', $data)){
$data['dt_createddate'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('dt_updateddate', $data)){
$data['dt_updateddate'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('dt_updateddate', $data)){
$data['dt_updateddate'] = date("Y-m-d H:i:s");
}
$data['var_fullname'] = $this->input->post('fullname');
$data['var_email'] = $this->input->post('email');
$data['var_password'] =getHashedPassword($this->input->post('password')) ;
$data['int_recipeunit'] = $this->input->post('recipeunit');
// if(!empty($data['var_fullname']) && !empty($data['var_email']) && !empty($data['var_password']) ){ }
/* check emailid all ready exist or not */
$email_check=$this->input->post('email');
$this->db->select('var_email');
$this->db->from('tbl_user');
$this->db->where('var_email', $email_check);
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
echo "{\"status\" : \"404\",\"message\" : \"Email all ready register\",\"data\":".str_replace("<p>","",'{}'). "}";
}
else
{
$insert = $this->db->insert('tbl_user', $data);
if($insert){
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$insert_id = $this->db->insert_id();
$query = $this->db->get_where('tbl_user', array('int_id' => $insert_id));
echo "{\"status\" : \"200\",\"message\" : \"User added sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
// return $this->db->insert_id();
}else
{
$message="Something Wrong";
echo "{\"status\" : \"400\",\"data\":".str_replace("<p>","",json_encode($message)). "}";
// return false;
}
}
}
/* Login user $email, $password*/
function login()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
if(verifyHashedPassword($password, $user[0]->var_password))
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
echo "{\"status\" : \"200\",\"message\" : \"Login sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Password does not match\",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
/* Fetch user data all or single */
function userlist()
{
$email=$this->input->post('email'); // post id of which user data you will get
if(!empty($email))
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
$responce_json=json_encode($query->row_array());
echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get('tbl_user');
$responce_json=json_encode($query->result_array());
echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
}
/* Update user data */
function edit_user($data = array()) {
$id = $this->input->post('id');
$data['first_name'] = $this->input->post('first_name');
/* $data['last_name'] = $this->input->post('last_name');
$data['email'] = $this->input->post('email');
$data['phone'] = $this->input->post('phone'); */
if(!empty($data) && !empty($id)){
if(!array_key_exists('modified', $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
$update = $this->db->update('users', $data, array('id'=>$id));
if($update){
$message="User Update Sucessfully";
$responce_json=json_encode($message);
echo "{\"status\" : \"200\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
}
else
{
return false;
}
}
/* change password */
function change_password()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$newpassword=$this->input->post('newpassword');
//$conformnewpassword=$this->input->post('conformnewpassword');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
if(verifyHashedPassword($password, $user[0]->var_password))
{
//if($newpassword==$conformnewpassword)
//{
$data['var_password'] = getHashedPassword($newpassword);
$update = $this->db->update('tbl_user', $data, array('var_email'=>$email));
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
echo "{\"status\" : \"200\",\"message\" : \"Password change sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
/* }
else
{
echo "{\"status\" : \"404\",\"message\" : \"New pass and conform pass does not match \",\"data\":".str_replace("<p>","",'{}'). "}";
} */
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid old password \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
/*
* Delete user data
*/
/* public function delete($id){
$delete = $this->db->delete('users',array('id'=>$id));
return $delete?true:false;
} */
}
?>