Twitter API - saving OAuth token in session - session

I am trying to find a way to keep connected with the Twitter API once authorised using OAuth but am having problems.
I get "Invalid / expired Token" when trying to connect to Twitter API using a saved Oauth token in a session or database.
Is there a way to do this? I dont want the users of my App to have to login via Twitter every time. Surely once they have authorised my App once, that should be enough?
$consumer_key = 'consumerkey';
$consumer_secret = 'consumersecret';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
if (isset($_GET['oauth_token'])){
$oauth_token = $_GET['oauth_token'];
} else if ($_SESSION['oauth_token']){
$oauth_token = $_SESSION['oauth_token'];
echo $_SESSION['oauth_token'];
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$oauth_token = $result[0];
}
if($oauth_token == ''){
$url = $twitterObj->getAuthorizationUrl();
$twitter_login = $url;
} else {
$twitterObj->setToken($oauth_token);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['oauth_token'] = $token->oauth_token;
$_SESSION['oauth_secret'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
echo $twitterInfo->response['error'];
//echo '<pre>';
//print_r($twitterInfo);
$id = $twitterInfo->id;
$username = $twitterInfo->screen_name;
//add to details database
//find the user by ID
if ($id != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND oauth_uid = '$id'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$id}, '{$username}', '{$_SESSION['oauth_token']}', '{$_SESSION['oauth_secret']}')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '{$_SESSION['oauth_token']}', oauth_secret = '{$_SESSION['oauth_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$id}");
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['oauth_token'];
$_SESSION['oauth_secret'] = $result['oauth_secret'];
}
$twitterAuth = TRUE;
}

I believe you are talking about access_token which you will get from the twitter as last part of OAuth handshaking after which you can go to access there services on user behalf.
Here is what they are saying in there official developer page
We do not currently expire access tokens.
Your access token will be invalid if a user explicitly
rejects your application from their settings or if a Twitter admin suspends
your application. If your application is suspended there will be
a note on your application page saying that it has been suspended.
So you can very well store that token in your database and can always use at later stage.
here is the reference to there API page
Twitter OAuth FAQ
So i suggest you to make sure that you are not changing any application setting and you are getting a valid access_token from session/database

Related

Code Issue when clicks "Return to Merchant" Button of Paypal

I am using Codeigniter to integrate the PayPal payment gateway on my website.
//This is my buy method
public function buy($id){
$course = $this->course_model->fetch_course_details_for_buy($id);
$returnURL = base_url().'paypal/success'; //payment success url
$cancelURL = base_url().'paypal/cancel'; //payment cancel url
$notifyURL = base_url().'paypal/ipn'; //ipn url
$userID = $this->session->userdata('student_id'); //current user id
$_SESSION['course_id'] = $course->course_id;
$logo = base_url().'assets/images/test-logo.png';
$this->paypal_lib->add_field('return', $returnURL);
$this->paypal_lib->add_field('cancel_return', $cancelURL);
$this->paypal_lib->add_field('notify_url', $notifyURL);
$this->paypal_lib->add_field('item_name', $course->title);
$this->paypal_lib->add_field('custom', $userID);
$this->paypal_lib->add_field('item_number', $course->course_id);
$this->paypal_lib->add_field('amount', $course->amount);
$this->paypal_lib->image($logo);
$this->paypal_lib->paypal_auto_form();
}
This is my PayPal's class method of success
function success(){
//get the transaction data
$paypalInfo = $this->input->get();
$data['item_number'] = $paypalInfo['item_number'];
$data['txn_id'] = $paypalInfo["tx"];
$data['payment_amt'] = $paypalInfo["amt"];
$data['currency_code'] = $paypalInfo["cc"];
$data['status'] = $paypalInfo["st"];
//pass the transaction data to view
$this->load->view('paypal/success', $data);
}
This is my IPN method
function ipn(){
//paypal return transaction details array
$paypalInfo = $this->input->post();
$data['user_id'] = $paypalInfo['custom'];
$data['product_id'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["txn_id"];
$data['payment_gross'] = $paypalInfo["mc_gross"];
$data['currency_code'] = $paypalInfo["mc_currency"];
$data['payer_email'] = $paypalInfo["payer_email"];
$data['payment_status'] = $paypalInfo["payment_status"];
$paypalURL = $this->paypal_lib->paypal_url;
$result = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
//check whether the payment is verified
if(preg_match("/VERIFIED/i",$result)){
//insert the transaction data into the database
$this->product->insertTransaction($data);
}
}
My payment is successful done from the sandbox account. But When I click the return to merchant button after payment it's throwing error of undefined indexes as mention in the success method. I apply first a time payment gateway and don't know what is missing in my code. Any help is appreciable.
You should log what $paypalInfo contains.
If you have enabled PDT, information may be coming as a POST rather than a GET.
In any case, make your code be able to check for and handle the missing data/indices or put it in a try/catch equivalent; it should not error.

How to redirect to another page after submitting a form

How to redirect to another page after submitting a form with my controller. the form is working fine but when i use the code like this i get a blank page and if i use
return view('leave.signUp');
it works but still remains in the page of the form and i want it to be redirected to another page.
public function index(Request $request)
{
if($request->isMethod('POST')){
$employee = new Employee;
$employee->lname = $request->input('lname');
$employee->fname = $request->input('fname');
$employee->oname = $request->input('oname');
$employee->employee_id = $request->input('staffId');
$employee->college = $request->input('college');
//$employee->salary_level = $request->input('salaryGradeLevel');
$employee->employee_type = $request->input('staffType');
$employee->employee_category= $request->input('staffCategory');
$employee->date_of_first_appointment= $request->input('dateOfFirstAppointment');
$employee->date_of_last_appointment= $request->input('dateOfLastAppointment');
$employee->country = $request->input('country');
$employee->gender = $request->input('gender');
$employee->title = $request->input('title');
$employee->marital_status = $request->input('maritalStatus');
$employee->email = $request->input('email');
$employee->phone_number = $request->input('phoneNumber');
$employee->date_of_birth = $request->input('dateOfBirth');
$employee->place_of_birth = $request->input('placeOfBirth');
$employee->religion = $request->input('religion');
$employee->origin = $request->input('stateOfOrigin');
$employee->local_government_area = $request->input('localGovernmentArea');
$employee->address = $request->input('address');
$employee->permanent_address = $request->input('permanentAddress');
$employee->extra_curicullar_activities = $request->input('extraCuricularActivities');
$employee->save();
$nextOfKin = new NextOfKin;
$nextOfKin->employee_id = $employee->employee_id;
$nextOfKin->title = $request->input('Ntitle');
$nextOfKin->surname = $request->input('Nsurname');
$nextOfKin->firstname = $request->input('Nfirstname');
$nextOfKin->othername = $request->input('Nothername');
$nextOfKin->relationship = $request->input('Nrelationship');
$nextOfKin->email = $request->input('Nemail');
$nextOfKin->phone_number = $request->input('NphoneNumber');
$nextOfKin->contact_address = $request->input('Naddress');
$nextOfKin->save();
return redirect(route('application'));
}
}
this is my web.php
Route::match(['post','get'],'application', 'LeavessController#index');
Route::match(['post','get'],'signUp', 'signUpsController#index');
Route::get('approved', 'LeavesController#getLeaveApproved');
Route::match(['post','get'], 'leaveType', 'LeavesController#getleaveType');
Route::match(['post','get'], 'leaveDepartment', 'LeavesController#getleaveDepartment');
Route::get('allLeave', 'LeavesController#getallLeave');
Route::get('leaveViewDetails', 'LeavesController#getleaveViewDetails');
Route::get('/get-leave-days/{leaveType}', 'LeavesController#getLeaveDays');
return redirect()->route('application');
The param for route() is what you defined in your routes with name(...)
https://laravel.com/docs/7.x/redirects#redirecting-named-routes
Besides that, I recommend you to read the laravel docs about Controllers: https://laravel.com/docs/7.x/controllers#resource-controllers
The index is only for returning the database entries. For inserting data into the database use store .
To redirect to a "simple" URL use:
return redirect('home/dashboard');
(replace 'home/dashboard' with the actual URL you want to redirect to)
To redirect to a named route use:
return redirect()->route('login');
(where login is the name of your route)
https://laravel.com/docs/7.x/responses#redirects

Yammer "Follow in Inbox" API support

My company has created a Yammer application that we use internally. Our app automatically subscribes people to various threads that have been created. We have found that there is a difference between "subscribing" someone to a thread and what happens when a user clicks the "follow in inbox" link on the site. When we automatically subscribe people, the only thing that we can see happening is that the thread will appear in the users "Following" section in the Home tab. Contrast this with what happens when a user clicks the "Follow in Inbox" link. From that point on any comments added to the thread will show up in the user's inbox and an email will be sent out to the user when this happens. We would really like for this to happen when we automatically subscribe someone to a thread, however, this feature seems to be missing from the REST API. Does anyone know of a way to accomplish this? The functionality provided by the subscription API endpoint is not sufficient for our purposes.
Thank you
P.S. I've sent the link to this question to several of my colleges they may respond before I get a chance to.
As a verified admin it is possible to create an impersonation token and then perform actions on behalf of the user such as join group/thread.
Note that for private groups, the group admin's are still required to approve the new member
https://developer.yammer.com/docs/impersonation
You can achieve your desired behaviour by adding users directly to the groups.
A C#.Net example I use:
// Impersonate user to join group
string ClientID = ConfigurationSettings.AppSettings["ClientID"]; // ClientID of custom app.
string userid = XMLDoc.Root.Element("response").Element("id").Value; // Yammer user id (in this case retreived from a previous API query)
string YammerGroupID = "123456"; // set group id.
string url = "https://www.yammer.com/api/v1/oauth/tokens.json?user_id=" + userid + "&consumer_key=" + ClientID; // impersonation end-point
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Bearer " + bearer); // Bearer token of verified admin running the custom app.
request.Timeout = 90000;
request.Method = "GET";
request.ContentType = "application/json";
request.Proxy = new WebProxy() { UseDefaultCredentials = true };
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string UserTokenJSON = reader.ReadToEnd(); // UserOAuth token as a JSON string.
string UserToken = UserTokenJSON.Substring(UserTokenJSON.IndexOf("token") + 8, 22); // Find 'token' in json string.
string temp = UserToken.Substring(UserToken.Length); // there is likely a much better way to parse out the token value, although this works.
temp = UserToken.Substring(UserToken.Length - 1);
temp = UserToken.Substring(UserToken.Length - 2);
if (UserToken.Substring(UserToken.Length) == "\\")
{ UserToken = UserToken.Substring(0, UserToken.Length); }
if (UserToken.Substring(UserToken.Length - 1) == "\"")
{ UserToken = UserToken.Substring(0, UserToken.Length - 1); }
if (UserToken.Substring(UserToken.Length - 2) == "\",")
{ UserToken = UserToken.Substring(0, UserToken.Length - 2); }
string url2 = "https://www.yammer.com/api/v1/group_memberships.json?group_id=" + YammerGroupID; // group membership endpoint,
HttpWebRequest request2;
request2 = (HttpWebRequest)WebRequest.Create(url2);
request2.Headers.Add("Authorization", "Bearer " + UserToken); // Impersonation Token
request2.Timeout = 90000;
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Proxy = new WebProxy() { UseDefaultCredentials = true };
try
{
using (WebResponse response2 = (HttpWebResponse)request2.GetResponse())
{
confirmedstring += " New member: " + Email + "\\r\\n"; // This is used for posting summary back to a Yammer group in further code.
confirmedadditions++;
}
}
catch
{
Errorstring += "Error in adding " + Email + " to group " + YammerGroupID + "\\r\\n";
errors++;
}
}
}

Set Session Expiration Time Manually-CodeIgniter

How can I set session expiration time dynamically in codeigniter?
For example, if a user logs in and has the role of admin, the expiration time should be longer than if a user logs in who does not have an admin role.
Thanks.
You can update your session expiration time by increasing this variable in config file:
$config['sess_expiration'] = 'somevalue'.
Set $config['sess_expiration'] = 0, if you want it to never expire.
Here's a good discussion on CI forums:
Dynamically set configuration on session expire doesn’t work
$data = array(
'username' => $this->input->post('username'),
'ADMIN_is_logged_in' => true
);
$this->session->sess_expiration = '14400';// expires in 4 hours
$this->session->set_userdata($data);// set session
None of these solutions address doing this dynamically or require another variable to be added to the session. The solution I came up with for CI 3.0.4 is to extend Session.php.
Create file application/libraries/Session/MY_Session.php
Put the following into the file and modify for your logic of setting the $expiration variable. In my case I am pulling the value from a database. NOTE: If you have different expiration values per user type; there is a chance they could get garbage collected and expire unexpectedly due to different expirations with the same session. In this case I do NOT recommend this approach.
<?php
class MY_Session extends CI_Session
{
public function __construct(array $params = array())
{
parent::__construct($params);
}
/**
* Configuration
*
* Handle input parameters and configuration defaults
*
* #param array &$params Input parameters
* #return void
*/
protected function _configure(&$params)
{
$CI =& get_instance();
$phppos_session_expiration = NULL;
$CI->db->from('app_config');
$CI->db->where("key", "phppos_session_expiration");
$row = $CI->db->get()->row_array();
if (!empty($row))
{
if (is_numeric($row['value']))
{
$phppos_session_expiration = (int)$row['value'];
}
}
$expiration = $phppos_session_expiration !== NULL ? $phppos_session_expiration : config_item('sess_expiration');
if (isset($params['cookie_lifetime']))
{
$params['cookie_lifetime'] = (int) $params['cookie_lifetime'];
}
else
{
$params['cookie_lifetime'] = ( ! isset($expiration) && config_item('sess_expire_on_close'))
? 0 : (int) $expiration;
}
isset($params['cookie_name']) OR $params['cookie_name'] = config_item('sess_cookie_name');
if (empty($params['cookie_name']))
{
$params['cookie_name'] = ini_get('session.name');
}
else
{
ini_set('session.name', $params['cookie_name']);
}
isset($params['cookie_path']) OR $params['cookie_path'] = config_item('cookie_path');
isset($params['cookie_domain']) OR $params['cookie_domain'] = config_item('cookie_domain');
isset($params['cookie_secure']) OR $params['cookie_secure'] = (bool) config_item('cookie_secure');
session_set_cookie_params(
$params['cookie_lifetime'],
$params['cookie_path'],
$params['cookie_domain'],
$params['cookie_secure'],
TRUE // HttpOnly; Yes, this is intentional and not configurable for security reasons
);
if (empty($expiration))
{
$params['expiration'] = (int) ini_get('session.gc_maxlifetime');
}
else
{
$params['expiration'] = (int) $expiration;
ini_set('session.gc_maxlifetime', $expiration);
}
$params['match_ip'] = (bool) (isset($params['match_ip']) ? $params['match_ip'] : config_item('sess_match_ip'));
isset($params['save_path']) OR $params['save_path'] = config_item('sess_save_path');
$this->_config = $params;
// Security is king
ini_set('session.use_trans_sid', 0);
ini_set('session.use_strict_mode', 1);
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.hash_function', 1);
ini_set('session.hash_bits_per_character', 4);
}
}
You can handle this with a custom controller. When a user logs in, set a session variable with the time of login. Create custom controller that contains a function in the constructor to check if the user is not admin user and if the timeout has expired. If it has, call $this->session->destroy(); Now, make all your controllers extend that controller instead of the CI base controller.
In Codeigniter 4
Go to the file App=>Config=>App.php
Find the var $sessionExpiration
The default value for this var is 7200
Change it to the value as you want your session to be alive.
The complete config for the session is given below:
public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler';
public $sessionCookieName = 'ci_session';
public $sessionExpiration = 7200;
public $sessionSavePath = WRITEPATH . 'session';
public $sessionMatchIP = false;
public $sessionTimeToUpdate = 300;
public $sessionRegenerateDestroy = false;
Session will expire in 10 seconds
$config['sess_expiration']= 10;
Session will not expire
$config['sess_expiration']= 0;
In Codeigniter 4, I do it the other way.
Set the session expiration time to maximal value (for example month for everybody) then in your controller or libraries, if the user is not admin, check the last active time, if time is more than what you need, destroy session and require log in.
use something like this:
$user_type = $this->input->post('user_type');
if ($user_type == 'admin')
{
//set session to non-expiring
$this->session->sess_expiration = '32140800'; //~ one year
$this->session->sess_expire_on_close = 'false';
}
else
{
//set session expire time, after that user should login again
$this->session->sess_expiration = '1800'; //30 Minutes
$this->session->sess_expire_on_close = 'true';
}
//set session and go to Dashboard or Admin Page
$this->session->set_userdata(array(
'id' => $result[0]['id'],
'username' => $result[0]['username']
));
At codeigniter go to applications/config.php and find the below configuration.
$config['sess_expiration'] = 14400; //in seconds
In your login functionality just after user credentials have been verified you can check if user is admin and set different sessions accordingly. Something along these lines
<?php
/*
*Assuming user is successfully veriefied and you've verified id user is admin*/
if($isAdmin==true){
$this->session->sess_expiration = 14400; // 4 Hours
}else{
// For ordinary users
$this->session->sess_expiration = 1800; // 30 minutes
}
$this->session->sess_expire_on_close = FALSE;
I think the most better chooice is using session temp_data and always you can change is dynamically and it is not depended your 'sess_expiration' in config file:
$this->session->set_tempdata('admin_session', true, 72000);
$this->session->set_tempdata('user_session', true, 14400);
where you check admin or user login state, like 'ADMIN_is_logged_in?'
check the remained 'tempdata' lifetime by:
if($this->session->tempdata('admin_session')){
//do something }
else{
//session timeout and is time to destroy all sessions
session_destroy();
}
You can solve the session issue by replacing this:
$config['sess_use_database'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;
with this:
$config['sess_use_database'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;

codeigniter admin login hacked although I have used all security matters

how come have the code before hacked with SQL Injection :(
$query = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?", array(mysql_real_escape_string($this->input->post('username')), mysql_real_escape_string(MD5($this->input->post('password')))));
appreciate helps!!
You don't need to use mysql_real_escape_string() as CodeIgniter Database driver does that for you. Double escaping your string could well cause some problems.
Use like this for more safer queries:
$query_username = $this->db->query("SELECT COUNT(username) AS count_username FROM users WHERE username=?", $this->input->post('username'));
$row_username = $query_username->row_array();
if ($row_username['count_username'] > 0) {
$query_password = $this->db->query("SELECT password FROM users WHERE username=?", $this->input->post('username'));
$row_password = $query_password->row_array();
if ($row_password['password'] == MD5($this->input->post('password')) {
// LOGIN SUCCESS
} else {
// LOGIN FAILED
}
} else {
// LOGIN FAILED
}

Resources