I am trying to post some data in json format and passing 'X-Api-Key' as header key. But my code always give notice of undefined index x-api-key. And no data is stored.
I am using cake php 2.x
Here is my php code
public function checkXAPI() {
$headers = apache_request_headers();
//X-Api-key unidentified
if($headers['X-Api-Key'] == 'AB5433GMDF657VBB'){
return true;
} else {
return true;
}
}
public function beforeFilter(){
$this->Auth->Allow(array('checkXAPI','Registerowner'));
$headersNotAllowed = array('login', 'checkXAPI', 'register');
$noSecurityAllowed = array('register');
if(!in_array($this->request->action, $noSecurityAllowed)){
$checkXAPI = $this->checkXAPI();
if (!$checkXAPI) {
$message = array(
'status' => false,
'message' => __('wrong X-API')
);
echo json_encode($message);
exit;
} else {
$headers = apache_request_headers();
if(!in_array($this->request->action, $headersNotAllowed)){
if (isset($headers['Id'])) {
$checkUserToken = $this->checkUserToken();
if (!$checkUserToken) {
$message = array(
'status' => false,
'message' => __('wrong User ID and User token combination')
);
echo json_encode($message);
exit;
}
}
}
}
}
}
Use $this->request->header('X-Api-Key') instead:
public function checkXAPI() {
return $this->request->header('X-Api-Key') === 'AB5433GMDF657VBB';
}
Related
Hi in the below php file I am calling in my android application but I am tried in postman am getting the below error.Using this url am accessing the login page but it is not working .No response from app
can any one please help me
Login.php:
<?php
class Mobile_WS_Login extends Mobile_WS_Controller {
function requireLogin() {
return false;
}
function process(Mobile_API_Request $request) {
$response = new Mobile_API_Response();
$username = $request->get('username');
$password = $request->get('password');
$current_user = CRMEntity::getInstance('Users');
$current_user->column_fields['user_name'] = $username;
if(vtlib_isModuleActive('Mobile') === false) {
$response->setError(1501, 'Service not available');
return $response;
}
if(!$current_user->doLogin($password)) {
$response->setError(1210, 'Authentication Failed');
} else {
// Start session now
$sessionid = Mobile_API_Session::init();
if($sessionid === false) {
echo "Session init failed $sessionid\n";
}
$current_user->id = $current_user->retrieve_user_id($username);
$current_user->retrieveCurrentUserInfoFromFile($current_user->id);
$this->setActiveUser($current_user);
$result = array();
$result['login'] = array(
'userid' => $current_user->id,
'crm_tz' => DateTimeField::getDBTimeZone(),
'user_tz' => $current_user->time_zone,
'user_currency' => $current_user->currency_code,
'session'=> $sessionid,
'vtiger_version' => Mobile_WS_Utils::getVtigerVersion(),
'date_format' => $current_user->date_format,
'mobile_module_version' => Mobile_WS_Utils::getVersion()
);
$response->setResult($result);
$this->postProcess($response);
}
return $response;
}
function postProcess(Mobile_API_Response $response) {
return $response;
}
}
Postman:
URL:http://XXXXXXX/modules/mobile/api/ws/Login.php
parms: username:abc
password:abc1
operation:login
Response From Postman:
<br />
<b>Fatal error</b>: Class 'Mobile_WS_Controller' not found in
<b>C:\xampp\htdocs\crmtest\modules\Mobile\api\ws\Login.php</b> on line
<b>10</b>
<br />
I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}
Created an API endpoint I which I am submitted data as the body in postman, but it is always empty on the server whereas it works fine on localhost.
Please look at the request
The same request works on localhost but not online. Here is code on the server side I am using Yii::$app->request->post() to dump the data, here is the full code of that endpoint. I had tried $_POST,$_REQUEST every request is empty on the server,
public function actionSocialcheck()
{
$data = [];
$model = new User();
var_dump(Yii::$app->request->post());
if ($model->load(Yii::$app->request->post(),'')) {
$social = User::findBySocialLogin($model->socialLogin);
if (empty($social)) {
$data['status'] = self::API_OK;
$data['check'] = false;
} else {
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
// $usercl=new User();
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
} else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
When I try the same request on the local server it works fine here is the output of that
Can you please help me out in this case. Thanks
public function actionSocialcheck(){
if(Yii::$app->request->isPost){
$data = [];
$social = User::findBySocialLogin(Yii::$app->request->post('socialLogin'));
if (empty($social)){
$data['status'] = self::API_OK;
$data['check'] = false;
}else{
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
}else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
This is the library I have created to load views in codeigniter,
Library:
public function view($view_name, $params = array(), $layout){
$renderedview = $this->CI->load->view($view_name,$params,TRUE);
if($this->data['title'])
{
$this->data['title'] = $this->title_separator.$this->data['title'];
}
if(array_key_exists('error', $this->data)){
$error = $this->data['error'];
}
else{
$error = '';
}
$this->CI->load->view('layouts/'.$layout, array(
'content_for_layout' => $renderedview,
'title_for_layout' => $this->data['title'],
'error' => $error
));
}
Here I want to pass array (having multiple views), currently only one view is going through it.
How I am calling this method.
Controller Method:
public function __adminRegisterView()
{
$this->layouts->setTitle('Admin Register');
$this->layouts->view('pages/admin/account/register','','admin/loginregister');
}
In the View:
<body class="login-img3-body">
<?php echo $content_for_layout; ?>
</body>
You can do something like this:
public function view($view_name, $params = array(), $layout){
if(!is_array($view_name))
{
$view_name[] = $view_name;
}
$renderedview = "";
foreach($view_name as $view)
{
$renderedview .= $this->CI->load->view($view,$params,TRUE);
}
if($this->data['title'])
{
$this->data['title'] = $this->title_separator.$this->data['title'];
}
if(array_key_exists('error', $this->data)){
$error = $this->data['error'];
}
else{
$error = '';
}
$this->CI->load->view('layouts/'.$layout, array(
'content_for_layout' => $renderedview,
'title_for_layout' => $this->data['title'],
'error' => $error
));
}
Now you can call view like that:
$this->layouts->view(array('pages/admin/account/register','pages/admin/account/login','test_view'),'','admin/loginregister');
or:
$this->layouts->view('pages/admin/account/register','','admin/loginregister');
I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>