Android firebase throws authentication error while trying to access storage - java

EDIT: I just restarted Android Studio after cleaning the project and invalidating cache. Now I get this error -
E/StorageException: { "error": { "code": 403, "message":
"Permission denied. Could not perform this operation" }}
I'm getting the following error that prints infinitely.
2020-09-27 17:00:32.931 11755-11863/com.example.XXXXXX E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
In my app I've created the user properly, and FirebaseAuth.getInstance().getCurrentUser(); does NOT return null. But if it does, I handle it by logging them in successfully or creating another user. My app now has 160+ users created, in less than half a day. I don't think I've even run the app that many times for testing. 'Sign in with email', and 'anonymous sign in' options are enabled in auth settings.
The problem starts when I try to access the storage. I get the above mentioned auth token error. The folder and file exist and this is how I'm trying to download the files -
fstore.child("gs://XXXXXX-XXXX.appspot.com/Books/XXXX").listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult listResult) {
for(StorageReference sref : listResult.getItems())
{
tempFilename = sref.getName();
File tmpFile = new File(tempSubDir, tempFilename);
try {
tmpFile.createNewFile();
sref.getFile(tmpFile).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(tabtwoactivity.this, "File download failed!", Toast.LENGTH_LONG).show();
System.out.println("ERROR: "+ e.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("IIIIII: "+sref.getName());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(tabtwoactivity.this, "Fetching Directory XXXXX Failed", Toast.LENGTH_LONG).show();
}
});
I've tried using fstore.child("XXXX").listAll() but that gave me an avalanche of different errors, mainly focused around Folder not found. My storage has the folder and files. I've even played around with the storage rules - allow read, write;, allow read, write: if request.auth!=null, allow read, write: if request.auth==null. But nothing worked.
What am I doing wrong?

Paste this in your google.json:
service firebase.storage {
// The {bucket} wildcard indicates we match files in all storage buckets
match /b/{bucket}/o {
// Match filename
match /filename {
allow read: if true;
allow write: if true;
}
}
}

Related

FirebaseUser password not updating through updatePassword() method in android

I am trying to update or reset the user's password in my Android application using Firebase Authentication. For this, I am using the updatePassword() method provided by FirebaseUser class, but it is throwing the code in addOnFailureListener() and I am unable to figure out why. please help me. I have provided the code to update the password below:
updatePasswordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newPassword = enterPasswordEditText.getText().toString().trim();
String confirmPassword = confirmPasswordEditText.getText().toString().trim();
if (!newPassword.equals(confirmPassword)) {
Toast.makeText(EditProfileActivity.this, "Passwords don't match!", Toast.LENGTH_SHORT)
.show();
} else {
//Updating password
firebaseUser.updatePassword(newPassword)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(EditProfileActivity.this, "Password changed successfully", Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditProfileActivity.this, "Error in changing password", Toast.LENGTH_SHORT)
.show();
}
});
}
}
});
You're getting the following error:
Error in changing password: This operation is sensitive and requires recent authentication. Log in again before retrying this request
Because changing the password is considered a sensitive operation. This means that in order to perform that operation, Firebase requires that the user has recently signed in.
If the user hasn't recently signed in, meaning that 5 minutes have already passed, when you try to perform such a sensitive operation, Firebase throws an exception that contains the error message from above.
The simplest solution for this situation would be to ask the user to re-enter their credentials and retry the operation.
Here is the official documentation for FirebaseAuthRecentLoginRequiredException.

ApiException in android with status code 7 while using safetynet attestation API

Apiexception with status code 7 occurs due to network error but that doesn't seem to be the issue since internet is working fine on the device.
Code snippet-
SafetyNet.getClient(this).attest(nonce, API_KEY)
.addOnSuccessListener(this,
new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(SafetyNetApi.AttestationResponse response) {
mResult = response.getJwsResult();
Log.i(TAG, "safetynet result is" + mResult + "\n");
mainres = initialDataExtraction(response.getJwsResult());
Log.i(TAG, "Main result is" + mainres + "\n");
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
int statuscode = apiException.getStatusCode();
Log.i(TAG,"EXCEPTION CODE: "+statuscode);
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
The issue was with my API key. I was using the API key of a colleague which was restricted. Using my own API key it worked fine.
My issue was i registered SHA1 from play console but not SHA1 in my android studio.
We have this error when the Safetynet API quotas are exceeded. The default quota is 10_000 requests per day, reset at midnight.
Downgrading the com.google.android.gms:play-services-safetynet dependency on the app's build.gradle from 18.0.1 to 18.0.0 fixed it for me.
Do still double-check your API key restrictions (SHA1, package name) since they might cause this error too if there's something wrong with them, but downgrading the API a notch fixed it for me.
Also, double-check if you're reading the APK key from your keys file correctly, try hard-coding the API key into the class as a String and see if it works, of course don't do this in production code, you must hide your API key in release.

Unable to match class for part: 'Lrx/Observable;' (unknown error)

hey guys am trying to execute the below method but am getting an error which says:
Unable to match class for part: 'Lrx/Observable;
my method:
public void SendNote(){
titleStr = etxtTitle.getText().toString();
// saving objects
NotesRealmClass notesRealmClass = new NotesRealmClass();
notesRealmClass.setTitle("try");
// save object asynchronously
Backendless.Persistence.save(notesRealmClass, new AsyncCallback<NotesRealmClass>() {
public void handleResponse(NotesRealmClass note) {
// new Contact instance has been saved
Toast.makeText(getActivity(), "Successfully posted ", Toast.LENGTH_SHORT).show();
}
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), "" + fault.getMessage(), Toast.LENGTH_SHORT).show();
// an error has occurred, the error code can be retrieved with fault.getCode()
}
}); }
here am trying to save an Object into Backendless Server but am getting this error, any one can explain me what this error is trying to tell ?? i searched around but didnt get anything yet
well it turns out that its a fault in realm , according to this https://www.bountysource.com/issues/29233605-java-lang-noclassdeffounderror-rx-observable-in-0-87-0 , for fixing it we just have to put compile 'io.reactivex:rxjava:1.0.16' in our grade file

Google Drive for Android SDK Doesn't List Files

I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});

AccountManagerFuture.getResult() results in "Couldn't sign in" screen

I am attempting to use AccountManager to get a token for an installed Google account. When I call getResult() on my AccountManagerFuture object, I get the "Couldn't sign in" screen on the device (which further says, "There was a probem communicating with Google servers. Try again later.). I checked that a network connection is available prior to calling this method. I also checked on the device that I am able to access, e.g. google.com, in the browser. Here is the code for my AccountManagerCallback:
amf = accMgr.getAuthToken(account, authTokenType, null, true,
new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> arg0) {
Bundle result;
Intent i;
String token;
try {
result = arg0.getResult();
if (result.containsKey(AccountManager.KEY_INTENT)) {
i = (Intent)result.get(AccountManager.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);
} else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);
}
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}, handler);
Also, these entries in LogCat might be helpful:
08-02 15:51:00.911: I/GLSUser(10134): GLS error: Unknown XXXX#gmail.com com.google
08-02 15:51:00.911: V/GoogleLoginService(10134): Returning error intent with: ComponentInfo{com.google.android.gsf.login/com.google.android.gsf.login.LoginActivity}
08-02 15:51:03.294: I/ActivityManager(324): START {cat=[XXXX#gmail.com] flg=0x10000000 cmp=com.google.android.gsf.login/.LoginActivity (has extras) u=0} from pid 11147
(Note: Actual gmail account name removed to avoid spam.)
Are you generating a signed APK? If you don't generate a signed APK (e.g., if you just hit "run app") you won't be able to take advantage of registered Google accounts on the device. So you'll have to hit "login with other" and login the roundabout way.
(Disclaimer: I didn't try to run your code, but it sounds like an issue I ran into earlier.)

Categories