How fix Facebook login error in codeigniter - codeigniter

Facebook SDK returned an error:
Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
I use fblogin() and fbcallback() in same controller. But face this error. Also do all steps in developer.facebook.com. Session is also started. But error says, do not match.
public function fblogin(){
$this->load->library('session');
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID', // Replace {app-id} with your app id
'app_secret' => '{APP_SECRET}',
'default_graph_version' => 'v2.5',//v2.5
]);
$helper = $fb->getRedirectLoginHelper();
// if (isset($_GET['state'])) {
// $helper->getPersistentDataHandler()->set('state', $_GET['state']);
// }
// $sURL = $helper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://www.collegeprintsusa.com/maintenance/signin/fbcallback', $permissions);
// echo 'Log in with Facebook!';
header("location: ".$loginUrl);
}
public function fbcallback() {
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.5',//v2.5
]);
// $serializedFacebookApp = serialize($fb);
// $unserializedFacebookApp = unserialize($serializedFacebookApp);
// echo $unserializedFacebookApp->getAccessToken();
$helper = $fb->getRedirectLoginHelper(); //'https://www.collegeprintsusa.com/maintenance/signin/fblogin'
// $_SESSION['FBRLH_state'] = $_REQUEST['state'];
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$fbClient = $fb->getClient();
$accessToken = $helper->getAccessToken($fbClient);
}
} 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($accessToken)) {
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 to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: collegeprintsusa.com');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email', $accessToken);
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
// echo $fbid.','.$fbfullname; die();
# save the user nformation in session variable
$get_user_email = $this->user_model->get_single_user(['email' => $fbemail]);
if($get_user_email){
$res_user_fbid_update = $this->user_model->update_users(['id' => $get_user_email['id']],['facebook_id' => $fbid]);
if($res_user_fbid_update){
$this->session->set_userdata(['username' => $get_user_email['usename'],
'name' => $get_user_email['name'],
'last' => $get_user_email['last_name'],
'email' => $get_user_email['email'],
'type' => $get_user_email['user_type'],
'uid' => $get_user_email['id'],
'phone' => $get_user_email['phone'],
'address' => $get_user_email['address'],
'profile_image' => $get_user_email['profile_image'],
'disable' => $get_user_email['sms_update']]);
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}else{
$res_user_reg = $this->user_model->add_users([
'name' => $fbfullname,
'email' => $fbemail,
'phone' => 0,
'user_type' => 'customer',
'username' => $fbemail,
'password' => SALT . sha1($fbemail),
'token' => SALT . sha1($fbemail),
'facebook_id' => $fbid
]);
if($res_user_reg){
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}
} 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: index.php");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
echo 'Log in with Facebook!';
}
}

Here I would like to suggest a better solution to log in with Facebook. Please use JavaScript instead of PHP, because PHP will redirect on facebook page & JavaScript will not redirect, It will open facebook login popup on own website, and it`s very quick & easy process according to performance.
Please follow below code to login with facebook using JavaScript.
$(document).ready(function($) {
window.fbAsyncInit = function() {
FB.init({
appId : '186770818730407', // Set YOUR APP ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fbLogin()
{
FB.login(function(response) {
if (response.authResponse) {
getFBUserInfo();
}else {
showToaster('error','User cancelled login or did not fully authorize.');
return false;
}
},{scope: 'email,user_photos,user_videos'});
}
function getFBUserInfo() {
FB.api('/me',{fields: "id,picture,email,first_name,gender,middle_name,name"}, function(response) {
$.ajax({
url : "http://example.com/welcome/facebook_login",
type : "POST",
data : {response:response},
dataType : "JSON",
beforeSend:function(){
ajaxindicatorstart();
},
success: function(resp){
ajaxindicatorstop();
if(resp.type == "success"){
fbLogout();
showToaster('success',resp.msg);
setTimeout(function(){
window.location.href = base_url() + 'account-setting';
},1000);
}
else{
showToaster('error',resp.msg);
}
},
error:function(error)
{
ajaxindicatorstop();
}
});
});
}
function fbLogout()
{
FB.logout(function(){ console.log('facebook logout') });
}
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
});
Hope You will like it.
Thanks

Related

How to handle multiple file upload in Laravel

In my Vue component, I'm sending an Axios request with an array of multiple files. How can I handle the individual files in my Laravel controller?
I always have an error saying 'Invalid argument supplied for foreach()'.
My Vue method to send the files:
uploadFiles() {
this.isPending = true;
this.error = null;
let f = new FormData();
f.append('files', this.files);
axios.post(`items/${this.$route.params.productId}/upload_files`, f)
.then((res) => {
console.log(res);
this.isPending = false;
}).catch((err) => {
console.log(err);
this.isPending = false;
this.error = 'Er is iets misgegaan. Probeer het nog een keer.';
});
}
My controller function:
public function upload_files(Request $request, $id)
{
$request->validate([
'files' => 'required'
]);
foreach ($request['files'] as $file) {
Storage::put($file->getClientOriginalName(), file_get_contents($file));
$path = $request->file('files')->store('public');
return $path;
}
}

how can I customize json responses of laravel api and show them in vuex

Trying different solutions, I am fooling around with
response()->json([ ])
To create responses that I can read in my vue / vuex application
The Laravel api function that stores a new Speler ( dutch for player ;)):
I have trouble sending the created, or found Speler-object, through the response to the vuex-store.
Tried to set the status to 202 when succesfully logged, yet the actual status sent is 200..
It is clear that I do not understand it well enough. Can anyone help and explain?
public function store(Request $request)
{
if (Game::where('id',$request['game_id'])->exists() ){
if (!Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->exists()){
$newSpeler = Speler::create(
[
'name' => $request['name'],
'pass_code' => $request['pass_code'],
'game_id' => $request['game_id']
])->first());
return $newSpeler;
}
elseif ( Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->exists()){
$speler = Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code']);
return response()->json(['speler'=> $speler, 202]);
}
return response()->json(['status' => 'This name is already used, pass-code is not correct', 409]);
}
return response()->json([ 'status' => 'The game-pin does not exist', 403 ]);
}
This is called form the vuex actions:
export const addSpeler = ({commit}, formData) => {
return new Promise((resolve, reject) => {
fetch(`api/speler`, {
method: 'post',
body:formData,
})
.then(res => {
if (res.status === 202){
resolve('De speler is succesfully logged on');
commit('SET_CURRENT_SPELER', res.data.speler);
}
else if (res.status === 201){
commit('SET_CURRENT_SPELER', res.data);
resolve('De speler is succesfully added')
}
else {
reject('De speler is not logged in. Name exists and does not match passcode');
}
})
.catch(err => {
reject(err.message)
});
})
}
and this is called from a vue method:
methods: {
addSpeler(){
this.errorMessage ='';
this.spelerAdded =false;
const formData = new FormData();
formData.append('name', this.name);
formData.append('pass_code',this.pass_code);
formData.append('game_id', this.currentGame.id);
this.$store.dispatch('addSpeler', formData )
.then(res => {
this.spelerAdded = true;
console.log(res.status);
})
.catch(err => {
this.errorMessage = err;
this.spelerAdded = false;
});
},
mutations.js:
export const SET_CURRENT_SPELER = (state, speler) => {
state.currentSpeler = speler;
}
state.js:
export default{
currentGame:{},
currentSpeler:{}
}
The comment by porloscerros answered the question perfectly :
the status goes as the second argument of the json method return response()->json(['speler'=> $speler], 202); (and not inside the array as you are doing). If you don't pass a second argument, the argument value is assigned to 200 by default json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)

Hybridauth - The authorization state [state=HA-SOME_STATE_DATA] of this page is either invalid or has already been consumed

I am using Hybridauth with Codeigniter to implement social login buttons in my app. I just require Google, Facebook & LinkedIn social login button. I have successfully implemented the Google sign & sign up method but the same code does not work for Facebook & LinkedIn, Here is the error I am getting always this exception,
ops, we ran into an issue! The authorization state
[state=HA-RBNC6FHJ54VZAM1KTD7EI3SPYG08U2OLWQ9X] of this page is either
invalid or has already been consumed.Unable to get your data!Try after
some time.
My config file for hybriduath.
<?php
$config['hybridauth'] = [
//Location where to redirect users once they authenticate with a provider
'callback' => 'http://localhost/insurance-experts/auth/social_auth',
//Providers specifics
'providers' => [
'Google' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
], //To populate in a similar way to Twitter
'Facebook' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
'LinkedIn' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
]
];
Here is the implementation of hybridauth
public function social_auth()
{
$user_profile = NULL;
$auth_provider = $this->input->get('auth_provider');
// Check if it is redirected url with code & state params
if (!isset($_GET['code'])) {
$user_role = $this->input->get('role');
// Save it in the session to reuse it after auth redirect
// We'll need it in case user does not exist
$_SESSION['temp_user_role'] = $user_role;
}
switch ($auth_provider) {
case GOOGLE:
$auth_provider = GOOGLE;
break;
case FACEBOOK:
$auth_provider = FACEBOOK;
break;
case LINKEDIN:
$auth_provider = LINKEDIN;
break;
default:
$auth_provider = GOOGLE;
break;
}
// Load the hybridauth config file
$this->config->load('hybridauth');
//First step is to build a configuration array to pass to `Hybridauth\Hybridauth`
$config = $this->config->item('hybridauth');
try {
//Feed configuration array to Hybridauth
$hybridauth = new Hybridauth($config);
//Attempt to authenticate users with a provider by name
$adapter = $hybridauth->authenticate($auth_provider);
//Retrieve the user's profile
$user_profile = $adapter->getUserProfile();
//Disconnect the adapter
$adapter->disconnect();
} catch (\Exception $e) {
echo 'Oops, we ran into an issue! ' . $e->getMessage();
}
if (!empty($user_profile)) {
$email = $user_profile->email;
// Check if email exist in DB then sign in the user
$user_data = $this->User_model->find(['email' => $email], USERS);
if (!empty($user_data) && count($user_data) > 0) {
$user = $user_data[0];
$user_role = "";
// Cross check the user role
$user_groups = $this->ion_auth->get_users_groups($user->id)->result();
if (!empty($user_groups)) {
$group = $user_groups[0];
switch ($group->id) {
case ROLE_INDIVIDUAL:
$user_role = ROLE_INDIVIDUAL_STRING;
break;
case ROLE_COMPANY:
$user_role = ROLE_COMPANY_STRING;
break;
}
} else {
// Something went wrong, Force logout user
redirect('auth/logout');
}
if (empty($user_role)) {
redirect('auth/logout');
}
// Explicitly set the user role here
// coz it required in header's menubar
$user->role = $user_role;
$login_done = $this->ion_auth->set_session($user);
if ($login_done == TRUE) {
// Everything is OK, redirect the user to home page
redirect('/');
} else {
echo "We could not logged you in this moment!Please try after some time.";
}
} else {
$this->create_user_via_social_sign_up($user_profile);
}
} else {
echo "Unable to get your data!Try after some time.";
}
}
private function create_user_via_social_sign_up($user_profile)
{
$user_role = check_group($_SESSION['temp_user_role']);
if (empty($user_profile) or empty($user_role)) {
// Something went wrong, Force logout user
redirect('auth/logout');
}
$email = $user_profile->email;
// Generate a random password,
$password = substr(md5(rand()), 0, 7);
$extra_data = [
'active' => 1,
'is_approved' => 1
];
$this->db->trans_start();
// Directly register user via Model method as no need to send the activation email
$id = $this->ion_auth_model->register($email, $password, $email, $extra_data, [$user_role]);
$user_data = $this->User_model->find(['id' => $id], USERS);
$user = $user_data[0];
// Add the role in user object
$user->role = $user_role;
$redirectProfileUrl = base_url('Profile_setting/');
if ($this->ion_auth->set_session($user)) {
// Create empty records in tables
$this->User_model->create_user_entries($user->id, $user_role);
if ($this->db->trans_status() !== false) {
$this->db->trans_commit();
redirect($redirectProfileUrl);
} else {
// Something went wrong rollback all the transactions & inform the user
$this->db->trans_rollback();
echo "Our system is down right now!Please try after some time.";
}
}
}
Codeigniter version: 3.x
Hybridauth Version: 3

REST User registration and Login through Api Key

I am not new to codeignitor , but still i didn't used they feature called 'API keys' authentication.
What i want to do ?
Register a user in my_users table and there is apikey as column that should store and generate unique api while user registration.
Login User , user give username , password and it get response as logged in if correct information is given , with it's respective apikey in my_users table.
After login i want to use apikey for all other user related calls like bookATask with header as X-API-KEY , which will allow me to control user session at client side and secure login and sign system.
Problem in Setup:
I am being asked each time i make a request to pass X-API-KEY which is wrong because , maybe there is call register_post in User controller which register users and Api key cannot be passed in headers unless it is generated in this method right?
I am just getting status:FALSE and error:Invalid Api key on each call i make.
What am i doing?
(Only changed code)
application/config/rest.php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['force_https'] = FALSE;
$config['rest_default_format'] = 'json';
$config['rest_supported_formats'] = [
'json',
'array',
'csv',
'html',
'jsonp',
'php',
'serialized',
'xml',
];
$config['rest_status_field_name'] = 'status';
$config['rest_message_field_name'] = 'error';
$config['enable_emulate_request'] = TRUE;
$config['rest_realm'] = 'REST API';
$config['rest_auth'] = 'basic';
$config['auth_source'] = '';
$config['allow_auth_and_keys'] = TRUE;
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
$config['auth_override_class_method_http']['user']['register']['post'] = 'none';
$config['auth_override_class_method_http']['user']['login']['post'] = 'none';
$config['rest_valid_logins'] = ['user1' => '12345'];
$config['rest_ip_whitelist_enabled'] = FALSE;
$config['rest_ip_whitelist'] = '';
$config['rest_ip_blacklist_enabled'] = FALSE;
$config['rest_ip_blacklist'] = '';
$config['rest_database_group'] = 'default';
$config['rest_keys_table'] = 'my_users';
$config['rest_enable_keys'] = TRUE;
$config['rest_key_column'] = 'apikey';
$config['rest_limits_method'] = 'ROUTED_URL';
$config['rest_key_length'] = 40;
$config['rest_key_name'] = 'X-API-KEY';
$config['rest_enable_logging'] = TRUE;
$config['rest_logs_table'] = 'app_logs';
$config['rest_enable_access'] = FALSE;
$config['rest_access_table'] = 'access';
$config['rest_logs_json_params'] = FALSE;
$config['rest_enable_limits'] = TRUE;
$config['rest_limits_table'] = 'app_limits';
$config['rest_ignore_http_accept'] = FALSE;
$config['rest_ajax_only'] = FALSE;
$config['rest_language'] = 'english';
$config['check_cors'] = FALSE;
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
'GET',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE'
];
$config['allow_any_cors_domain'] = FALSE;
$config['allowed_cors_origins'] = [];
application/config/autoload.php
$autoload['libraries'] = array('database');
controllers/api/Key.php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Key extends REST_Controller {
protected $methods = [
'index_put' => ['level' => 10, 'limit' => 10],
'index_delete' => ['level' => 10],
'level_post' => ['level' => 10],
'regenerate_post' => ['level' => 10],
];
public function index_put()
{
$key = $this->_generate_key();
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = ctype_digit($this->put('ignore_limits')) ? (int) $this->put('ignore_limits') : 1;
if ($this->_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits]))
{
$this->response([
'status' => TRUE,
'key' => $key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
public function index_delete()
{
$key = $this->delete('key');
if (!$this->_key_exists($key))
{
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
$this->_delete_key($key);
$this->response([
'status' => TRUE,
'message' => 'API key was deleted'
], REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
public function level_post()
{
$key = $this->post('key');
$new_level = $this->post('level');
if (!$this->_key_exists($key))
{
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
if ($this->_update_key($key, ['level' => $new_level]))
{
$this->response([
'status' => TRUE,
'message' => 'API key was updated'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not update the key level'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
public function suspend_post()
{
$key = $this->post('key');
if (!$this->_key_exists($key))
{
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
if ($this->_update_key($key, ['level' => 0]))
{
$this->response([
'status' => TRUE,
'message' => 'Key was suspended'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not suspend the user'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
public function regenerate_post()
{
$old_key = $this->post('key');
$key_details = $this->_get_key($old_key);
if (!$key_details)
{
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
$new_key = $this->_generate_key();
if ($this->_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits]))
{
$this->_update_key($old_key, ['level' => 0]);
$this->response([
'status' => TRUE,
'key' => $new_key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
private function _generate_key()
{
do
{
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
if ($salt === FALSE)
{
$salt = hash('sha256', time() . mt_rand());
}
$new_key = substr($salt, 0, config_item('rest_key_length'));
}
while ($this->_key_exists($new_key));
return $new_key;
}
private function _get_key($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->get(config_item('rest_keys_table'))
->row();
}
private function _key_exists($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->count_all_results(config_item('rest_keys_table')) > 0;
}
private function _insert_key($key, $data)
{
$data[config_item('rest_key_column')] = $key;
$data['date_created'] = function_exists('now') ? now() : time();
return $this->db
->set($data)
->insert(config_item('rest_keys_table'));
}
private function _update_key($key, $data)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->update(config_item('rest_keys_table'), $data);
}
private function _delete_key($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->delete(config_item('rest_keys_table'));
}
}
(Method used in controller to generate Api key)
private function _generate_key()
{
do
{
// Generate a random salt
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
// If an error occurred, then fall back to the previous method
if ($salt === FALSE)
{
$salt = hash('sha256', time() . mt_rand());
}
$new_key = substr($salt, 0, config_item('rest_key_length'));
}
while ($this->_key_exists($new_key));
return $new_key;
}
private function _key_exists($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->count_all_results(config_item('rest_keys_table')) > 0;
}
On Database i have two extra tables app_limits , app_logs , and apikey column with varchar(40) in my_users table that's all , can anyone help me solving my issue , what am i doing wrong ?
I have found the answer myself , i just modifying these variables helped me :
$config['auth_override_class_method_http']['user']['customer_register']['post'] = 'none';
$config['auth_override_class_method_http']['user']['customer_login']['post'] = 'none';
these are basically exception methods for Api key which can be register and login , thanks myself

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Resources