Im working on a android app with email-password login.
The user is created in a local sqlite db and in firebase + auth.
Situation: The user uninstalls the app, the local db is deleted. Then the user re-installs the app and wants to login using old credentials, But the user does not exist locally thus the app tries to create a new. - but the user already exist remote in my firebase users table + auth.
Question: How do I query either firebase auth or firebase for the user info only using email, pass and perhaps a few extras.
Most answers I found refer to using the update event from firebase, but at this point it´s not possible as the user is not yet authenticated
I solved it myself.
It was simple and not at all. A part of my fix is below. But in short. I get the user from firebase, then make an update to firebase and then I restore the user in a addValueEventListener(new ValueEventListener()
_fbAuth.signInWithEmailAndPassword(_email, _password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Firebase login success");
FirebaseUser fbUser = _fbAuth.getCurrentUser();
String uid = fbUser.getUid();
FireBaseWriteHelper wh = new FireBaseWriteHelper();
FireBaseReadHelper fireBaseReadHelper = new FireBaseReadHelper(getApplicationContext(), uid, Util.VERSION_KEY_FREE);
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
Date date = new Date();
wh.UpdateUserLastLogIn(uid, format.format(date));
_user = _userHelper.CheckUserExist(_email, _password);
mPasswordView.setError(null);
mEmailView.setError(null);
} else {
try {
throw task.getException();
} catch (FirebaseAuthInvalidUserException e) {
} catch (FirebaseAuthInvalidCredentialsException e) {
} catch (FirebaseNetworkException e) {
} catch (Exception e) {
}
}
}
});
You can use the Firebase in Offline mode. You don't need to use two databases. Guide here.
Related
i'm working on Login and register activity using Firebase that requires me to strore data in realtime database. I setup the firebase realtime database location in South East Asia, and this is the supposed URL: https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/
and this is my code on writing Users data on the DB, after succesfully creating user using .createUserWithEmailAndPassword(email, password) ==>>
myRef = FirebaseDatabase.getInstance().getReference("Users");
String currUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
User user = new User(username, "default");
myRef.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
} else{
}
}
});
After debugging, i found that the process fails at myRef.setValue(user) because the URL set up for database reference is https://chatapp-5e8ce-default-rtdb.firebaseio.com/Users instead of https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/Users.
How do i set the URL so it match my firebase database location?
You can pass the URL to FirebaseDatabase.getInstance(), so:
myRef = FirebaseDatabase.getInstance("https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
You can also download an updated google-services.json, which will contain the correct string and replace the existing (incompletely) file in your Android Studio project with that.
I am using Cloud Firestore in my Android app. It's a quiz application where I randomly get documents from Firestore. When the internet connection is good, the app works fine. When the network gets disconnected and then again gets connected, I am unable to read the documents. When I debug, I find that my get() method is not getting executed at all.
Iterator iterator = randomIds.iterator();
while (iterator.hasNext()) {
String documentId = (String) iterator.next();
DocumentReference documentReference = db.collection(categoryName).document(documentId);
if (documentReference!=null) {
documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
System.out.println("Task successful");
DocumentSnapshot document = task.getResult();
questionDetailsObj = new QuestionDetails();
questionDetailsObj = document.toObject(QuestionDetails.class);
if (questionDetailsObj != null) {
System.out.println("Question details: " + questionDetailsObj.getQuestion_text());
// Adding the questions to a list
questionsList.add(questionDetailsObj);
}
} else {
Log.d("MainActivity", "get() failed with " + task.getException());
}
}
});
}
}
I want to retrieve 10 documents. Sometimes, few documents are retrieved successfully and for the others I get the exception
get() failed with com.google.firebase.firestore.FirebaseFirestoreException:
Failed to get document because the client is offline.
I don't understand why would some documents come successfully and some fail to get retrieved. Please help me understand if any code changes are required.
I am developing an Android App using Firebase, In my app I am using Firebase Anonymous Login and Google sign In.
When the application starts if the user is not Logged In, then I am using Anonymous Authentication to log the user in.
Afterwards when user chooses to Sign In using Google, then I am converting Anonymous Account to a permanent account.
My issue over here is, When user's account is converted from Anonymous Account to permanent account (using Google Sign In in this case), I am not getting User's Display Name and Photo Url.
For converting from Anonymous Account to permanent account I am using below code.
AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful());
if (!task.isSuccessful()) {
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",Toast.LENGTH_SHORT).show();
//If Google Account already linked up with other UID
Tasks.await(mAuth.signInWithCredential(credential)).getUser();
}
}
});
After the Sign In process completes, the AuthStateListener onAuthStateChanged is called, Then in onAuthStateChanged I am extracting User's Display Name, User's Photo Url and User's Email. Below is the onAuthStateChanged code.
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null && !(user.isAnonymous())) {
Log.d("userDetails", "UID: " + user.getUid());
Log.d("userDetails", "Name: " + user.getDisplayName());
Log.d("userDetails", "PhotoUrl: " + user.getPhotoUrl().toString());
Log.d("userDetails", "Email: " + user.getEmail());
}
In the log I am getting null for user.getDisplayName() and user.getPhotoUrl()
I don't understand what I am doing wrong. Please help.
Thanks & Regards,
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.getProviderData();
loop through providers and get the desired provider
userData.getProviderId().equals(GoogleAuthProvider.PROVIDER_ID)
Uri photoUrl = userData.getPhotoUrl();
When linking accounts (or even on every sign in), call this function
Future<void> updateMissingUserPropertise(User user) async {
if (user.photoURL == null) await user.updatePhotoURL(user.providerData[0].photoURL);
if (user.displayName == null) await user.updateDisplayName(user.providerData[0].displayName);
}
In order to support multiple providers, each of which might hold a different name, photo, or phone number, Firebase auth does not modify the user properties when linking accounts.
Even if the user signs out later and signs in with Google, or any other federated account, it does not change the user properties.
The function above 'fixes' the missing user properties by grabbing them from the first provider, which is Google in your case, and setting them in the user properties for good.
The more complex version of this function, which supports the case of multiple providers, loops through the providers until a DisplayName or a photoURL are found.
Future<void> updateMissingUserPropertise(User user) async {
if (user.photoURL == null) {
user.providerData.forEach((provider) async {
if (provider.photoURL != null) {
await user.updatePhotoURL(provider.photoURL);
return;
}
});
}
if (user.displayName == null) {
user.providerData.forEach((provider) async {
if (provider.displayName != null) {
await user.updateDisplayName(provider.displayName);
return;
}
});
}
}
i have set up firebase storage for my app, and added the code for anonymous auth on the app and on the firebase console.
it worked at first, but i dont know why it stopped working, saying that the user does not have permission to access the object
Anonymous auth is correctly set up and i did see it working, code is almost like Google Firebase docs
logcat:
D/FirebaseAuth: signInAnonymously:onComplete:true
D/FirebaseAuth:
onAuthStateChanged:signed_in: (Random auth user id)
... When i request the item from firebase
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.FirebaseException: An internal error has occured. [Internal error encountered.]
I/DpmTcmClient: RegisterTcmMonitor
from: com.android.okhttp.TcmIdleTimerMonitor W/NetworkRequest: no auth
token for request E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
Can Someone help?
Declaring Variables
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
on the OnCreate method
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("FirebaseAuth", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("FirebaseAuth", "onAuthStateChanged:signed_out");
}
// ...
}
};
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("FirebaseAuth", "signInAnonymously:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("FirebaseAuth", "signInAnonymously", task.getException());
Toast.makeText(SingleMemeEditor.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
and the method that gets from storage:
Bitmap bmp;
final Context lContext = context; //getting the MainActivity Context
final String lFileName = fileName; //filename to download
final String lCatPath = catPath; //internal categorization folder
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl(context.getResources().getString(R.string.firebase_bucket));
// Create a reference with an initial file path and name
StorageReference filesRef = storageRef.child("files/" + fileName);
try
{
final File localFile = File.createTempFile("images", "jpg");
filesRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>()
{
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot)
{
// Local temp file has been created
File file = new File(getDirectory(lContext)
+ File.separator + lCatPath + File.separator + lFileName);
try
{
Boolean b = file.createNewFile();
if(b)
{
FileInputStream in = new FileInputStream(localFile);
FileOutputStream out = new FileOutputStream(file);
// Transfer bytes from in to out
byte[] buf = new byte[(int)localFile.length()];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
Drawable.createFromPath(file.getPath())).getBitmap());
}
catch (IOException ex)
{
// Handle any errors
Log.e("CopyingFromTemp", ex.getMessage());
}
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception ex)
{
// Handle any errors
Log.e("FirebaseDownloadError", ex.getMessage());
}
});
}
catch(Exception ex)
{
Log.e("FirebaseDownloadError", ex.getMessage());
}
also i'm using standard security rules:
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
as Benjamin Wulfe hinted, i deleted the App's data on the phone and it worked, which means that some kind of Token data was stored on the phone and Anonymous Auth was getting an old session data.
so i added a sign out code before signInAnonymously
mAuth.signOut();
and done!
Thanks to you all for the help!
EDIT: I found another method which is better than signing out and in again (which lead to hundreds of unused anonymous users on the firebase console, and that because the app is not in production yet, would have been millions).
this is what i did:
if (mAuth.getCurrentUser() != null)
{
mAuth.getCurrentUser().reload();
}
else
{
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
Log.d("FirebaseAuth", "signInAnonymously:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
{
Log.w("FirebaseAuth", "signInAnonymously", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
this just reloads current authenticated (anonymous) user.
The message " W/NetworkRequest: no auth token for request " is key for debugging this issue.
This log message means that Firebase Storage did not see any login in the current context. This includes anonymous logins. It means that no authorization was passed to the backend and the only way this will be allowed is if you set your rules to be completely open (public access) which is not recommended (see below).
//this sets completely open access to your data
allow read, write;
I would review the code you have for logging in and ensure it successfully completes before any storage operation is done.
If you are sure your auth code is correct, try resetting data on the device so that no saved state might be there to mess up the application's authorization information.
You might have to check your RULES for storage in firebase console. By default it is set to only permit to authenticated user only
like this
allow read, write: if request.auth != null;
Sometime its disconnect from firebase database,So Connect your app with firebase authentication in android studio through firebase assistance tool.
I am creating an box android app that allows user to upload media files on their account.
I have set up my client id and client secret,it is authenticating my app too.
Uploading part is also done,but the problem i am facing is to save the auth data [which is obviously needed so user is not needed to login again and again]
Load, save and use of authentication data in Box Android API
the solution given above is not working [may b they have removed 'Utils.parseJSONStringIntoObject' method]
i can store the access token and refresh token but whats the point of saving when i cant use them to re authenticate a user
switch (requestCode)
{
case AUTHENTICATE_REQUEST:
if (resultCode == Activity.RESULT_CANCELED)
{
String failMessage = data.getStringExtra(OAuthActivity.ERROR_MESSAGE);
Toast.makeText(this, "Auth fail:" + failMessage, Toast.LENGTH_LONG).show();
// finish();
}
else
{
BoxAndroidOAuthData oauth = data.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
BoxAndroidClient client = new BoxAndroidClient(BoxSDKSampleApplication.CLIENT_ID, BoxSDKSampleApplication.CLIENT_SECRET, null, null);
client.authenticate(oauth);
String ACCESS_TOKEN=oauth.getAccessToken();
String REFRESH_TOKEN=oauth.getRefreshToken();
Editor editor = prefs.edit();
editor.putString("ACCESS_TOKEN", ACCESS_TOKEN);
editor.putString("REFRESH_TOKEN", REFRESH_TOKEN);
editor.commit();
BoxSDKSampleApplication app = (BoxSDKSampleApplication) getApplication();
client.addOAuthRefreshListener(new OAuthRefreshListener()
{
#Override
public void onRefresh(IAuthData newAuthData)
{
Log.d("OAuth", "oauth refreshed, new oauth access token is:" + newAuthData.getAccessToken());
//---------------------------------
BoxOAuthToken oauthObj=null;
try
{
oauthObj=getClient().getAuthData();
}
catch (AuthFatalFailureException e)
{
e.printStackTrace();
}
//saving refreshed oauth object in client
BoxAndroidOAuthData newAuthDataObj=new BoxAndroidOAuthData(oauthObj);
getClient().authenticate(newAuthDataObj);
}
});
app.setClient(client);
}
i have referred https://github.com/box/box-android-sdk-v2/tree/master/BoxSDKSample example
can any one tell me what i am doing wrong or any alternative to authenticate user using authdata,access token,refresh token?
UPDATE
refreshing token as they have said
'Our sdk auto refreshes OAuth access token when it expires. You will want to listen to the refresh events and update your stored token after refreshing.'
mClient.addOAuthRefreshListener(new OAuthRefreshListener()
{
#Override
public void onRefresh(IAuthData newAuthData)
{
Log.d("OAuth", "oauth refreshed, new oauth access token is:" + newAuthData.getAccessToken());
try
{
oauthObj=mClient.getAuthData();
mClient.authenticate(newAuthData);
String authToken=null;
//Storing oauth object in json string format
try
{
authToken = new BoxJSONParser(new AndroidBoxResourceHub()).convertBoxObjectToJSONString(newAuthData);
prefs.edit().putString("BOX_TOKEN", authToken).commit();
//saving authToken in shared Preferences
mClient.authenticate(newAuthData);
String ACCESS_TOKEN=newAuthData.getAccessToken();
String REFRESH_TOKEN=newAuthData.getRefreshToken();
Log.v("New Access token ", oauthObj.getAccessToken());
Log.v("New Refresh token ", oauthObj.getRefreshToken());
editor.putString("ACCESS_TOKEN", ACCESS_TOKEN);
editor.putString("REFRESH_TOKEN", REFRESH_TOKEN);
prefs.edit().putString("BOX_TOKEN", authToken).commit();
editor.commit();
}
catch (BoxJSONException e1)
{
e1.printStackTrace();
}
Log.v("Token Refreshed", " ");
}
catch (AuthFatalFailureException e)
{
e.printStackTrace();
}
}
});
app.setClient(mClient);
}
onClientAuthenticated();
In main activity,fetching stored token
try
{
stored_oauth_token=prefs.getString("BOX_TOKEN", null);
authData = new BoxJSONParser(new AndroidBoxResourceHub()).parseIntoBoxObject(stored_oauth_token, BoxAndroidOAuthData.class);
}
catch (BoxJSONException e)
{
e.printStackTrace();
}
mClient = new BoxAndroidClient(BoxSDKSampleApplication.CLIENT_ID, BoxSDKSampleApplication.CLIENT_SECRET, null, null);
mClient.authenticate(authData);
BoxSDKSampleApplication app = (BoxSDKSampleApplication) getApplication();
app.setClient(mClient);
i tried this app to upload a file after existing ,it did work
but after 60-70 odd minutes i couldn't upload file.
is there anything wrong in my code ?
This is how I initialize my Box client:
mClient = new BoxClient(BOX_CLIENT_ID, BOX_CLIENT_SECRET, null, null);
mClient.addOAuthRefreshListener(new OAuthRefreshListener() {
#Override
public void onRefresh(IAuthData newAuthData) {
try {
String authToken = new BoxJSONParser(new AndroidBoxResourceHub()).convertBoxObjectToJSONString(newAuthData);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("box_token", authToken).commit();
} catch (BoxJSONException e) { }
}
});
mAuthToken = prefs.getString("box_token", null);
if (mAuthToken != null) {
BoxAndroidOAuthData authData = new BoxJSONParser(
new AndroidBoxResourceHub()
).parseIntoBoxObject(mAuthToken, BoxAndroidOAuthData.class);
mClient.authenticate(authData);
}
if (!mClient.isAuthenticated()) {
Intent intent = OAuthActivity.createOAuthActivityIntent(context, BOX_CLIENT_ID, BOX_CLIENT_SECRET, false, "https://yoururl.com/");
((Activity) context).startActivityForResult(intent, BOX_AUTH_REQUEST_CODE);
}
So for the auth refresh there are a couple of things to be considered:
box client automatically refreshes OAuth tokens, you'll want to attach a OAuthRefreshListener to listen to the refresh, if you want to persist, persist the oauth data passed into the refresh listener. The listener only update your persisted oauth data, you don't need to re-authenticate in the refresh listener, sdk does the re-authenticate automatically.
When you first initiate box client, you need to authenticate either by persisted auth, or the OAuth UI. The logic should be:
check client.isAuthenticated();
2.1 If authenticated, do nothing.
2.2 if not authenticated, try to check whether there's persisted auth data. If so, authenticate by client.authenticate(oauthdata);
2.3 if 2.2 failed, start OAuth UI flow.
2.4 at last, in case of OAuthFatalFailureException, start OAuth UI flow.