Store Twitter Tokens in mysql database - php

I can't seem to save the Twitter user_id, screen_name, oauth_token and oauth_token_secret (from a logged in user) into a mysql database that I've set up?
I'm using the Abraham Williams Oauth library.
That code works fine and I can see the components that make up the access_token by using a print_r request when a user logs in, however the tokens aren't saved into the table 'users' in the database 'tokens'?
I've read nearly all the questions/answers on SO and tested every bit of code however I can't seem to get a simple INSERT to work for these tokens? I've also hard coded some test components into the config_db file (as an INSERT) and they load fine.
Callback code:
<?php
require_once("/path/config_db.php");
session_start();
// Include class & create
require_once('/path/config.php');
require_once('/path/twitteroauth/twitteroauth.php');
// User has selected to DENY access
if(!empty($_GET["denied"])) {
// could re-direct or display cancelled view/template
// we're just echoing out a message
echo "No deal! <a href='index.php'>Try again?</a>";
die();
}
/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
header('Location: ./clearsessions.php');
}
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
//echo "RECEIVED TOKENS<br>";
// Check we have valid response
if(is_numeric($access_token["user_id"])) {
// Save the access tokens to a DB (we're using a session)
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
//GET CREDENTIALS VIA API
$credentials = $connection->get('account/verify_credentials');
//insert tokens into db
print_r($_SESSION["access_token"]);
$sql="INSERT INTO users (`user_id` ,`screen_name` ,`oauth_token` ,`oauth_token_secret`)
VALUES ('".$_SESSION["access_token"]["user_id"]."',
'".$_SESSION["access_token"]["screen_name"]."',
'".$_SESSION["access_token"]["oauth_token"]."',
'".$_SESSION["access_token"]["oauth_token_secret"]."'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
//echo $query;
//echo mysql_error();
print_r($_SESSION["access_token"]);
$message = array('status' => 'Test OAuth update. #testoauth');
$test = $connection->post('statuses/update', array('status' => 'Just a test '));
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
header('Location: ./callback.php');
} else {
/* Save HTTP status for error dialog on connnect page.*/
header('Location: ./clearsessions.php');
}
?>
<? print_r($access_token); ?>
The connection (config_db file) is as follows
<?php
$con=mysqli_connect("server","username","password","tokens");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
The table 'users' is as follows:
$sql = "CREATE TABLE users
(
user_id INT(11),
screen_name varchar(50),
oauth_token varchar(90),
oauth_token_secret varchar(90),
)";

You have a syntax error on sql query. you forget the close parentheses.
'".$_SESSION["access_token"]["oauth_token_secret"]."'"; change this
'".$_SESSION["access_token"]["oauth_token_secret"]."')";

Related

Store user session Corona SDK

I am trying to build a social app using Lua(Corona SDK). What I want to do is save the user in a session when they login/register so they won't have to login whenever they close the app and open it again.
I am sort of confused because I don't really know much Lua but my code doesn't work. I am using PHP and MySQL as the backend and DB. I already save the user in a session in PHP but how do I show the session id to the front end and verify it so that I can automatically login in ?
local function networkListener( event )
if ( event.isError ) then
local alert = native.showAlert("Error Logging In", "Check your internet connection .", {"Try again" })
else if event.response == "success" then
-- put the code here to go to where the user needs to be -- after a successful registration
--username = userID
composer.setVariable( "username", username.text )
composer.gotoScene( "feed", { params = parametersToSend } )
composer.removeScene( "login" )
else -- put code here to notify the user of the problem, perhaps -- a native.alert() dialog that shows
--them the value of event.response -- and take them back to the registration screen to let them try
--again
local json = require("json") print( json.prettify( event ) )
local alert = native.showAlert( "Error Logging In", event.response , { "Try again" } )
end
end
end
local function userLogin(event)
if ( "ended" == event.phase ) then
if emptyFields() == true then
else
local parameters = {}
parameters.body = "Login=1&username=" .. username.text .. "&pw=" .. pw.text
local URL = "http://192.168.1.37/hashmobile/process2.php"
network.request(URL, "POST", networkListener, parameters)
local headers = {}
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Language"] = "en-US"
parameters.headers = headers
end
end
end
process2.php:
$sql = "SELECT pw FROM users WHERE username = ?";
$stmt = mysqli_prepare($con, $sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($hashed_pwd); // Binds variables to a prepared statement for result storage
$stmt->fetch(); // Fetch results from a prepared statement into the bound variables
if (password_verify($pw, $hashed_pwd)) {
//session_id($_POST['user_session_id']); //starts session with given session id
// password verified
$_SESSION["user_session_id"] = $username;
echo "success";
//echo $_SESSION["user_session_id"];
//header('Location: profile.php');
//die();
} else {
//echo 'Incorrect username or Password.';
die('Incorrect username or Password.');
}
That is how I login to my app. Any help ?

Error - Expected content type text/json got text/html

After trying the Register function in this app, it shows an error via a UIAlert that says
Error
Expected content type{["text/json", "application/json", "text/javascript" )}, got text/html.
How can one fix this type of error? After looking at the overview tab in Charles Proxy, it confirms that the Content-Type is text/html; charset=UTF-8. Charles proxy is also showing the username and password being entered but it seems it's not being executed.
This is the header used in the app
header("Content-Type: application/json");
What is causing this error and how can it be solved?
//the web location of the service
#define kAPIHost #"http://192.168.1.3:8888"
#define kAPIPath #"iReporter/"
Edit
The app is supposed to register a user to a mysql database using AFNetworking in iOS and Json in its respective php web service
lib.php (helps connect to mysql database)
<?
//setup db connection
$link = mysqli_connect("localhost","root","root");
mysqli_select_db($link, "iReport");
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php (the file the app connects to to call the php commands via AFNetworking Json response)
<?
/* iReporter complete web demo project
*
* index.php takes care to check the "command" request
* and call the proper API function to process the user request
*
*/
// this line starts the server session - that means the server will "remember" the user
// between different API calls - ie. once the user is authorized, he will stay logged in for a while
session_start();
// the require lines include the lib and api source files
require("lib.php");
require("api.php");
// this instructs the client (in this case the iPhone app)
// that the server will output JSON data
header("Content-Type: application/json");
// the iPhone app sends over what "command" of the API it wants executed
// the tutorial covers "login","register","upload", "logout" and "stream"
// so using a switch statement for this taks makes most sense
// the functions you call inside the switch are found in the api.php file
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']);
break;
case "register":
register($_POST['username'], $_POST['password']);
break;
api.php (the file index.php connects to in order to call the server functions used in the app like login and register)
<?
// helper function, which outputs error messages in JSON format
// so that the iPhone app can read them
// the function just takes in a dictionary with one key "error" and
// encodes it in JSON, then prints it out and then exits the program
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
// register API
function register($user, $pass) {
//check if username exists in the database (inside the "login" table)
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
//the username exists, return error to the iPhone app
errorJson('Username already exists');
}
//try to insert a new row in the "login" table with the given username and password
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//registration is successful, try to also directly login the new user
login($user, $pass);
} else {
//for some database reason the registration is unsuccessfull
errorJson('Registration failed');
}
}
//login API
function login($user, $pass) {
// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
// a row was found in the database for username/pass combination
// save a simple flag in the user session, so the server remembers that the user is authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
// print out the JSON of the user data to the iPhone app; it looks like this:
// {IdUser:1, username: "Name"}
print json_encode($result);
} else {
// no matching username/password was found in the login table
errorJson('Authorization failed');
}
}
//upload API
function upload($id, $photoData, $title) {
// index.php passes as first parameter to this function $_SESSION['IdUser']
// $_SESSION['IdUser'] should contain the user id, if the user has already been authorized
// remember? you store the user id there in the login function
if (!$id) errorJson('Authorization required');
// check if there was no error during the file upload
if ($photoData['error']==0) {
// insert the details about the photo to the "photos" table
$result = query("INSERT INTO photos(IdUser,title) VALUES('%d','%s')", $id, $title);
if (!$result['error']) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the photos table
$IdPhoto = mysqli_insert_id($link);
// move the temporarily stored file to a convenient location
// your photo is automatically saved by PHP in a temp folder
// you need to move it over yourself to your own "upload" folder
if (move_uploaded_file($photoData['tmp_name'], "upload/".$IdPhoto.".jpg")) {
// file moved, all good, generate thumbnail
thumb("upload/".$IdPhoto.".jpg", 180);
//just print out confirmation to the iPhone app
print json_encode(array('successful'=>1));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
} else {
errorJson('Upload database problem.'.$result['error']);
}
} else {
errorJson('Upload malfunction');
}
}
//logout API
function logout() {
// by saving an empty array to $_SESSION you are
// effectively destroying all the user session data
// ie. the server won't "remember" anymore anything about
// the current user
$_SESSION = array();
// and to make double-sure, there's also a built-in function
// which wipes out the user session
session_destroy();
}
//stream API
//
// there are 2 ways to use the function:
// 1) don't pass any parameters - then the function will fetch all photos from the database
// 2) pass a photo id as a parameter - then the function will fetch the data of the requested photo
//
// Q: what "$IdPhoto=0" means? A: It's the PHP way to say "first param of the function is $IdPhoto,
// if there's no param sent to the function - initialize $IdPhoto with a default value of 0"
function stream($IdPhoto=0) {
if ($IdPhoto==0) {
// load the last 50 photos from the "photos" table, also join the "login" so that you can fetch the
// usernames of the photos' authors
$result = query("SELECT IdPhoto, title, l.IdUser, username FROM photos p JOIN login l ON (l.IdUser = p.IdUser) ORDER BY IdPhoto DESC LIMIT 50");
} else {
//do the same as above, but just for the photo with the given id
$result = query("SELECT IdPhoto, title, l.IdUser, username FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto='%d' LIMIT 1", $IdPhoto);
}
if (!$result['error']) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}
?>
Edit: The error is shown when trying the register function from the apps login screen

Why my facebook log in code not ask user for permission?

Why my facebook log in code not ask user for permission ?
Normally facebook lo ing on other website. when user log in with facebook on first time. It's will show ask permission box. But my facebook login code not show ask permission box. (still log in success)
How can i do for show ask permission box
<?php
include("connect.php");
session_start();
ob_start();
define('APP_ID', 'xxxxxxxxxxxxxxx'); // Your Facebook Application ID goes in here
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); // Your Facebook Application Secret goes in here
define('LOGIN_PAGE_URL', 'https://www.example.com/'); // The URL to your login page ending with a slash goes in here. Example: https://www.vasplus.info/demos/login_with_fb/
include 'vpb_fb/facebook.php';
//Facebook Application Details
$facebook_application_info = new Facebook(array('appId' => APP_ID, 'secret' => APP_SECRET));
//Get Facebook user id
$vpb_get_user = $facebook_application_info->getUser();
/**************************************************************************************************
* This script is brought to you by Vasplus Programming Blog by whom all copyrights are reserved.
* Website: www.vasplus.info
* Email: vasplusblog#gmail.com or info#vasplus.info
* Do not remove this information from the top of this page please.
***************************************************************************************************/
//Be sure that the user id is not an empty field before you can proceed
if ($vpb_get_user && !empty($vpb_get_user))
{
try { $vpb_fetch_data = $facebook_application_info->api('/me'); } // This user is authenticated therefore, proceed
catch (FacebookApiException $ex)
{
error_log($ex);
$vpb_get_user = null;
}
//Be sure user data from Facebook is not empty
if (!empty( $vpb_fetch_data ))
{
$uid = $vpb_fetch_data['id'];
$first_name = $vpb_fetch_data['first_name'];
$last_name = $vpb_fetch_data['last_name'];
$full_name = $vpb_fetch_data['name'];
$user_name = $vpb_fetch_data['username'];
$email = $vpb_fetch_data['email'];
$gender = $vpb_fetch_data['gender'];
$birthday = $vpb_fetch_data['birthday'];
$location = $vpb_fetch_data['location'];
$bio = $vpb_fetch_data['bio'];
$vpb_fb_logout = array('next' => LOGIN_PAGE_URL.'logout.php');
$logout_url = $facebook_application_info->getLogoutUrl($vpb_fb_logout);
$_SESSION['complete_logout'] = $logout_url;
// Be sure that the most important user info are in place then proceed
if(!empty($uid))
{
$_SESSION['Username'] = $username_user;
$_SESSION['admin'] = '0';
}
else
{
// There was an error therefore, take the user back to the login page
header('location: index.php?facebook_error=1'); // If the user denies the application access to his or her account
}
}
else
{
// There was an error therefore, take the user back to the login page
header('location: index.php?facebook_error=2'); // If something go wrong
}
}
else
{
// There was an error therefore, take the user to login via Facebook again with permission info
$vpb_login_url = $facebook_application_info->getLoginUrl(array('scope' => 'email, user_birthday, user_location, user_photos', 'redirect_uri' => LOGIN_PAGE_URL.'facebook_redirect_to_index.php'));
header("location: " . $vpb_login_url);
}
?>

Twitter oAuth Connection issue

I am doing Login with twitter in my application and using Twitter oAuth. I am placing proper consumer key and proper consumer secret key and valid callback url still having a error
Could not connect to Twitter. Refresh the page or try again later.
so what should I do now. couldn't trace out what is causing the trouble.
My index file
<?php
/**
* User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/
/* Load required lib files. */
session_start();
require_once('oauth/twitteroauth.php');
require_once('twitter_class.php');
if(isset($_GET['connect']) && $_GET['connect'] == 'twitter'){
$objTwitterApi = new TwitterLoginAPI;
$return = $objTwitterApi->login_twitter($_GET['connect']);
if($return['error']){
echo $return['error'];
}else{
header('location:'.$return['url']);
exit;
}
}
?>
My callback.php
<?php
session_start();
require_once('oauth/twitteroauth.php');
require_once('twitter_class.php');
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
header('Location: destroy.php');
}else{
$objTwitterApi = new TwitterLoginAPI;
$connection = $objTwitterApi->twitter_callback();
if( $connection == 'connected'){
header('Location: index.php?connected=Y');
exit;
}else{
header('Location: index.php?connected=F');
exit;
}
}
Help me on this hence i am new to this couldn’t trace out the actual problem.
PS: in oAuth there is always a blank response if curl

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

Categories