How to implement SSO in android app - java

I have two different app,i have user database in backend,if any user loged in one app,he can also login in the another app without pressing login,just like facebook,how can i implement SSO in app?

You can do that using Content Provider also you can do the same using Shared preferences
Using Shared preferences here is the example:
Call this method when user logged in one app.
public void writeSSOInfo(){
SharedPreferences prefs = getSharedPreferences("CheckSSO",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
if(userLoggedIn){
editor.putBoolean("isLoggedIn", true);
}else{
editor.putBoolean("isLoggedIn", false);
}
editor.commit();
}
After saving in shared memory you can access the same detail in another application using below method.
public void readSSOInfo(){
Context con;
try {
con = createPackageContext("com.app.packagename1", 0);
SharedPreferences pref = con.getSharedPreferences("CheckSSO", Context.MODE_PRIVATE);
dataShared = pref.getBoolean("isLoggedIn", false);
}
catch (Exception e) {
Log.e("Not data shared", e.toString());
}
}

My advice would be after you logged in with any of the apps, I would store a user token with in SharedPreferences between both apps. Then get it at onCreate method of the both apps like this:
String PACKAGE_NAME = "your.package";
String PREFERENCE_NAME = "user-token";
String USER_TOKEN = "";
try {
myContext = createPackageContext(PACKAGE_NAME,Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPrefs = myContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_WORLD_READABLE);
USER_TOKEN = sharedPrefs.getString(PREFERENCE_NAME, "");
}
catch (NameNotFoundException e) {
e.printStackTrace();
}
Then check if USER_TOKEN is empty or not and if it is not I would skip to next screen and keep using same Auth token.

Related

Facebook SDK blocking upload of String to Firebase

I'm developing an Android app which uses Facebook Login. Login's working fine and I'm able to get back info via Facebook Graph API calls.
I'm trying upload a string to my Firebase database and the string (titled parentFirstNameFromFacebook) is the first name of the user who signed into Facebook. I'm trying to eventually upload a parent object with parentFirstNameFromFacebook in its setName() method.
doneCreatingNameAndPasswordFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gettingTextFromNameAndPasswordEditTexts();
//region creating new Parent object and setting required variables
Parent coOpCreatingParent = new Parent();
coOpCreatingParent.setCoopCreator(true);
coOpCreatingParent.setNumOfHoursOwned(0);
Bundle params = new Bundle();
params.putString("fields", "id,first_name");
new GraphRequest(AccessToken.getCurrentAccessToken(), "me", params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
parentFirstNameFromFacebook = data.getString("first_name");
SharedPreferences fBookSharedPref;
SharedPreferences.Editor editor;
fBookSharedPref = getSharedPreferences(Constants.FBOOK_NAME_SHARED_PREF, Context.MODE_PRIVATE);
editor = fBookSharedPref.edit();
editor.putString(Constants.FBOOK_NAME_SHARED_PREF, parentFirstNameFromFacebook);
editor.apply();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
SharedPreferences fBookSharedPref = getSharedPreferences(Constants.FBOOK_NAME_SHARED_PREF, Context.MODE_PRIVATE);
fbookFirstNameForUpload = fBookSharedPref.getString(Constants.FBOOK_NAME_SHARED_PREF, null);
coOpCreatingParent.setName(fbookFirstNameForUpload);
getProfileImageUrlFromFBookGraph();
coOpCreatingParent.setImageUrl(parentImageIDFromFBookGraph);
ArrayList<Child> newChildArrayList = new ArrayList<>();
coOpCreatingParent.setChildren(newChildArrayList);
//endregion
//region creating new ArrayList<Parent> adding Parent object from above
ArrayList<Parent> coOpParentArrayList = new ArrayList<>();
coOpParentArrayList.add(coOpCreatingParent);
//endregion
getReferenceOfCoOpBeingCreated();
//region uploading entire new Co-Op object to Firebase
CoOp coOpObjectBeingUploaded = new CoOp(coOpKey, enteredNewCoOpPassword, enteredNewCoOpName, coOpParentArrayList);
referenceOfCoOp.setValue(coOpObjectBeingUploaded);
//endregion
//region going to AddChildren Activity with Co-Op key in intent
Intent intentForNewActivity = new Intent(getBaseContext(), AddChildrenActivity.class);
intentForNewActivity.putExtra(Constants.CO_OP_REFERENCE_TO_CHILD_ACTIVITY_KEY, coOpKey);
startActivity(intentForNewActivity);
//endregion
}
});
In the Firebase screenshot below, parentsInCoOp is an ArrayList and the 0 below it is the Parent object. I'm trying to set a name and Facebook URL string as other variables for that Parent object.
Firebase screenshot
Whatever I do, the name doesn't show up on Firebase! I'm not sure what I'm doing wrong!
I also tried using Shared Preferences in case there's an issue with setting parentFirstNameFromFacebook within the Facebook call's onCompleted() method. I put parentFirstNameFromFacebook in SharedPref and then got it out to pass it through parent.setName().
Once I successfully upload the first name, then I'll do the same process for the fbook image URl string.
Anyone have any advice? Thanks!
You are performing the Facebook API GraphRequest using the executeAsync() method. The request is processed on a separate thread and the onComplete() response is received asynchronously. I don't use the Facebook API, but am guessing the request requires communication with the Facebook servers and will require many milliseconds to deliver a response.
The result is that these statements
fbookFirstNameForUpload =
fBookSharedPref.getString(Constants.FBOOK_NAME_SHARED_PREF, null);
coOpCreatingParent.setName(fbookFirstNameForUpload);
execute before the statements in the callback have executed and stored the name in preferences.

Android change a stored SharedPreferences value?

I create a shared preferences file at login, but I cannot figure out the code to change the preferences inside of my app.
SharedPreferences.java
public void editHospitalId(String hospital_id) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
Editor editor = prefs.edit();
editor.putString(KEY_HOSPITALID, hospital_id);
editor.commit();
}
I have already initialized a value for KEY_HOSPITALID on login:
SharedPreferences.java
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
// create login session
public void createLoginSession(String name, String hospital_id){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_HOSPITALID, hospital_id);
// commit changes
editor.commit();
I suppose I could delete the value and re-add it? But there has to be a way to overwrite it.
SharedPreferences contain data as key-value pairs, so calling putString(KEY, VALUE) will assign VALUE to the KEY, regardless of if it's already set. In short, it deletes previous entry automatically.

i want to use shared preference in the onpurchaseresponse() of SamplepurchaseListener.java of inapppurchasing via amazon

when case is successful i want to edit the variable value and then i want to use this value in other class of my project.
how can i do it?
kindly suggest me?
switch (status) {
case SUCCESSFUL:
SamplePurchasingListener.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_WORLD_READABLE).edit();
editor.putBoolean("PREMIUM", true); // Storing boolean - true/false
editor.commit();
}
});
final Receipt receipt = response.getReceipt();
iapManager.setAmazonUserId(response.getUserData().getUserId(), response.getUserData().getMarketplace());
Log.d(TAG, "onPurchaseResponse: receipt json:" + receipt.toJSON());
iapManager.handleReceipt(response.getRequestId().toString(), receipt, response.getUserData());
iapManager.refreshLevel2Availability();
break;
case ALREADY_PURCHASED:
Log.i(TAG,
"onPurchaseResponse: already purchased, you should verify the entitlement purchase on your side and make sure the purchase was granted to customer");
break;
If you just want to retrieve value from another class, why don't just get it from preferences? Something like this:
SharedPreferences sp = getSharedPreferences(MY_PREFS_NAME, MODE_WORLD_READABLE);
boolean premium = sp.getBoolean("PREMIUM", false);
if(premium) { ...
If there are not value have been stored before, method will return "false".
Maybe I haven't understood your question.

How to access saved data from different method?

I am trying to save a value as a string on the device's internal memory so that it can be accessed when the app is closed and reopened by clicking another button. When I run the program, I enter values for inputs A and B, and I know it processes them through the calculations because I modified it so that it displays the answer as soon as it is calculated.
But on this version, if I click the save button, and subsequently click the Access button to show the answer and the textview labeled Previous Answer, it simply shows "xx" which is the initial value of the string I'm trying to save. So either it doesnt store the updated version which includes the answer, or the Access button is only able to access the original value of the string.
Button jSave = (Button) findViewById(R.id.iSave);
Button jAccess = (Button) findViewById(R.id.iAccess);
final String saveName="Name";
final String saveValue = "xx";
jSave.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
//Calculations. These are a part of a more complex series of
//calculations between several classes, but I've simplified it
//somewhat for this post.
EditText jInputA = (EditText)findViewById(R.id.iInputA);
double dInputA = Double.parseDouble(jInputA.getText().toString());
EditText jInputB = (EditText)findViewById(R.id.iInputB);
double dInputB = Double.parseDouble(jInputB.getText().toString());
double myAnswer = Double.parseDouble(ProfileCalculations.functionQ(jInputA, jInputB));
//Update the value of saveValue to match that of myAnswer
final String saveValue = "The answer is " myAnswer;
//Save saveValue as a string under file saveName
try{
FileOutputStream jFOS = openFileOutput(saveName, Context.MODE_PRIVATE);
jFOS.write(saveValue.getBytes());
jFOS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
jAccess.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
try {
FileInputStream jFIS = openFileInput(saveName);
jFIS.read(saveValue.getBytes());
jFIS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
TextView jPreviousAns = (TextView) findViewById(R.id.iPreviousAns);
jPreviousAns.setText(saveValue + "");
}
}
);
How about shared preferences? Here's an example.
private SharedPreferences defaultPrefs;
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String url = "http://www.example.com";
SharedPreferences.Editor ed = defaultPrefs.edit();
ed.putString("homepage", url);
ed.commit();
And, later:
String url = defaultPrefs.getString("homepage", "http://www.example.com/some_default_page");
Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
For your given application of this, I would imagine that Shared Preferences or Internal Storage would be the way to go.
Internal Storage: Using this route, you would have to call openFileOutput() to start a FileOutputStream, and from there use write() to write data to the file, and close() to close the FileOutputStream.
Ex:
String FILENAME = "hello_file";
String string = "hello world!";
//Initiate
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//Write to file
fos.write(string.getBytes());
//Close file
fos.close();
Shared Preferences: If you are to use this, then you must call edit() to get a SharedPrefrencesEditor, and then to add values to this, you would simply use putBoolean(), putString(), etc. Once you're finished you commit the data using commit().
Ex:
//Initiate Shared Preferences
SharedPreferences.Editor editor = settings.edit();
//Writes data
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
(Source)

Twitter Digits check if the authentication was already made

I managed to integrate twitter digits and the authentication is working, but I want to check if the user already added his number and code.
For now I only have the authentication part:
final TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Crashlytics(), new Twitter(authConfig));
And the button event:
digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);
digitsButton.setCallback(new AuthCallback() {
#Override
public void success(DigitsSession session,
String phoneNumber) {
// Do something with the session
Toast.makeText(WelcomeActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show();
}
#Override
public void failure(DigitsException exception) {
// Do something on failure
Toast.makeText(WelcomeActivity.this,"Registration Failed",Toast.LENGTH_SHORT).show();
}
});
-
How can I check if the user already made these steps?
You can save the fact that an authentication was successful by storing the data somewhere. Storage Options
Using SharedPreferences, to check if an authentication was successful you would use isAuthenticated below:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean isAuthenticated = settings.getBoolean("ALREADY_AUTHENTICATED", false);
And to set that an authentication was successful (true), you could put this in the callback's success method
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("ALREADY_AUTHENTICATED", true /** or false */);
// Commit the edits!
editor.commit();

Categories

Resources