Android Firebase Authentication - How to Link Existing User Account to Anonymous Account - firebase

I am having some trouble understanding how to link an existing email account to an anonymous firebase account. is this possible ? or does it only link if the email account is new ?
when i call the following code to link accounts both the anonymous account and existing account exist. but if its a new email account then i see that the new email account as the same uid as the anonymous account and the anonymous account is gone.
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w(TAG, "linkWithCredential:failure", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
so my question is: am i able to link anonymous user account to EXISTING user account ? because then my firebase console is going to be filled with anonymous user entries.
UPDATE: Using the firebase mergService here how can i delete the anonymous account ? i dont see it returning a credential for me to delete.
the mergeService describe looks like this:
public class MyManualMergeService extends ManualMergeService {
private Iterable<DataSnapshot> mChatKeys;
#Override
public Task<Void> onLoadData() {
final TaskCompletionSource<Void> loadTask = new TaskCompletionSource<>();
FirebaseDatabase.getInstance()
.getReference()
.child("chatIndices")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
mChatKeys = snapshot.getChildren();
loadTask.setResult(null);
}
#Override
public void onCancelled(DatabaseError error) {
FirebaseCrash.report(error.toException());
}
});
return loadTask.getTask();
}
#Override
public Task<Void> onTransferData(IdpResponse response) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference chatIndices = FirebaseDatabase.getInstance()
.getReference()
.child("chatIndices")
.child(uid);
for (DataSnapshot snapshot : mChatKeys) {
chatIndices.child(snapshot.getKey()).setValue(true);
DatabaseReference chat = FirebaseDatabase.getInstance()
.getReference()
.child("chats")
.child(snapshot.getKey());
chat.child("uid").setValue(uid);
chat.child("name").setValue("User " + uid.substring(0, 6));
}
return null;
}
}
this gets called after user transitions from anonymous user to a real account. how can i then know the credential so i can delete the anonymous account ?

You can't link an existing credential to anonymous user.
You have to basically copy the data of the anonymous user to the existing credential user and then delete the anonymous user.
It is not possible for Firebase to handle this for you. You have 2 users with different uids and data saved on each users, not to mention different profile data on each. Firebase doesn't know which user to keep and how to merge the profile/data. In some cases, data could be saved outside of Firebase services.
FirebaseUI is currently doing a similar mechanism for upgrading anonymous users on sign in. If the credential is new, then linking will succeed without any additional action. If the credential already exists, linking will fail and the developer is expected to handle the merge conflict, copy the data from the non anonymous user and delete the anonymous user after.
This is the web flow in FirebaseUI-web: https://github.com/firebase/firebaseui-web#upgrading-anonymous-users
This is being implemented for FirebaseUI-android:
https://github.com/firebase/FirebaseUI-Android/pull/1185
Here is an example with web, given an authCredential and an anonymous user signed in.
Here is a simple web example how to handle merge conflicts.
let data;
// Default App with anonymous user.
const app = firebase.app();
// Anonymous user.
anonymousUser = app.auth().currentUser;
// Get anonymous user data.
app.database().ref('users/' + app.auth().currentUser.uid)
.once('value')
.then(snapshot => {
// Store anonymous user data.
data = snapshot.val();
// Sign in credential user.
return app.auth().signInWithCredential(authCredential);
})
.then(user => {
// Save the anonymous user's data to the credential user.
return app.database().ref('users/' + user.uid).set(data);
})
.then(() => {
// Delete anonymnous user.
return anonymousUser.delete();
})
})

Related

The getter 'uid' was called on null in flutter

I'm implementing firebase authentication in flutter application but while trying to get user uid , it is crashing and show noSuchMethodError uid is null , if anyone could help , it is deeply appreciated
That's how i init my variables
class _UserRegistrationState extends State<UserRegistration> {
FirebaseAuth auth;
DocumentReference reference;
Reference storage;
PickedFile imageUri;
final ImagePicker _imagePicker = new ImagePicker();
#override
void initState() {
super.initState();
auth = FirebaseAuth.instance;
// the uid is where the logcat is pointing too and it is null
reference = FirebaseFirestore.instance.collection('users').doc(auth.currentUser.uid);
storage = firebase_storage.FirebaseStorage.instance.ref('avatar').child(auth.currentUser.uid);
}
When you sign in to Firebase Authentication, the SDK automatically persists the user's credentials in local storage. When you restart the app, the SDK tries to restore the user's authentication state from the stored credentials. This requires that it calls the servers to get a new ID token, and for example to check if the account was deleted/disabled in the meantime.
Depending on the platform where you run your code, the calls to the server may have completed before your auth.currentUser runs, or not. To safely respond to the user state, always use an auth state listener as shown in the FlutterFire documentation on responding to auth state changes:
#override
void initState() {
super.initState();
auth = FirebaseAuth.instance;
FirebaseAuth.instance.authStateChanges().listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
reference = FirebaseFirestore.instance.collection('users').doc(auth.currentUser.uid);
storage = firebase_storage.FirebaseStorage.instance.ref('avatar').child(auth.currentUser.uid);
}
});
}
currentUser → User?
Returns the current User if they are currently signed-in, or null if not.
So most likely thing is that you are not logged in and therefore passing null to reference

Verify a user's email address before confirming registration, with Flutter and Firebase

I've created a login and registration screen that works with my Flutter app, using Firebase as the backend authentication service. I'm able to switch between the login, registration and reset password screens well.
The Issue
At the moment, the registration screen accepts any email address that is entered, whether or not it is real. For example, if I were to type in gvevg#gverwbgw.com, it would allow the user to register. This is obviously an issue, when it comes to fake accounts and spam etc.
The Aim
I would basically like to be able to edit my code, to automatically generate an email address verification email, which prevents the user from signing in, before their email address has been verified. The code I have made uses a Future, FirebaseAuth and async/await to make this happen.
My Current Code
Firstly, I define an AuthBase abstract class, that creates the 'createUserWithEmailAndPassword' function (amongst others) as follows:
abstract class AuthBase {
Stream<User> get onAuthStateChanged;
Future<User> currentUser();
Future<User> createUserWithEmailAndPassword(String email, String password);
}
Then, I create an Auth function, that implements AuthBase, gets the current user from Firebase and creates the registration Future function, as follows:
class Auth implements AuthBase {
final _firebaseAuth = FirebaseAuth.instance;
// This creates the user ID token variable (if one doesn't already exist) which is then populated using one of the login methods.
User _userFromFirebase(FirebaseUser user) {
if (user == null) {
return null;
}
return User(uid: user.uid);
}
// This helps to get the user from Google Firebase, noting if there is or isn't a user with those login details already.
#override
Stream<User> get onAuthStateChanged {
return _firebaseAuth.onAuthStateChanged.map(_userFromFirebase);
}
// This identifies the current user, who is logged in at the time.
#override
Future<User> currentUser() async {
final user = await _firebaseAuth.currentUser();
return _userFromFirebase(user);
}
// This creates the user account for an email-and-password sign-in, with firebase, if it doesn't already exist.
#override
Future<User> createUserWithEmailAndPassword(
String email, String password) async {
final authResult = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(authResult.user);
}
}
My Question
How do I edit my code, so that it allows me to implement email verification automatically for any user that wants to sign in with email? I believe the sendEmailVerification() function must use FirebaseUser, although I am not sure how to implement it here. I would appreciate any help. Thanks!
Email+password authentication requires nothing more than that the user knows the combination of email+password. It doesn't in itself require the email address to be verified to sign in. If you want the email address to be verified before allowing access to other data, you can do that by checking the user's token for the email_verified claim for example in the security rules of your database.
Also see:
How do I lock down Firebase Database to any user from a specific (email) domain?
Firebase email verification at SignUp
How to prevent user authentication in Firebase/Vue.js BEFORE email is verified
Only let pre-verified users log into Firebase

Firestore Security: Deny Update / Write If Field In Request Resource (Works in simulator, not IRL)

I have user profile data stored in Firestore. I also have some profile fields in Firestore that dictate user permission levels. I want to deny the user the ability to write or update to their Firestore profile if they include any changes that would impact their permission level.
Example fields in user's firestore doc for their profile
permissionLevel: 1
favoriteColor: red
Document ID is the same as the user's authentication uid (because only the user should be able to read / write / update their profile).
I want to deny updates or writes if the user's firestore update or write includes a permissionLevel field, to prevent the user from changing their own permission level.
Current Firestore Rules
This is working fine when I build an object in the simulator to test including or not including a field called "permissionLevel". But this is denying all update / write requests from my client-side web SDK.
service cloud.firestore {
match /databases/{database}/documents {
// Deny all access by default
match /{document=**} {
allow read, write: if false;
}
// Allow users to read, write, and update their own profiles only
match /users/{userId} {
// Allow users to read their own profile
allow read: if request.auth.uid == userId;
// Allow users to write / update their own profile as long as no "permissionLevel" field is trying to be added or updated
allow write, update: if request.auth.uid == userId &&
request.resource.data.keys().hasAny(["permissionLevel"]) == false;
}
}
}
Client-Side Function
For example, this function attempts to just update when the user was last active by updating a firestore field. This returns the error Error updating user refresh time: Error: Missing or insufficient permissions.
/**
* Update User Last Active
* Updates the user's firestore profile with their "last active" time
* #param {object} user is the user object from the login auth state
* #returns {*} dispatched action
*/
export const updateLastActive = (user) => {
return (dispatch) => {
firestore().settings({/* your settings... */ timestampsInSnapshots: true});
// Initialize Cloud Firestore through Firebase
var db = firestore();
// Get the user's ID from the user retrieved user object
var uid = firebaseAuth().currentUser["uid"];
// Get last activity time (last time token issued to user)
user.getIdTokenResult()
.then(res => {
let lastActive = res["issuedAtTime"];
// Get reference to this user's profile in firestore
var userRef = db.collection("users").doc(uid);
// Make the firestore update of the user's profile
console.log("Firestore write (updating last active)");
return userRef.update({
"lastActive": lastActive
})
})
.then(() => {
// console.log("User lastActive time successfully updated.");
})
.catch(err => {
console.log("Error updating user refresh time: ", err);
})
}
}
This same function works fine if I remove this line from the firestore rules. I don't see how they have anything to do with each other, and why it would work fine in the simulator.
request.resource.data.keys().hasAny(["permissionLevel"]) == false;
Update
I got a notice that writeFields is deprecated. I have another another answer to a similar question here which uses request.resource.data which may be an alternative that is useful to people who arrive here.
Original Answer
OK, I found a solution, but I can't find any official documentation in the firebase docs to support this. It doesn't work in the simulation, but it works IRL.
Replace (from my example above)
request.resource.data.keys().hasAny(["permissionLevel"]) == false
With This
!("permissionLevel" in request.writeFields);
Full Working Permissions Example
service cloud.firestore {
match /databases/{database}/documents {
// Deny all access by default
match /{document=**} {
allow read, write: if false;
}
// Allow users to read, write, and update their own profiles only
match /users/{userId} {
// Allow users to read their own profile
allow read: if request.auth.uid == userId;
// Allow users to write / update their own profile as long as no "admin" field is trying to be added or created
allow write, update: if request.auth.uid == userId &&
!("permissionLevel" in request.writeFields);
}
}
}
This successfully prevents an update or write whenever the key permissionLevel exists in the firestore request map object, and allows other updates as intended.
Documentation Help
Firestore Security Docs Index lists "rules.firestore.Request#writeFields" - but when you click it, the resulting page doesn't even mention "writeFields" at all.
I used the principles based on rules.Map for
k in x Check if key k exists in map x
Two other things you could consider doing for adding permission levels:
Create a separate subcollection for the user that will then contain a document with information you do not want the user to be able to change. That document can be given different permission controls.
Use Firebase Auth Tokens with Custom Claims. Bonus: this method will not trigger reads on the database. I recommend checking out these Firecasts:
Controlling Data Access Using Firebase Auth Custom Claims
Minting Custom Tokens with the Admin SDK for Java
Add the Firebase Admin SDK to Your Server guide is also very helpful.
I am new to the development game, but this what I use to manually create custom claims using ItelliJ IDEA:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.UserRecord;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class App {
//This will be the UID of the user we modify
private static final String UID = "[uid of the user you want to modify]";
//Different Roles
private static final int USER_ROLE_VALUE_BASIC = 0; //Lowest Level - new user
private static final int USER_ROLE_VALUE_COMMENTER = 1;
private static final int USER_ROLE_VALUE_EDITOR = 2;
private static final int USER_ROLE_VALUE_MODERATOR = 3;
private static final int USER_ROLE_VALUE_SUPERIOR = 4;
private static final int USER_ROLE_VALUE_ADMIN = 9;
private static final String FIELD_ROLE = "role";
//Used to Toggle Different Tasks - Currently only one task
private static final boolean SET_PRIVILEGES = true; //true to set User Role
//The privilege level being assigned to the uid.
private static final int SET_PRIVILEGES_USER_ROLE = USER_ROLE_VALUE_BASIC;
public static void main(String[] args) throws IOException {
// See https://firebase.google.com/docs/admin/setup for setting this up
FileInputStream serviceAccount = new FileInputStream("./ServiceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://[YOUR_DATABASE_NAME].firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
// Set privilege on the user corresponding to uid.
if (SET_PRIVILEGES){
Map<String, Object> claims = new HashMap<>();
claims.put(FIELD_ROLE, SET_PRIVILEGES_USER_ROLE);
try{
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
FirebaseAuth.getInstance().setCustomUserClaims(UID, claims);
// Lookup the user associated with the specified uid.
UserRecord user = FirebaseAuth.getInstance().getUser(
System.out.println(user.getCustomClaims().get(FIELD_ROLE));
}catch (FirebaseAuthException e){
System.out.println("FirebaseAuthException caught: " + e);
}
}
}
}
The build.gradle dependency is currently:
implementation 'com.google.firebase:firebase-admin:6.7.0'

Firebase add/link password to existing federated provider

I'm allowing user to Sign Up with Google, Facebook or Email. Follow this link I know how to link multiple auth provider to the same account but here is my scenario
Let say an user create account with Google or Facebook but later(after his account created) he want to set password so he can login with email and password as well. I know how to link an email/password account with other federated provider(google, facebook) but not the other way. My only though is to create an new account with that new password and email associated with the method they choose in early stage but it will not work due to email already exist. I even enable allow multiple account with same address at my console but it return ERROR_EMAIL_ALREADY_IN_USE so I think it doesn't work with email/password.
So how can I add password to that account after sign up with Facebook or Google? Thank in any advace.
From the documentation on linking account providers:
Email-password sign-in
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
And then you link the credential with the existing Google/Facebook accont with:
Pass the AuthCredential object to the signed-in user's linkWithCredential method:
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w(TAG, "linkWithCredential:failure", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
Update
use signInAndRetrieveDataWithCredential instead of linkWithCredential, because linkWithCredential is deprecated.

Firebase how to get user details?

I am using Firebase authentication in my app and signing up a user with email and password. I want to get other users details (separate from the logged-in user) as well while a user is signed in with their own account. How can I get that information?
Values like email, display name and id (specific to authentication system) are available off of the Firebase User object. You can get a reference to the current logged in user off of the FIRAuth class. I provided links and class names for iOS, but other platforms are similarly structured.
If you want to store additional data for users, I would recommend including a users root node, using the uid off of the Firebase User object as the key for users child nodes.
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// 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()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
String user_id = auth.getCurrentUser().getUid();
DatabaseReference current_user_db = _Database.child(user_id);
current_user_db.child("name").setValue(name);
current_user_db.child("image").setValue("default");
startActivity(new Intent(SignupActivity.this, ProfileActivity.class));
finish();
}
}
});
}
});
It's not a security issue, but just a mean of how you treat personal information. You can store what you want in firebase so you can easily store when the user login his/her avatar url (aka facebook url) or just id or any other infos anyway, then retrieve it.
If you need to retrieve infos of users which are not using your apps beside, thden you can also easily via the facebook sdk with user permission of course. take care–

Resources