Custom user model to firebase authentication - firebase

I have an AuthService class that has the following code
UserData _userDetFromFirebaseUser(User user) {
if (user != null) {
return UserData(uid: user.uid);
} else {
return null;
}
}
Stream<UserData> get userData {
return _firebaseAuth.authStateChanges().map(_userDetFromFirebaseUser);
}
And I used StreamProvider from the flutter provider package
Widget build(BuildContext context) {
return StreamProvider<UserData>.value(
value: AuthService().userData,
child: MaterialApp(
home: HomeController(),
),
);
}
It is all working well but the problem is that I want to add custom variables to the UserData model and get it through the provider and I don't know how to to do it. can You please help me?
the usermodel goes like this
class UserData {
final String uid;
String name;
String phoneNumber;
UserData({this.uid});
}
also: I tried calling Provider.of method and adding the fields in the app but then the app restarts the state is lost I want to save that state( the field variables in the model)I am new to Provider and state management so Please elaborate the answer.

That is one of my next tasks. From my understanding so far, you create a root level folder in FireStore called /users and add for each user a document with the UID of the user as the document id.
Unfortunately I am still fighting other Firestore challenges before I can tell, whether this is already sufficient to get all the fields of that user document together with the returned User element upon login.

Related

Cannot get the currentUser's displayName with FirebaseAuth

I have made a sign-in page, and a sign-up page with Firebase Authentication in Flutter and Dart.
After the sign up, I'm trying to retrieve the current user's displayName, however, when I try retrieving it, I seem to get not the current one, but the one that I signed up with before this one.
However, when I for example hot-restart the app, I get the current user's details just fine.
I try to retrieve the current user's displayName property with this code:
static String? getUsername() {
return FirebaseAuth.instance.currentUser?.displayName!;
}
The way I call this, is I initialize a variable to store the username which I get from the method, on a different dart file, different from the signUp page I got. I also call this method in the initState() method.
This is how I sign-up the user and set the displayName:
static void signUpUser(String username, String emailAddress, String password) async {
try {
final credential =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailAddress,
password: password,
);
// Here I set the displayName property
await credential.user!.updateDisplayName(username);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {}
else if (e.code == 'email-already-in-use') {}
} catch (e) {}
}
I tried to use the user.reload(), and FirebaseAuth.userChanges() functions, but these did not seem to fix my problem.
Maybe I'm trying to retrieve the displayName property wrong, what am I missing? I'm quite new to developing my own apps and working with Firebase.
The Future that updateDisplayName returns completes when the call has been made to the underlying Firebase SDK. It does not automatically update the user profile in your application at that point though. That will only happen automatically once every hour (when the SDK refreshes the ID token on which that profile is based), or when the user signs out and in again.
To force a refresh of the profile from your application code outside of those automatic conditions, you can call reload() on the user object.

Flutter firebase user problem trying to link to a model

the error I'm getting:
A value of type 'UserA?' can't be returned from the method
'_userFromFirebaseUser' because it has a return type of 'User'
I'm following along this tutorial: Flutter & Firebase App Tutorial #6 - Custom User Model
At about 5:35 into the video he talks about returning the Firebase user object and linking it to the model. Now the video is about 2 years old, so Firebase has moved on a bit. FirebaseUser is now just called User, but I think in my changes I've made a mistake. Here is my code:
class AuthService{
final FirebaseAuth _auth = FirebaseAuth.instance;
//create user object based on firebaseuser
User _userFromFirebaseUser(User? user) {
return user != null ? UserA(uid: user.uid) : null;
}
This is my model:
class UserA {
final String uid;
UserA({ required this.uid });
}
Since FirebaseUser is now just called User I've changed the model to be UserA since I was getting confused.
Any suggestion on what I'm doing wrong?
You're mixing up the two types of users in your code.
The video has two types: FirebaseUser and User, which you have mapped to Users and UserA respectively.
With your types, the function should be:
UserA? _userFromFirebaseUser(User? user) {
return user != null ? UserA(uid: user.uid) : null;
}
Aside from the type change, the ? is needed in Dart nowadays to indicate that you may return either a UserA object or null.

Update user data in provider if user document has changed on firestore

I would like to update user data in provider if user document has changed on firestore.
Actually, I use provider to store current user data in a variable called _currentUser. This variable is helpful to display user data on several screens.
class UserService extends ChangeNotifier {
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
late User _currentUser;
User get currentUser => _currentUser;
Future<User> getUser(String uid) async {
var userData = await usersCollection.doc(uid).get();
User user = User.fromMap(userData.data()!);
_currentUser = user;
print("nb lives : ${_currentUser.nbLives}");
notifyListeners();
return user;
}
}
Current User data can change over time and the problem of my current solution is that if user document has changed, _currentUser variable is not updated and the old data is displayed on app screens. I want to find a way to listen to this document and update _currentUser variable if user data has changed.
A solution i found is to use Streams to fetch user data but I don't like it because it runs on a specific screen and not in background.
Does anyone have ever face a similar issue ? Thank you for your help !
class UserService extends ChangeNotifier {
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
late User _currentUser;
User get currentUser => _currentUser;
void init(String uid) async {
// call init after login or on splash page (only once) and the value
// of _currentUser should always be updated.
// whenever you need _currentUser, just call the getter currentUser.
usersCollection.doc(uid).snapshots().listen((event) {
_currentUser = User.fromMap(event.data()!);
notifyListeners();
});
}
}
You can do this in many ways
When you update the _currentUser in firestore, update the same in the provider variable with notifylistner and wrap your widget that uses the _currentUser in Consumer, so the changes get updated always.
In you root widget use StreamBuilder with stream: ....snapshots() and on change update the _currentUser
This depends on your use-case and want things to react on changes to _currentUser.

Firebaseui FirestoreRecyclerAdapter: How to use data pointed to by DocumentReference

My data is set up as follows:
- The Users collection contains User documents.
- A User document contains a Friends subcollection.
- A Friends subcollection contains UserRef documents.
- A UserRef document contains a DocumentReference to a User document.
I want to display all the friends of a particular user in a RecyclerView using the FirestoreRecyclerAdapter. From this answer, it seems like I cannot retrieve the User documents pointed to by a DocumentReference in a query. So, the following code is my attempt at using a SnapshotParser to do so. However, I don't know how to can return the User from parseSnapshot() since it is retrieved asynchronously.
Query query = friendsSubcollection;
FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User.class, new SnapshotParser<User>() {
#NonNull
#Override
public User parseSnapshot(#NonNull DocumentSnapshot snapshot) {
DocumentReference userRef = snapshot.toObject(DocumentReference.class);
userRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
User user = documentSnapshot.toObject(User.class); // How do I return this user from parseSnapshot()?
}
});
}
})
.build();
You won't be able to do this because parseSnapshot needs to happen synchronously, but getting another document is asynchronous. The document get won't complete with a callback until after parseSnapshot returns. So, you won't be able to use Firebase UI for this - you'll have to come up with your own way of making multiple requests to populate the RecyclerView, and it will likely require a lot of work.

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

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();
})
})

Resources