Dropbox Api AccessToken Changed - android

I am developing an android application that has the potential to provide large amount of statistical information. I want to save this data on my dropbox to be analyzed later.
So I used the AuthActivity to get the key and secret for my own account, which I then hardcoded to get an AcessTokenPair instance:
AcessTokenPair tokenPair = new AccessTokenPair("key", "secret");
mDBApi.getSession().setAccessTokenPair(tokenPair);
I then send the file to my dropbox using the AsyncTask below:
private class SendToDropbox extends AsyncTask<String, Void, String> {
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String timestamp = new Date().toString();
FileInputStream inputStream = null;
DisplayMetrics dm = new DisplayMetrics();
win.getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
File sdcard = new File(Environment.getExternalStorageDirectory()
.getPath());
File session = null;
try {
session = File.createTempFile("analytics_" + timestamp, ".txt", sdcard);
if (session.exists()) {
PrintStream ps = new PrintStream(session);
ps.println("Screen Size: " + screenInches);
ps.println("Device: " + android.os.Build.MODEL);
ps.println("Carrier: " + android.os.Build.BRAND);
ps.println("Locale: " + Locale.getDefault().toString());
ps.println("OS: " + android.os.Build.VERSION.SDK);
ps.println("${EOF}");
ps.checkError();
ps.close();
inputStream = new FileInputStream(session);
com.dropbox.client2.DropboxAPI.Entry newEntry = mDBApi
.putFile("Analytics" + File.separator
+ session.getName(), inputStream,
session.length(), null, null);
if (session.delete()) {
} else {
session.deleteOnExit();
}
Log.i("DbExampleLog", "The uploaded file's rev is: "
+ newEntry.rev);
} else {
Log.e("DropBoxFile", "SD NOT MOUNTED!!");
}
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return null;
}
The only problem with this code is that it only works a few weeks, maybe a month before the access token changes. This means I would have to manually update the apk every few weeks, which isn't very feasible. Instead I would like to store the keys on a website or online file that I can access via http.
Are there any free programs that DO NOT require account access and allow you to upload and edit .txt files on the web?

Access tokens do not currently expire, though that may change in future. You'd need to be very careful never to unlink your app from the account used to generate the token, though, since that would invalidate the token which is hard-coded into your app.
I can't recommend this, though, for security reasons. A token embedded into your app can be discovered by someone reverse-engineering the app. And anyone with that token can not only read, but also write to the Dropbox (or App folder) to which the token has access, and by doing so they might screw up the other users of your app.

From the Dropbox Best Practices: Best Practices
Your app should take precautions in case of revoked access. Access tokens may be disabled by the user (from the account page), revoked by Dropbox administrators in cases of abuse, or simply expire over time.
In the case where a token is no longer authorized, the REST API will return an HTTP Error 401 Unauthorized response. The iOS SDK detects 401s for you and will call the sessionDidReceiveAuthorizationFailure: method on the session's delegate to notify you that the authorization was revoked. The Android, Python, Ruby, and Java SDKs will all raise an exception on server errors that you can catch and inspect. Re-authenticating is typically all that is necessary to regain access.
So the Access Token can surely change over time. You just must be flexible enough to deal with that.

Related

Stripe payment gateway in android

I am integrating Stripe in my android application.
I have found two issues and I am stuck.
First (and major) issue is -
I have got token key from the card information. But when I tried to make my first charge, it shows error in following line.
Stripe.apiKey = "sk_test_0000000000000";
I have googled also but couldn't find any solution.
Creating Stripe Customer - cannot resolve symbol apiKey
I have even seen this kind of question too. But I failed to understand its solution.
Following is my code for making charge:
final String publishableApiKey = BuildConfig.DEBUG ?
"pk_test_000000000000000000" :
//"sk_test_00000000000000000000000" :
getString(R.string.com_stripe_publishable_key);
final TextView cardNumberField = (TextView) findViewById(R.id.cardNumber);
final TextView monthField = (TextView) findViewById(R.id.month);
final TextView yearField = (TextView) findViewById(R.id.year);
TextView cvcField = (TextView) findViewById(R.id.cvc);
Card card = new Card(cardNumberField.getText().toString(),
Integer.valueOf(monthField.getText().toString()),
Integer.valueOf(yearField.getText().toString()),
cvcField.getText().toString());
Stripe stripe = new Stripe();
stripe.createToken(card, publishableApiKey, new TokenCallback() {
public void onSuccess(Token token) {
// TODO: Send Token information to your backend to initiate a charge
Toast.makeText(
getApplicationContext(),
"Charge Token created: " + token.getId(),
Toast.LENGTH_LONG).show();
/*make a charge starts*/
// Set your secret key: remember to change this to your live secret key in production
// Create the charge on Stripe's servers - this will charge the user's card
Stripe.apiKey = "sk_test_0000000000000000000000";
try {
Map<String, Object> chargeParams = new HashMap<String, Object>();
chargeParams.put("amount", 100); // amount in cents, again
chargeParams.put("currency", "usd");
chargeParams.put("source", token.getId());
chargeParams.put("description", "Example charge");
Charge charge = Charge.create(chargeParams);
System.out.println("Charge Log :" + charge);
} catch (CardException e) {
// The card has been declined
} catch (APIException e) {
e.printStackTrace();
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (InvalidRequestException e) {
e.printStackTrace();
} catch (APIConnectionException e) {
e.printStackTrace();
}
/*charge ends*/
}
I have tried these code from different examples. I followed Stripe doc too.
But I got this error:
com.stripe.exception.AuthenticationException: No API key provided. (HINT: set your API key using 'Stripe.apiKey = '.
Second Issue is - about validation.
If I am entering my own card details, and if I write wrong cvv number. It still generates token key.
I have already implemented validation of fields using Stripe's official doc. I don't know how to validate it with real time data.
Solution for the First Issue:
com.stripe.Stripe.apiKey = "sk_test_xxxxxxxxxxxxxxxxxxx";
try {
final Map<String, Object> chargeParams = new HashMap<String, Object>();
chargeParams.put("amount", 500); // amount in cents, again
chargeParams.put("currency", "usd");
chargeParams.put("source", token.getId());
chargeParams.put("description", "Example charge");
new Thread(new Runnable() {
#Override
public void run() {
Charge charge = null;
try {
charge = Charge.create(chargeParams);
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (InvalidRequestException e) {
e.printStackTrace();
} catch (APIConnectionException e) {
e.printStackTrace();
} catch (CardException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
System.out.println("Charge Log :" + charge);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
Stripe's Android bindings only let you tokenize card information. Once the token has been created, it must be sent to an external server where you can use it in API requests.
You cannot use the token directly from the app as the app must never have access to your secret key, where it could easily be extracted by an attacker who would then have access to your account.
Re. your second question, the card isn't validated with the bank when the token is created (there are still some basic sanity checks, such as checking the number of digits, the fact that the expiry date is in the future, etc.). It is only when you use the token in a server-side API request that the card will be checked with the bank.

Upload file with Azure Storage using SAS (Shared Access Signature)

I know that there is library available for uploading the file using Azure Storage. I have refer this for same.
But, they have not give information for how to use SAS with that. I have account name, and sas url for access and upload file there. But I don't know how to use that for uploading file.
If I use above mention library it shows me invalid storage connection string because I am not passing the key in it (Which is not required with sas). So I am confused how I can upload file.
I have refer this documentation also for uploading file using sas. but not getting proper steps to do this. They have made demo for their windows app. I want to have that in android with use of sas.
Update
I have try with below code with reference to the console app made by Azure to check and access SAS.
try {
//Try performing container operations with the SAS provided.
//Return a reference to the container using the SAS URI.
//CloudBlockBlob blob = new CloudBlockBlob(new StorageUri(new URI(sas)));
String[] str = userId.split(":");
String blobUri = "https://myStorageAccountName.blob.core.windows.net/image/" + str[1] + "/story/" + storyId + "/image1.jpg" + sas.toString().replaceAll("\"","");
Log.d(TAG,"Result:: blobUrl 1 : "+blobUri);
CloudBlobContainer container = new CloudBlobContainer(new URI(blobUri));
Log.d(TAG,"Result:: blobUrl 2 : "+blobUri);
CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
String filePath = postData.get(0).getUrl().toString();
/*File source = new File(getRealPathFromURI(getApplicationContext(),Uri.parse(filePath))); // File path
blob.upload(new FileInputStream(source), source.length());*/
Log.d(TAG,"Result:: blobUrl 3 : "+blobUri);
//blob.upload(new FileInputStream(source), source.length());
//blob.uploadText("Hello this is testing..."); // Upload text file
Log.d(TAG, "Result:: blobUrl 4 : " + blobUri);
Log.d(TAG, "Write operation succeeded for SAS " + sas);
response = "success";
//Console.WriteLine();
} catch (StorageException e) {
Log.d(TAG, "Write operation failed for SAS " + sas);
Log.d(TAG, "Additional error information: " + e.getMessage());
response = e.getMessage();
} catch (FileNotFoundException e) {
e.printStackTrace();
response = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
response = e.getMessage();
} catch (URISyntaxException e) {
e.printStackTrace();
response = e.getMessage();
} catch (Exception e){
e.printStackTrace();
response = e.getMessage();
}
Now, when I upload text only it says me below error
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Now, my requirement is to upload Image file. So when I uncomment code for uploading image file it is not giving me any error but even not uploading image file.
#kumar kundal
The mechanism that you have explained is completely right.
Below is the more detailed answer about uploading profile image to the Azure Server.
First create SAS url to upload Image(or any file) to blob storage:
String sasUrl = "";
// mClient is the MobileServiceClient
ListenableFuture<JsonElement> result = mClient.invokeApi(SOME_URL_CREATED_TO_MAKE_SAS, null, "GET", null);
Futures.addCallback(result, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement result) {
// here you will get SAS url from server
sasUrl = result; // You need to parse it as per your response
}
#Override
public void onFailure(Throwable t) {
}
});
Now, you have sasURL with you. That will be something like the below string:
sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B
Now, you need to append the sas url with your uploading url. See below code in which I have appended the SAS url with my uploading request.
try {
File source = new File(filePath); // File path
String extantion = source.getAbsolutePath().substring(source.getAbsolutePath().lastIndexOf("."));
// create unique number to identify the image/file.
// you can also specify some name to image/file
String uniqueID = "image_"+ UUID.randomUUID().toString().replace("-", "")+extantion;
String blobUri = MY_URL_TO_UPLOAD_PROFILE_IMAGE + sas.replaceAll("\"","");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
CloudBlobContainer container = blobCLient.getContainerReference("");
CloudBlockBlob blob = container.getBlockBlobReference(uniqueID);
BlobOutputStream blobOutputStream = blob.openOutputStream();
byte[] buffer = fileToByteConverter(source);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
int next = inputStream.read();
while (next != -1) {
blobOutputStream.write(next);
next = inputStream.read();
}
blobOutputStream.close();
// YOUR IMAGE/FILE GET UPLOADED HERE
// IF YOU HAVE FOLLOW DOCUMENT, YOU WILL RECEIVE IMAGE/FILE URL HERE
} catch (StorageException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
I hope this information help you lot for uploading the file using blob storage.
Please let me know if you have any doubt apart from this. I can help in that.
Uploading a pic to BLOB storage . I got it after searching for hours .Take a look :-
Uploading the photo image is a multistep process:
First you take a photo, and insert a TodoItem row into the SQL database that contains new meta-data fields used by Azure Storage.
A new mobile service SQL insert script asks Azure Storage for a Shared Access Signature (SAS).
That script returns the SAS and a URI for the blob to the client.
The client uploads the photo, using the SAS and blob URI.
So what is a SAS?
It's not safe to store the credentials needed to upload data to the Azure Storage service inside your client app. Instead, you store these credentials in your mobile service and use them to generate a Shared Access Signature (SAS) that grants permission to upload a new image. The SAS, a credential with a 5 minute expiration, is returned securely by Mobile Services to the client app. The app then uses this temporary credential to upload the image.
for further queries and detail analysis. Visit this official documentation https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/

Can't receive mails with Pop in Android

I can receive my mails with Imap with this code sample :
URLName server = new URLName("imaps://" + username + ":"+ password + "#imap.gmail.com/INBOX");
Session session = Session.getDefaultInstance(new Properties(), null);
Folder folder = session.getFolder(server);
if (folder == null)
{
System.exit(0);
}
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
But sometimes Imap doesn't give any service and at those times I want to use Pop but I couldn't use it with my code. It is different the other codes for using receive mail. But in Android only this code is working.
What should I change in this code to work with Pop?
First, there's a nice URLName constructor that takes all the component pieces as separate parameters, so you don't have to do string concatenation.
Switch from IMAP to POP3 requires changing the protocol name as well as the host name. See the JavaMail FAQ for examples. The protocol name is "pop3s" and the host name is "pop.gmail.com".
Finally, you should use Session.getInstance instead of Session.getDefaultInstance. Compare the javadocs for the two methods to understand why.
How about this one.Really worked for me!!(Source:here)
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "","youremailid#gmail.com",yourpassword);
Session session = Session.getInstance(pop3Props, null);
Store store = new POP3SSLStore(session, url);
try {
store.connect();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Folder folder = null;
try {
folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (folder == null) {
System.exit(0);
}
try {
folder.open(Folder.READ_ONLY);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try retreiving folder via store object.And also mention that the folder you wish to retreive is INBOX!Also note that in settings,port number is 995 form pop.(You may leave the first six lines as they are.)

Android - Lock Screen via App and if user unlocks , system should ask for password

I am developing an App in which I need to lock screen than if user unlocks, it should ask for password...
Help would be really appreciated.
What you basically need is a way to make sure that the user has a password set for their lock screen. There's no clean way of doing this. No formal API. If you're willing to risk a hack, you can try this. I cobbled it together some code I found on this site.
boolean hasPasswordOnLockScreen(){
String sLockPasswordFilename =
android.os.Environment.getDataDirectory().getAbsolutePath() +
"/system/password.key";
try {
// Check if we can read a byte from the file
RandomAccessFile raf = new RandomAccessFile(filename, "r");
raf.readByte();
raf.close();
return true;
} catch (FileNotFoundException fnfe) {
return false;
} catch (IOException ioe) {
return false;
}
}
Note that this is a hack and has the potential to not work in the future is the path and file name of the password file changes.

Android OAuth: Exception on retrieveAccessToken()

I'm setting up OAuth for my Android app. To test it I did the following:
Added signpost-core-1.2.1.1.jar and signpost-commonshttp4-1.2.1.1.jar to my project, added the variables "CommonsHttpOAuthConsumer consumer" and "CommonsHttpOAuthProvider provider" and did the following when the button is clicked:
consumer = new CommonsHttpOAuthConsumer("xxx", "yyy");
provider = new CommonsHttpOAuthProvider("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
oauthUrl = provider.retrieveRequestToken(consumer, "myapp://twitterOauth");
persistOAuthData();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oauthUrl)));
persistOAuthData() does the following:
protected void persistOAuthData()
{
try
{
FileOutputStream providerFOS = this.openFileOutput("provider.dat", MODE_PRIVATE);
ObjectOutputStream providerOOS = new ObjectOutputStream(providerFOS);
providerOOS.writeObject(this.provider);
providerOOS.close();
FileOutputStream consumerFOS = this.openFileOutput("consumer.dat", MODE_PRIVATE);
ObjectOutputStream consumerOOS = new ObjectOutputStream(consumerFOS);
consumerOOS.writeObject(this.consumer);
consumerOOS.close();
}
catch (Exception e) { }
}
So, the consumer and the provider are saved before opening the browser, like described here.
In the onResume() method I load the provider and consumer data and do the following:
Uri uri = this.getIntent().getData();
if (uri != null && uri.getScheme().equals("myapp") && uri.getHost().equals("twitterOauth"))
{
verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
if (!verifier.equals(""))
{
loadOauthData();
try
{
provider.retrieveAccessToken(consumer, verifier);
}
catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
}
So, what works:
1) I do get a requestToken and a requestSecret.
2) I do get the oauthUrl.
3) I am directed to the browser page to authorize my app
4) I am getting redirected to my app.
5) I do get the verifier.
But calling retrieveAccessToken(consumer, verifier) fails with an OAuthCommunicationException saying "Communication with the service provider failed: null".
Does anyone know what might be the reason? Some people seem to have problems getting the requestToken, but that just works fine. I wonder if it might be a problem that my app has also included the apache-mime4j-0.6.jar and httpmime-4.0.1.jar which I need for multipart upload.
Okay, I figured it out. Maybe this is helpful to others:
First of all, you do not need to save the whole consumer and provider object. All you need to do is store the requestToken and the requestSecret. Luckily, those are Strings, so you don't need to write them to disk or anything. Just store them in the sharedPreferences or something like that.
Now, when you get redirected by the browser and your onResume() method is called, just do the following:
//The consumer object was lost because the browser got into foreground, need to instantiate it again with your apps token and secret.
consumer = new CommonsHttpOAuthConsumer("xxx", "yyy");
//Set the requestToken and the tokenSecret that you got earlier by calling retrieveRequestToken.
consumer.setTokenWithSecret(requestToken, tokenSecret);
//The provider object is lost, too, so instantiate it again.
provider = new CommonsHttpOAuthProvider("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
//Now that's really important. Because you don't perform the retrieveRequestToken method at this moment, the OAuth method is not detected automatically (there is no communication with Twitter). So, the default is 1.0 which is wrong because the initial request was performed with 1.0a.
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
That's it, you can receive the token and the secret with getToken() and getTokenSecret(), now.
Hi Manuel i see you are avoidin the OAuthocalypse too!
heres is a good example to implement OAuth for Twitter using sharedPreferences to save requestToken and the requestSecret, like your solution.
http://github.com/brione/Brion-Learns-OAuth
by Brion Emde
heres the video
hope this helps other developers =)

Categories

Resources