Hello I'm trying to validate the token I've created with the accountManager from my php server but I keep getting the error "invalid token" from google server on my php server... Here is the code :
private String updateToken(boolean invalidateToken, int accountref) {
String authToken = "null";
try {
AccountManager am = AccountManager.get(TestAuthActivity.this);
Account[] accounts = am.getAccountsByType("com.google");
AccountManagerFuture<Bundle> accountManagerFuture;
if(TestAuthActivity.this == null){//this is used when calling from an interval thread
accountManagerFuture = am.getAuthToken(accounts[accountref], SCOPE, false, null, null);
} else {
accountManagerFuture = am.getAuthToken(accounts[accountref], SCOPE, null, TestAuthActivity.this, null, null);
}
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN).toString();
if(invalidateToken) {
am.invalidateAuthToken("com.google", authToken);
authToken = updateToken(false, accountref);
}
} catch (Exception e) {
e.printStackTrace();
}
Dialog d = new Dialog(TestAuthActivity.this);
d.setTitle("Token :" + authToken);
d.show();
createSession(TestAuthActivity.this, authToken);
return authToken;
}
So I'm getting a token then I'm sending it to my php server :
<?php
if( isset($_POST['authToken'])){
//pour que la réponse s'affiche comme du texte brut
header('Content-Type: text/plain');
/*partie à modifier*/
$name = 'www.google.com';//nom du site
$data = $_POST['authToken'];
$envoi = "POST /m8/feeds/contacts/default/full HTTP/1.1\r\n";
$envoi .= "Host: ".$name."\r\n";
$envoi .= "Authorization: GoogleLogin auth='".$data."'\r\n";
$envoi .= "Connection: Close\r\n";
$envoi .= "Content-type: application/x-www-form-urlencoded\r\n";
$envoi .= "Content-Length: ".strlen($data)."\r\n\r\n";
$envoi .= $data."\r\n";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket < 0){
die('FATAL ERROR: socket_create() : " '.socket_strerror($socket).' "');
}
if (socket_connect($socket,gethostbyname($name),80) < 0){
die('FATAL ERROR: socket_connect()');
}
if(($int = socket_write($socket, $envoi, strlen($envoi))) === false){
die('FATAL ERROR: socket_write() failed, '.$int.' characters written');
}
$reception = '';
while($buff = socket_read($socket, 2000)){
$reception.=$buff;
}
echo(json_encode($reception));
socket_close($socket);
}
?>
and I keep getting the error : 401 invalid token :S
Does anyone have a solution or a good sample (couldn't found one that matches what I want to do !)
I can think of two possible problems you might have:
The auth token has expired. When you call your method updateToken() to get the token you need to set the parameter invalidateToken to true to make sure you get a fresh token.
The value of SCOPE is wrong. Based on the code you've provided it looks like you are trying to use the Google Contacts API, for this API SCOPE should have the value https://www.google.com/m8/feeds
Related
I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all
To login with facebook on my android app I request the public_profile and email of the user:
LoginManager.getInstance().logInWithReadPermissions(LoginFragment.this,
Arrays.asList("public_profile", "email"));
Then I send the id_token Profile.getCurrentProfile().getId() to the backend server.
On server side I try to verify the token as follows:
$id_token = $_POST['idToken'];
$app_access_token = FB_APP_ID . "|" . FB_APP_SECRET;
$fb = new \Facebook\Facebook(['app_id' => FB_APP_ID,
'app_secret' => FB_APP_SECRET,
'default_graph_version' => 'v2.8',
'default_access_token' => $app_access_token]);
$response = $fb->get('/debug_token?input_token=' . $id_token, $app_access_token);
But $response just contains an empty json {}.
UPDATE 1:
With
$oauth = $fb->getOAuth2Client();
$meta = $oauth->debugToken($app_access_token);
I eventually managed to validate the id_token. $meta contains then:
["metadata":protected]=>
array(4) {
["app_id"]=>string(16) "123456"
["application"]=>string(10) "abcdef"
["is_valid"]=>bool(true)
["scopes"]=>array(0) {}
}
What it also shows is that the scopes-array is empty although I called logInWithReadPermissions with public_profile and email permissions. I even checked the Permissions again in the onSuccess()-method of the FacebookCallback. But before I store the data to the DB I would like to read the user_id, user_name and email on server side to ensure that they match the id_token.
UPDATE 2:
When I call $oauth->debugToken() with $id_token instead of $app_access_token I now get what I expected. It also shows the pemissions I set before. But still I have the problem that I don't know how to access the granted information (user_name, user_profile_picture, email, etc.).
Finally I managed to solve the whole problem. I guess my main problem was that I wasn't aware of when to use user access token and when app access token. In many discussions and even documentations one is just talking about access token without specifying whether he means the user or the app access token. That said, here my final solution:
$id_token = $_POST['idToken'];
$app_access_token = FB_APP_ID . "|" . FB_APP_SECRET;
$fb = new \Facebook\Facebook(['app_id' => FB_APP_ID,
'app_secret' => FB_APP_SECRET,
'default_graph_version' => 'v2.8',
'default_access_token' => $app_access_token]);
$oauth = $fb->getOAuth2Client();
$meta = $oauth->debugToken($app_access_token);
try {
$meta->validateAppId(FB_APP_ID);
$idTokenIsValid = true;
} catch(FacebookSDKException $e) {
$idTokenIsValid = false;
exit;
}
if($idTokenIsValid){
$resp = $fb->get('/me?fields=id,name,email,first_name,last_name,locale,gender', $id_token);
$user = $resp->getGraphUser();
if($user->getId() != null){
$facebook_id = $user->getId();
$picture = "graph.facebook.com/" . $facebook_id . "/picture";
}
if($user->getName() != null){
$name = $user->getName();
}
$emailIsVerified = false;
if($user->getEmail() != null){
$email = $user->getEmail();
$emailIsVerified = true;
}
if($user->getFirstName() != null){
$given_name = $user->getFirstName();
}
if($user->getLastName() != null){
$family_name = $user->getLastName();
}
if($user->getProperty('locale') != null){
$locale = $user->getProperty('locale');
}
if($user->getProperty('gender') != null){
$gender = $user->getProperty('gender');
}
if($emailIsVerified){
//update db or/and request data from db
}
}
I am struggling with one situation. I am returning some json data from PHP server my code is as follows,
PHP API code:
if ($user != false) {
$result = mysql_query("SELECT stock_name,stock_location FROM btrack_stock WHERE user_id= '$user_id'") or die(mysql_error());
$rows = array();
$count = mysql_num_rows($result);
if($count > 0){
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('usertransaction' => $rows));
}else{
$response["error"] = 1;
$response["error_msg"] = "You do not have any transaction so far. ";
echo json_encode($response);
}
}
On android side, I use a class that extends AsyncTask and on my onPostExecute I use:
protected void onPostExecute(JSONObject json) {
try {
if(json.getString("error_msg") != null){
String err = json.getString("error_msg");
stock_error.setText(err);
stock_error.setVisibility(View.VISIBLE);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well actually, I wanted to display error message that is returned from PHP server and display all the data if I got success message (here I am showing a Toast).
My question is how can we display error message if json returns error message and display success if json does not return error message.
* My code works fine if I get error_msg as json response but if I return other data the app stuck in process dialog with a warning in LogCat as " There is no value for error_msg".
Thanks in Advance.
Try this:
if json.isNull("error_msg") {
do_something()
}
else {
json.getString("error_msg");
do_something_else()
}
I tried several ways to upload a file on the FTP server, but I failed in that.
Here I am pasting My server code (php)to accept the file from the device, please provide android code corresponding to that server code.
<?php
error_reporting(0);
include("dbconfig.php");
$msg = '';
$status = 1;
$overwrite = 1;
/*echo "<pre>";
print_r($_POST);
echo "</pre>";*/
/*echo "<pre>";
print_r($_FILES);
echo "</pre>";*/
if(trim($_POST['userid'])!='')
{
$userid = trim($_POST['userid']);
$overwrite = trim($_POST['overwrite']);
if($overwrite == 0)
{
$selfilesqry = mysql_query("SELECT filepath FROM userfiles WHERE userid = 1 AND status=1");
while($row = mysql_fetch_array($selfilesqry))
{
$selfiles[] = $row['filepath'];
}
}
/* echo "<pre>";
print_r($selfiles);
echo "</pre>";*/
$host = '97.***.****';
$usr = '*****************8';
$pwd = '**********************';
$paths = '/mobbisys/cloudbin/data';
//$paths = '/php_projects/mahesh/ftpupload/data';
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
for($i=0; $i<count($_FILES['txtfile']['name']); $i++)
{
if($_FILES['txtfile']['name'][$i]!='')
{
$type = explode('/',$_FILES['txtfile']['type'][$i]);
$filetype = $type[0];
if($filetype == 'audio')
{
$path = $paths."/audio";
}
else if($filetype == 'video')
{
$path = $paths."/video";
}
else if($filetype == 'image')
{
$path = $paths."/image";
}
else
{
$path = $paths."/misc";
}
//echo "<br />".$path;
$name = $_FILES['txtfile']['name'][$i];
$filep = $_FILES['txtfile']['tmp_name'][$i];
// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);
$filepath = strtolower($path.'/'.$name);
if($overwrite == 1)
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
else
{
if(in_array($filepath, $selfiles))
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i].' already exist.';
}
else
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
}
}
}
// close the FTP stream
ftp_close($conn_id);
}
else
{
$msg = 'Please provide userid';
}
echo $msg;
?>
You have to include move_uploaded_file function when you want insert
Syntax : move_uploaded_file ( string $filename , string $destination )
Example : move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./upload/".$_FILES["uploadedfile"]["name"]);
http://php.net/manual/en/function.move-uploaded-file.php
this is bad code. why not upload the files from android device via ftp without a server side script?
see here
I've been trying to get the email of the person who is sending a GET to AppEngine for hours I can't get that working.
What I'm trying to do is:
A client request a GET to an URL from Android.
AppEngine returns XML depending on the user making the request.
I'm using AERC library from Tim Bray to authenticate using a token that android provides.
public void run() {
if(client == null){
final AccountManager mgr = AccountManager.get(mActivity);
Account[] accts = mgr.getAccountsByType("com.google");
client = new AppEngineClient(APP_URI, accts[0], mActivity);
}
Log.i(tag, "Respuesta de auth: "+new String(client.get(AUTH_URI, null).body));
}
On the server side I have this:
UserService userService = UserServiceFactory.getUserService();
if (userService.getCurrentUser() != null) {
ret = "<tag>User userSErvice: "+userService.getCurrentUser() + "</tag>";
}else{
ret = "<tag>User userSErvice: null</tag>";
}
if (request.getUserPrincipal() != null) {
ret += "<tag>User request: "+request.getUserPrincipal() + "</tag>";
}else{
ret += "<tag>User request: null</tag>";
}
I'm using userService.getCurrentUser() and request.getUserPrincipal() because I don't know what method is which have to work. Both return null.
What am I doing wrong?
Thanks
Solved.
I had to add security contraints on web.xml like this:
<security-constraint>
<web-resource-collection>
<url-pattern>/yourservlet/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
And you have to request to an https to get the user from appengine