FingerPrint Authentication in my app - android

Im trying to implement fingerprint authentication inside app. while initializing KeyGenerator .it showing this error.
protected void generateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}
try {
keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
throw new RuntimeException(
"Failed to get KeyGenerator instance", e);
}
try {
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
throw new RuntimeException(e);
}
Error:'KeyGenParameterSpec()' is not public in 'android.security.keystore.KeyGenParameterSpec'. Cannot be accessed from outside package

Below are two classes which you can use to authenticate with finger print. Their will be minor issues like permsission handling or any import. but this is working code of finger print authentication.
FingerPrintHandler class
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.Manifest;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.v4.app.ActivityCompat;
import yasiriqbal.ethereum.R;
import yasiriqbal.ethereum.util.SessionManager;
#TargetApi(Build.VERSION_CODES.M)
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
// You should use the CancellationSignal method whenever your app can no longer process user input, for example when your app goes
// into the background. If you don’t use this method, then other apps will be unable to access the touch sensor, including the lockscreen!//
private CancellationSignal cancellationSignal;
private Context context;
public FingerprintHandler(Context mContext) {
context = mContext;
}
//Implement the startAuth method, which is responsible for starting the fingerprint authentication process//
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
public void StopListener() {
try {
if (cancellationSignal != null)
cancellationSignal.cancel();
cancellationSignal = null;
}catch (Exception e)
{}
}
#Override
//onAuthenticationError is called when a fatal error has occurred. It provides the error code and error message as its parameters//
public void onAuthenticationError(int errMsgId, CharSequence errString) {
//I’m going to display the results of fingerprint authentication as a series of toasts.
//Here, I’m creating the message that’ll be displayed if an error occurs//
}
#Override
//onAuthenticationFailed is called when the fingerprint doesn’t match with any of the fingerprints registered on the device//
public void onAuthenticationFailed() {
}
#Override
//onAuthenticationHelp is called when a non-fatal error has occurred. This method provides additional information about the error,
//so to provide the user with as much feedback as possible I’m incorporating this information into my toast//
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
}
#Override
//onAuthenticationSucceeded is called when a fingerprint has been successfully matched to one of the fingerprints stored on the user’s device//
public void onAuthenticationSucceeded(
FingerprintManager.AuthenticationResult result) {
if (new SessionManager(context).getUsername() != null && !new SessionManager(context).getUsername().isEmpty()) {
String userName = new SessionManager(context).getUsername();
String pass = new SessionManager(context).getPass();
if (pass != null) {
((SigninActivity) context).requestLoginToServer(userName, pass);
((SigninActivity) context).isSignInButtonClicked = false;
}
}
//context.startActivity(new Intent(context, DashboardActivity.class));
}
}
Signin Class
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Handler;
import android.provider.ContactsContract;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.AppCompatTextView;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import yasiriqbal.ethereum.EthereumApplication;
import yasiriqbal.ethereum.PermissionActivity;
import yasiriqbal.ethereum.R;
import yasiriqbal.ethereum.dashboad.DashboardActivity;
import yasiriqbal.ethereum.models.EthUserModel;
import yasiriqbal.ethereum.models.ServerMessage;
import yasiriqbal.ethereum.network.VolleyRequestHelper;
import yasiriqbal.ethereum.settings.ChangePasswordActivity;
import yasiriqbal.ethereum.signup.MobileCodeVerifyActivity;
import yasiriqbal.ethereum.signup.MobileNumberActivity;
import yasiriqbal.ethereum.signup.SignUpActivity;
import yasiriqbal.ethereum.util.Constants;
import yasiriqbal.ethereum.util.DialogErrorFragment;
import yasiriqbal.ethereum.util.DialogHelper;
import yasiriqbal.ethereum.util.Fonts;
import yasiriqbal.ethereum.util.MyUtils;
import yasiriqbal.ethereum.util.PermissionHandler;
import yasiriqbal.ethereum.util.SessionManager;
public class SigninActivity extends AccountAuthenticatorActivity implements View.OnClickListener, Response.Listener<JSONObject>, Response.ErrorListener {
public static final String PARAM_USER_PASS = "userpassword";
private static final int CODE_EMAIL_NOT_VERIFIED = 408;
private AppCompatTextView txt_loginscreen_not_register_member, txt_loginscreen_header,
txt_loginscreen_forgetpassword, txt_loginscreen_touchid;
private TextInputEditText edit_loginscreen_username, edit_loginscreen_password;
Button btn_loginscreen_signin;
PermissionHandler permissionHandler;
private TextInputLayout layout_loginscreen_password, layout_loginscreen_username;
private KeyStore keyStore;
private Cipher cipher;
private final int CODE_WRONG_PASSWORD = 401;
private final int CODE_INVALID_USER = 400;
private final int CODE_LOGIN_SUCCESS = 200;
public final int CODE_PROFILE_STATUS_COMPLETE = 2;
public final int CODE_MOBILE_NOT_VERIFY = 1;
private DialogHelper dialogHelper;
private final int ACCOUNT_PERMISSION_ID = 1234;
boolean isFromSetting = false;
private static final String KEY_NAME = "ethereum";
private Typeface qanelasRegularTypeFace;
private Typeface qanelasSemiBoldTypeFace;
private String previousUserName = "";
FingerprintHandler handler;
FingerprintManager mFingerprintManager;
public boolean isSignInButtonClicked = false;
FingerprintManager.CryptoObject cryptoObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
if (permissionHandler.isMarshMallow()) {
authenticateWithFingerPrint();
if (permissionHandler.isPermissionAvailable(Manifest.permission.USE_FINGERPRINT)) {
setFingerprintConfig();
} else {
permissionHandler.requestPermission(Manifest.permission.USE_FINGERPRINT);
}
}//end of if is marshmallow
//dialogErrorFragment.show(getFragmentManager(),"dialog");
}//end of onCreate
#TargetApi(Build.VERSION_CODES.M)
private void authenticateWithFingerPrint() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
if (mFingerprintManager.isHardwareDetected()) {
KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (mKeyguardManager.isKeyguardSecure()) {
generateKey();
if (initCipher()) {
cryptoObject = new FingerprintManager.CryptoObject(cipher);
handler = new FingerprintHandler(this);
handler.startAuth(mFingerprintManager, cryptoObject);
}
} else {
Toast.makeText(this, "Lock Screen Security not enabled in Settings.", Toast.LENGTH_LONG).show();
}
}
}
#TargetApi(Build.VERSION_CODES.M)
protected void generateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new RuntimeException("Failed to get KeyGenerator instance", e);
}
try {
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
throw new RuntimeException(e);
}
}
//Create a new method that we’ll use to initialize our cipher//
#TargetApi(Build.VERSION_CODES.M)
public boolean initCipher() {
try {
//Obtain a cipher instance and configure it with the properties required for fingerprint authentication//
cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException |
NoSuchPaddingException e) {
throw new RuntimeException("Failed to get Cipher", e);
}
try {
keyStore.load(null);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
//Return true if the cipher has been initialized successfully//
return true;
} catch (KeyPermanentlyInvalidatedException e) {
//Return false if cipher initialization failed//
return false;
} catch (KeyStoreException | CertificateException
| UnrecoverableKeyException | IOException
| NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to init Cipher", e);
}
}
//xml initalization
private void initResources() {
//textViews initalize
}//end of initResources
#Override
protected void onResume() {
super.onResume();
}//end of onResume
//here to discover fingerprint hardware and set views
#TargetApi(Build.VERSION_CODES.M)
#SuppressWarnings("MissingPermission")
private void setFingerprintConfig() {
FingerprintManager mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
if (mFingerprintManager.isHardwareDetected()) {
if (getPreviousUsername() != null && !getPreviousUsername().isEmpty() && mFingerprintManager.hasEnrolledFingerprints()) {
//TODO show finger print icon that this device support
} else {
//here means user is not enrolled for fingerpring
//TODO handle case when fingerprint not supported
}
}
}//end of setFingerprint
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionHandler.PERMISSIONS_REQUEST == requestCode && grantResults.length > 0 && grantResults[0] > -1) {
setFingerprintConfig();
}
}
//onclick reciver for signin activity
#Override
public void onClick(View v) {
switch (v.getId()) {
default:
throw new IllegalArgumentException(v.getId() + " is not handle in onclick of signing activity");
}//end f switch
}//end of onClick
#Override
protected void onPause() {
super.onPause();
}
//here check if user profile complete then redirect to dashboard or then mobile verify
private void redirectUserAfterSuccessLogin(String data) throws JSONException {
if (!data.isEmpty()) {
Gson gsonForUser = new Gson();
new SessionManager(this).adToken(new JSONObject(data).getString("authenticationToken"));
EthUserModel ethUserModel = gsonForUser.fromJson(data, EthUserModel.class);
EthereumApplication.getInstance().setEthUserLoginObj(ethUserModel);
insertEthUserToContentProvider(ethUserModel);
if (!previousUserName.equals(ethUserModel.getEthUserName()) && !removeAccountFromAccountManager(ethUserModel, edit_loginscreen_password.getText().toString())) {
addAccountToAuthenticator(ethUserModel, edit_loginscreen_password.getText().toString());
startOtherActivity(ethUserModel);
//startSyncAdapter();
}//end of if for removeAccount return false
else {
startOtherActivity(ethUserModel);
//startSyncAdapter();
}//end of else
} else {
//here to show retry login
}
}//end of function
private void startOtherActivity(EthUserModel ethUserModel) {
if (isSignInButtonClicked)
new SessionManager(this).addData(edit_loginscreen_username.getText().toString(), edit_loginscreen_password.getText().toString());
if (txt_loginscreen_touchid.getVisibility() == View.VISIBLE)
try {
handler.StopListener();
} catch (Exception e) {
}
if (ethUserModel.getProfileStatus() == CODE_MOBILE_NOT_VERIFY) {
//redirect to mobile screen
startActivity(new Intent(this, MobileNumberActivity.class));
} else {
//redirect to dashboard if user not from setting
if (!getIntent().getBooleanExtra(Constants.ARG_IS_USER_FROM_SETTING, false)) {
if (EthereumApplication.getInstance().getEthUserLoginObj().getEthUserDoubleAuthenticationStatus() == Constants.ResultCode.CODE_DOUBLE_AUTHENTICATION_TRUE)
startActivity(new Intent(this, MobileCodeVerifyActivity.class)
.putExtra(Constants.MobileCodeVerifyActivity.IS_FROM_SIGNIN, true)
.putExtra(Constants.MobileNumberActivity.EXTRA_MOBILE_NUMBER, EthereumApplication.getInstance().getEthUserLoginObj().getMobileNum()));
else
startActivity(new Intent(this, DashboardActivity.class));
finish();
}
}//end of else
}//end of function
#Override
protected void onStop() {
super.onStop();
}
}//end of activity

Related

Firebase Realtime Database UID different from Authentication UID

I am trying to call for the UID that firebase provides and register it to the Realtime Database. For some reason the two UIDs are different. I think Authentication UID is changing after I register the original UID to Realtime Database. Perhaps the way I am calling the UID is wrong?
Authentication UID: zD40xuce4SWPiidMGOm62hFWOFP2
Realtime Database UID: rhqgglru9FXV5jhITSQmpqwBdc53
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_user);
email = findViewById(R.id.email_create);
password = findViewById(R.id.password_create);
con_password = findViewById(R.id.password_confirm);
auth = FirebaseAuth.getInstance();
registerBtn = findViewById(R.id.Register);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
String txt_con_password = con_password.getText().toString();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
Toast.makeText(New_User.this, "" + currentFirebaseUser.getUid(), Toast.LENGTH_SHORT).show();
String txt_UID = currentFirebaseUser.getUid();
//check empty fields
if (txt_email.isEmpty() || txt_password.isEmpty()) {
Toast.makeText(New_User.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
//check passwords match
else if (!txt_password.equals(txt_con_password)){
Toast.makeText(New_User.this, "Passwords are not matching", Toast.LENGTH_SHORT).show();
}
else{
databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(txt_UID)) {
Toast.makeText(New_User.this, "User ID is taken", Toast.LENGTH_SHORT).show();
}
else {
registerUser(txt_email, txt_password, txt_UID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
}
private void registerUser(String email, String password, String UID) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(New_User.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//doesnt upload login information into realtime database, but registers account
if (task.isSuccessful()) {
databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child("User ID").child(UID).child("email").setValue(email);
databaseReference.child("User ID").child(UID).child("password").setValue(password);
Toast.makeText(New_User.this, "User registered successfully.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(New_User.this, PhysicalParameters.class);
startActivity(intent);
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
FirebaseUser user = auth.getCurrentUser();
Toast.makeText(New_User.this, "Registering user successful", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(New_User.this, Welcome_Page.class);
//startActivity(intent);
}else {
Toast.makeText(New_User.this, "Failed Registration: " + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
fAuth = FirebaseAuth.getInstance();
fAuth.getUid()
For more reference. This is my project
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
public class Register extends AppCompatActivity {
EditText mFullName, mEmail, mPassword, mPhone;
Button mRegisterBtn, pickimagebtn;
TextView mLoginHereBtn,imgsourcetxtview;
FirebaseAuth fAuth;
ProgressBar progressBar;
String encryptionimagestring;
Bitmap bitmap;
ImageView ProfileImage;
SparseArray<Face> faces;
private static final int PICK_IMAGE = 1;
int count = 0;
private byte encryptionkey[] = {9, 115, 51, 86, 105, 4, -31, 23, -68, 88, 17, 20, 3, -105, 119, -53};
private Cipher cipher, decipher;
private SecretKeySpec secretKeySpec;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
imgsourcetxtview =(TextView) findViewById(R.id.imagesoucetxtview);
imgsourcetxtview.setMovementMethod(new ScrollingMovementMethod());
imgsourcetxtview.setSingleLine();
//pick image
pickimagebtn = findViewById(R.id.pickimagebtn);
pickimagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(null)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(Register.this);
}
});
try {
cipher = Cipher.getInstance("AES");
decipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
secretKeySpec = new SecretKeySpec(encryptionkey, "AES");
mFullName = findViewById(R.id.Register_FullName);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mPhone = findViewById(R.id.Register_Phone);
mRegisterBtn = findViewById(R.id.Register_button);
mLoginHereBtn = findViewById(R.id.LoginHere);
mFullName = findViewById(R.id.Register_FullName);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
if (fAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));
finish();
}
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if (TextUtils.isEmpty(mFullName.getText().toString().trim())) {
mFullName.setError("Name is required.");
return;
}
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(mPhone.getText().toString().trim())) {
mPhone.setError("Phone is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if (password.length() < 6) {
mPassword.setError("Password must be >= 6 characters.");
return;
}
if (TextUtils.isEmpty(imgsourcetxtview.getText().toString().trim())) {
imgsourcetxtview.setError("Image is required.");
return;
}
else{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
detectFace(options);
if (faces.size() < 1) {
imgsourcetxtview.setError("Can't detect face.");
return;
}
if (faces.size() > 1) {
imgsourcetxtview.setError("More than one face is detected.");
return;
}
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//add information to firebase
myRef.child("Account").child(fAuth.getUid()).child("name").setValue(AESEncryptionmethod(mFullName.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("phone").setValue(AESEncryptionmethod(mPhone.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("email").setValue(AESEncryptionmethod(mEmail.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("photo").setValue(encryptionimagestring);
myRef.child("Account").child(fAuth.getUid()).child("coin").setValue("0");
Toast.makeText(Register.this, "User created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));
} else {
Toast.makeText(Register.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mLoginHereBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), Login.class));
}
});
}
private String AESEncryptionmethod(String string) {
byte[] stringByte = string.getBytes();
byte[] encryptedByte = new byte[stringByte.length];
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encryptedByte = cipher.doFinal(stringByte);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
String returnString = null;
try {
returnString = new String(encryptedByte, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnString;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result.getUri());
} catch (IOException e) {
e.printStackTrace();
}
imgsourcetxtview.setText(String.valueOf(result.getUri()));
Toast.makeText(
this, "Cropping successful, Sample: " + result.getUri(), Toast.LENGTH_LONG)
.show();
encryptionimage(bitmap);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
public void encryptionimage(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String string=Base64.encodeToString(b, Base64.DEFAULT);
byte[] stringByte = string.getBytes();
byte[] encryptedByte = new byte[stringByte.length];
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encryptedByte = cipher.doFinal(stringByte);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
String returnString = null;
try {
returnString = new String(encryptedByte, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
encryptionimagestring = returnString;
}
private void detectFace(BitmapFactory.Options options) {
/*Bitmap bitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.test1,
options
);*/
Paint paint = new Paint();
paint.setStrokeWidth(6);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(tempBitmap);
canvas.drawBitmap(bitmap,0,0,null);
FaceDetector faceDetector = new FaceDetector.Builder(Register.this).setTrackingEnabled(false)
.build();
if(!faceDetector.isOperational()){
new AlertDialog.Builder(this).setMessage("Could not set up Face Detector!").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
faces = faceDetector.detect(frame);
/*for(int i=0; i<faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
canvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, paint);
}*/
// imageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));
}
}

Android Fingerprint API and Private/Public keys

When I enrol first and only fingerprint and generate KeyPair the PrivateKey gets invalidated when I use it for the second time. This happens only once. Am I the only one having this issue? Is there something wrong with my code?
I cannot use any other key as I'm using PrivateKey to sign data.
Steps:
Wipe all fingerprints
Enrol one fingerprint
Generate KeyPair and use FingerprintManager :: authenticate
During next use of FingerprintManager :: authenticate PrivateKey gets permanently invalidated. This happens only for the first time
Below the code where I generate the KeyPair
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keystore.load(null);
KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
generator.initialize(new KeyGenParameterSpec.Builder("key_name", KeyProperties.PURPOSE_SIGN)
.setDigests(digest) // I have defined digest before
.setSignaturePaddings(paddings) // I have defined paddings before
.setUserAuthenticationRequired(true)
.build());
generator.generateKeyPair();
And here is the code where I invoke fingerprint authentication for data signing:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
Signature signature = Signature.getInstance("signing_algorithm");
PrivateKey privateKey = (PrivateKey) keyStore.getKey("key_name", null);
signature.initSign(privateKey); // Here I get KeyPermanentlyInvalidatedException
CryptoObject crypto = new CryptoObject(signature);
FingerprintManager fingerprintManager = context.getSystemService(FingerprintManager.class);
CancellationSignal cancellationSignal = new CancellationSignal();
AuthenticationCallback authenticationCallback = new AuthenticationCallback() {
...
};
fingerprintManager.authenticate(crypto, cancelationSignal, 0, authenticationCallback, null);
i try this link and work perfectly .
First you need to set Minimum sdk look like the Picture
Second set Permission in Mainfest
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
Third
generateKey() function which generates an encryption key which is then stored securely on the device.
cipherInit() function that initializes the cipher that will be used to create the encrypted FingerprintManager.
CryptoObject instance and various other checks before initiating the authentication process which is implemented inside onCreate() method.
FingerPrintActivty.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class FingerprintActivity extends AppCompatActivity {
private KeyStore keyStore;
// Variable used for storing the key in the Android Keystore container
private static final String KEY_NAME = "androidHive";
private Cipher cipher;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint);
// Initializing both Android Keyguard Manager and Fingerprint Manager
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
textView = (TextView) findViewById(R.id.errorText);
// Check whether the device has a Fingerprint sensor.
if(!fingerprintManager.isHardwareDetected()){
/**
* An error message will be displayed if the device does not contain the fingerprint hardware.
* However if you plan to implement a default authentication method,
* you can redirect the user to a default authentication activity from here.
* Example:
* Intent intent = new Intent(this, DefaultAuthenticationActivity.class);
* startActivity(intent);
*/
textView.setText("Your Device does not have a Fingerprint Sensor");
}else {
// Checks whether fingerprint permission is set on manifest
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
textView.setText("Fingerprint authentication permission not enabled");
}else{
// Check whether at least one fingerprint is registered
if (!fingerprintManager.hasEnrolledFingerprints()) {
textView.setText("Register at least one fingerprint in Settings");
}else{
// Checks whether lock screen security is enabled or not
if (!keyguardManager.isKeyguardSecure()) {
textView.setText("Lock screen security not enabled in Settings");
}else{
generateKey();
if (cipherInit()) {
FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this);
helper.startAuth(fingerprintManager, cryptoObject);
}
}
}
}
}
}
#TargetApi(Build.VERSION_CODES.M)
protected void generateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new RuntimeException("Failed to get KeyGenerator instance", e);
}
try {
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
throw new RuntimeException(e);
}
}
#TargetApi(Build.VERSION_CODES.M)
public boolean cipherInit() {
try {
cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new RuntimeException("Failed to get Cipher", e);
}
try {
keyStore.load(null);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
return true;
} catch (KeyPermanentlyInvalidatedException e) {
return false;
} catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to init Cipher", e);
}
}
}
FingerprintAuthenticationHandler.Class
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.CancellationSignal;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.TextView;
/**
* Created by whit3hawks on 11/16/16.
*/
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
this.update("Fingerprint Authentication error\n" + errString, false);
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
this.update("Fingerprint Authentication help\n" + helpString, false);
}
#Override
public void onAuthenticationFailed() {
this.update("Fingerprint Authentication failed.", false);
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
this.update("Fingerprint Authentication succeeded.", true);
}
public void update(String e, Boolean success){
TextView textView = (TextView) ((Activity)context).findViewById(R.id.errorText);
textView.setText(e);
if(success){
textView.setTextColor(ContextCompat.getColor(context,R.color.colorPrimaryDark));
}
}
}
Hope it help.
you can see this one on github: hope it will help you : Confirm Credentials

Awkward session error with magento cookie parsing in Android App

I am working on an Android app which uses sessions by managing cookies from an API based on magento backend.
On the app side, I am using Volley Library for network request. I have successfully got the network response and from that I have fetched the "Set-Cookie" value. Now when I am attaching this cookie to the header but the server doesn't validate my session.
The strange thing is I tried to request the same JSON request from a rest client and then used the cookie from that and added to the header as a static value and then I was provided session access. I completely have no idea regarding what is going on. Why the cookies from rest client is working while the cookie value from my network response doesn't.
Here is my SignIn Activity code where I am doing a login json request and storing the cookie value.
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc#xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the code for the fragment where I am doing a check session test with the stored cookie received from network response (Note: I replaced the cookie with the one I got from rest client and it worked!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
There is no structural difference between the rest client cookie and the one recieved in app:
rest client cookie : frontend=48b1i38fgls4d0241mp6d6rrr0
app side cookie : frontend=86n349m3patu37eud00ntobd90
Thanks in advance. It will be a life saver if some one can help.

Avoiding multiple/double/two permission screens when getting a token via Google Play Services

The user is being presented with multiple permission screens for the same permissions in my app/game.
First, I use mGoogleApiClient = new GoogleApiClient.Builder ( .. to get the user's email address. A "Google+" permissions screen pops up.
Then, I use GoogleAuthUtil.getToken(context, accountName, scope); to get a token, where accountName is the email address. A "Google" permissions screen pops up.
Is there any way I can avoid two permission screens?
Full code is below.
package com.flyingsoftgames.googleplayservices;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.games.Players;
import com.google.android.gms.games.Games;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.plus.Account;
import com.google.android.gms.plus.Plus;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import org.apache.cordova.*;
import java.io.IOException;
import android.util.Log;
public class GooglePlayServices extends CordovaPlugin implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String LOG_TAG = "GooglePlayServices";
private static final int REQ_SIGN_IN_REQUIRED = 55664;
public static GoogleApiClient mGoogleApiClient = null;
public CallbackContext tryConnectCallback = null;
public String accessToken = "";
private int connectionAttempts = 0;
#Override public void onConnectionFailed (ConnectionResult result) {
String errormessage = result.toString();
Log.w (LOG_TAG, errormessage);
connectionAttempts += 1;
if (!result.hasResolution() || connectionAttempts >= 2) {
Log.w (LOG_TAG, "Error: no resolution. Google Play Services connection failed.");
tryConnectCallback.error ("Error: " + errormessage + "."); tryConnectCallback = null;
return;
}
try {
result.startResolutionForResult (cordova.getActivity(), result.getErrorCode());
} catch (SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect ();
}
}
#Override public void onConnected (Bundle connectionHint) {
String mAccountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
new RetrieveTokenTask().execute (mAccountName);
Games.setViewForPopups (mGoogleApiClient, webView);
}
public void onActivityResult (int requestCode, int responseCode, Intent intent) {
if (!mGoogleApiClient.isConnecting()) mGoogleApiClient.connect ();
}
#Override public void onConnectionSuspended (int cause) {
mGoogleApiClient.connect ();
}
public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
if ("getPlayerId".equals(action)) {
String playerId = Games.Players.getCurrentPlayerId (mGoogleApiClient);
callbackContext.sendPluginResult (new PluginResult (PluginResult.Status.OK, playerId));
} else if ("tryConnect".equals(action)) {
tryConnect (callbackContext);
} else if ("getAccessToken".equals(action)) {
callbackContext.sendPluginResult (new PluginResult (PluginResult.Status.OK, accessToken));
}
return true;
}
// tryConnect runs the callback with a value of false if Google Play Services isn't available.
public void tryConnect (CallbackContext callbackContext) {
boolean isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
if (!isGpsAvailable) {
callbackContext.sendPluginResult (new PluginResult (PluginResult.Status.OK, false));
return;
}
tryConnectCallback = callbackContext;
mGoogleApiClient = new GoogleApiClient.Builder (cordova.getActivity().getApplicationContext())
.addConnectionCallbacks (this)
.addOnConnectionFailedListener (this)
.addApi (Games.API)
.addScope (Games.SCOPE_GAMES)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build ();
mGoogleApiClient.connect ();
}
private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
#Override protected String doInBackground (String... params) {
String accountName = params[0];
String scope = "oauth2:https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
Context context = cordova.getActivity().getApplicationContext();
try {
accessToken = GoogleAuthUtil.getToken(context, accountName, scope);
Log.e (LOG_TAG, "127: " + accessToken);
} catch (IOException e) {
String errormessage = e.getMessage();
Log.e (LOG_TAG, errormessage);
if (tryConnectCallback != null) tryConnectCallback.error ("Error: " + errormessage + "."); tryConnectCallback = null;
} catch (UserRecoverableAuthException e) {
cordova.getActivity().startActivityForResult (e.getIntent(), REQ_SIGN_IN_REQUIRED);
} catch (GoogleAuthException e) {
String errormessage = e.getMessage();
Log.e (LOG_TAG, errormessage);
if (tryConnectCallback != null) tryConnectCallback.error ("Error: " + errormessage + "."); tryConnectCallback = null;
}
return accessToken;
}
#Override protected void onPostExecute (String newAccessToken) {
super.onPostExecute (newAccessToken);
accessToken = newAccessToken;
if (tryConnectCallback != null) {
String playerId = Games.Players.getCurrentPlayerId (mGoogleApiClient);
tryConnectCallback.sendPluginResult (new PluginResult (PluginResult.Status.OK, playerId));
tryConnectCallback = null;
}
}
}
}
I figured out that if I use just AccountPicker.newChooseAccountIntent, I do not need to do mGoogleApiClient = new GoogleApiClient.Builder: https://github.com/agamemnus/googleplaytoken.

Facebook integration in android application [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Is there any api for facebook to integration in android?
I got a requirement to publish images to facebook through android application.
Please give links or suggestions regarding this..
If you had taken the time to Google "Android Facebook SDK" you'd have immediately found the official Android Facebook SDK: http://github.com/facebook/facebook-android-sdk
Having used it in a project I can say it's a little rough around the edges as the new oAuth / Graph API based stuff is quite young, but it works well with a little tweaking.
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.sun.medialib.mlib.Image;
import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.Facebook;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class TestRocket extends Activity implements LoginListener {
public FBRocket fbRocket;
public static String currentFileName ;
public final String images[] = {"http://safesport.site40.net/tv.jpg"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
fbRocket = new FBRocket(this, "test",
"ommited");
if (fbRocket.existsSavedFacebook()) {
fbRocket.loadFacebook();
return;
} else {
//fbRocket.login(R.layout.testrocket);
fbRocket.login(R.layout.testrocket);
}
}
public void onLoginFail() {
fbRocket.displayToast("Login failed!");
//fbRocket.login(R.layout.correr);
}
public String setFileName(String filename) {
// TODO Auto-generated method stub
TestRocket.currentFileName = filename;
return filename;
}
public void onLoginSuccess(Facebook facebook) {
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
String data = sdf.format(new Date());
String time = sdf1.format(new Date());
try {
facebook.setStatus("Start Walk:"+time+"\n"+ "Day:"+data+"\n"+"Where:"+"\n"
+"http://maps.google.com/?q=http://safesport.site40.net/"+currentFileName);
fbRocket.displayToast("Status Posted Successfully!! ");
return ;
} catch (ServerErrorException e) {
if (e.notLoggedIn()) {
fbRocket.login(R.layout.ciclismo);
} else {
System.out.println(e);
}
}
}
}
I explained the process in detail together with a simple sample code. You can find it here:
http://developer.blog.appxtream.com/?p=34
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/)
package facebooklocation.facebooklocation;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CallbackManager callbackManager;
ImageView iv_image, iv_facebook;
TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
LinearLayout ll_facebook;
String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
boolean boolean_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getKeyHash();
listener();
}
private void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_dob = (TextView) findViewById(R.id.tv_dob);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_facebook = (TextView) findViewById(R.id.tv_facebook);
ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
FacebookSdk.sdkInitialize(this.getApplicationContext());
}
private void listener() {
tv_facebook.setOnClickListener(this);
ll_facebook.setOnClickListener(this);
iv_facebook.setOnClickListener(this);
}
private void facebookLogin() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
+ "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
boolean_login = true;
tv_facebook.setText("Logout from Facebook");
Log.e("object", object.toString());
str_facebookname = object.getString("name");
try {
str_facebookemail = object.getString("email");
} catch (Exception e) {
str_facebookemail = "";
e.printStackTrace();
}
try {
str_facebookid = object.getString("id");
} catch (Exception e) {
str_facebookid = "";
e.printStackTrace();
}
try {
str_birthday = object.getString("birthday");
} catch (Exception e) {
str_birthday = "";
e.printStackTrace();
}
try {
JSONObject jsonobject_location = object.getJSONObject("location");
str_location = jsonobject_location.getString("name");
} catch (Exception e) {
str_location = "";
e.printStackTrace();
}
fn_profilepic();
} catch (Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
facebookLogin();
}
}).executeAsync();
}
#Override
public void onError(FacebookException e) {
Log.e("ON ERROR", "Login attempt failed.");
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
}
}
private void getKeyHash() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void fn_profilepic() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "large");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Response 2", response + "");
try {
String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
Log.e("Picture", str_facebookimage);
Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
} catch (Exception e) {
e.printStackTrace();
}
tv_name.setText(str_facebookname);
tv_email.setText(str_facebookemail);
tv_dob.setText(str_birthday);
tv_location.setText(str_location);
}
}
).executeAsync();
}
#Override
public void onClick(View view) {
if (boolean_login) {
boolean_login = false;
LoginManager.getInstance().logOut();
tv_location.setText("");
tv_dob.setText("");
tv_email.setText("");
tv_name.setText("");
Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
tv_facebook.setText("Login with Facebook");
} else {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
facebookLogin();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
LoginManager.getInstance().logOut();
}
}

Categories

Resources