Flutter Firebase adding other user information such as Address to the database - firebase

I am currently working on Flutter Firebase to save the details of the users that are signing up for the app.
What I've done is that the user are able to sign up with their email and password. But what I would like to know is how do I add other user information such as Address to be saved so that the users will be able to see it when I am retrieving it from Firebase to the app.
What I've done :
AuthResult user = await
FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email,password:_password);
This saves the user email and password into the database.
I've tried the solution on : Flutter user registration with Firebase: Add extra user information (age, username)
What I've tried to do :
Firestore.instance.collection('users').document().setData({ 'userid':
user.uid, 'username': _address });
And I seem to get errors on that Firestore is an undefined name along with the uid isn't defined for the class 'AuthResult' . Am I missing some import files?
I've only imported :
import 'package:firebase_auth/firebase_auth.dart';
Also, I know I have to create a table called user to allow the data to be saved in but which one do I use? The Cloud Firestore or the Realtime Database?
Thanks for all the help.

You have a lot of questions hidden in a single question. I'll try to address as many as I can below, but please try to stick to a single question in the future.
Recommending one database over the other is off-topic on Stack Overflow. But I'd recommend reading the Firebase documentation on it here.
Since you started with Cloud Firestore, let's focus on that.
You'll need to import the plugin for Firestore, just like you've done with the plugin with Authentication. So something like:
import 'package:cloud_firestore/cloud_firestore.dart';
As you've discovered, there is no AuthResult.uid property. In such cases, I recommend browsing the reference documentation for the plugin, which makes it fairly easy to see that AuthResult.user is probably the path to go.
So something like:
AuthResult result = await
FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email,password:_password);
User user = result.user;
Not the solution to the question you're asking, but please use document(user.uid) instead of just document(). What you now have generates a document ID, while it's idiomatic (and much easier) to use the UID as the key in a users collection.

Related

How to add Firebase authentication for email/pass, phone, and google to an existing UI in flutter

So basically, I have already made the UI for the sign in, sign up, etc screens and now I want to implement firebase into it, does anyone know how to do this? Anything could be useful
Here's a quick recap on how to do this, although i really recommend reading firebase's official tutorial on this,
first you need to add the firebase plugin:
go to the firbase_auth pub page, and follow the "installing" instructions there
open a firebase account, add a project using the firebase console, and follow the tutorial to connect you firebase project you created on the website to your app
now lets say you have some textfields and a button to register/log in, you want to add a "controller" to the text field:
final controller = TextEditingController();
and then in the onPressed of the button, you want to provider a function that calls:
String resultText = controller.text
now you can use the resultText string and send it to firebase (do the same with 2 controllers, one for email and one for password)
first initialize the firebase instance:
import 'package:firebase_auth/firebase_auth.dart';
FirebaseAuth auth = FirebaseAuth.instance;
then anywhere in your app your can call (for example with the string variables you got from the controllers of the text fields):
UserCredential result = await auth.createUserWithEmailAndPassword(
email: email, password: password);
User user = result.user;
and then you can check if the user is received successfully, and condition moving on to the next screen accordingly
this is just an example for registering, you will need different code to check if the user exists on login, but its all through the auth api, which you can read on in the first link I supplied
this is just to give you an example of the steps required to get this done, and i'm over simplifying stuff, but should get you started :)

FIREBASE WARNING: Firebase Error. Please ensure that you spelled the name of your Firebase correctly

as you can see by the question, I am having trouble using Firebase in my app. I initialized the Firebase object and used the configuration from my Firebase account. Additionally, I have been able to authenticate users (I have a semi-functional login system going). So far, users can login to existing accounts and create new accounts. However, I am trying to store data with my user (during registration) by taking the uid from the user and using that in my Cloud Firestore. After they register, I am trying to store the other fields (firstName, lastName, school, etc.) into the Cloud Firestore under the uid.
this.props.firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((auth) => {
this.props.firebase
.database()
.ref("users/" + auth.user.uid)
.set({data})...
It successfully creates the user but doesn't let me store the information in the Cloud Firestore and throws the error I displayed above. Can anyone help? Thank you!
Note: this.props.firebase is the reference to the firebase object instantiated with firebase.initializeApp()
Hahahaha, I suppose that I needed to actually create a real-time database in order for it to work. I had set up the Cloud Firestore while using the Realtime Database methods. Sorry to all for your troubles.

Retrieve FirebaseUser data by UID using only FirebaseAuth

I am using theFirebaseAuth Flutter plugin in order to manage the authentication process of users in my app. So far, I have been able to retrieve data from the current user with no trouble. However, I would like to retrieve user information data such as the profile picture using the UID of that user. This is quite easy when the user I want to get the data from is the current user, but I can't see the way of doing that when the user is different.
Is it possible, in some way, to build an instance of FirebaseUser specifying the UID? Or am I forced to store that information in some external storage platform? I prefer
For security reasons, getting user info from any user besides the current one has to be done in a managed environment like a server or Cloud Functions. You can use the Admin SDK to handle this.

Reference firestore database with firebase auth uID

Is there a way to reference Auth uID with my created users DB through firebase console? Or i need to do it through application by writing code?
Since my app doesn't have registration but only log in as a function, then i have already populated auth table, but i need to somehow reference each uID with user in DB.
One way that i thought about was that i would create new users DB field when someone logs in for the first time. That could be a workaround, but still.
Maybe someone has an idea or solution of what i should do to achieve a result for my problem?

Adding users to Firebase Database

I'm learning Firebase and creating my first project with it. I'm using FirebaseUI to simplify the authentication. I'm now working on the database and I need to start by adding my authenticated users to it. I've read all the documentation and I'm able to do this, but I'm wondering if I'm doing it the best way.
Since I'm using FirebaseUI and I'm not actually calling the signIn() or createUser() methods of Firebase Authentication myself, I thought the best way for me to add users would be to do it onAuthStateChanged()
usersRef = rootRef.child('users')
firebase.auth().onAuthStateChanged(user => {
if (user) {
let userRef = usersRef.child(user.uid)
userRef.set({
name: user.displayName,
email: user.email,
photoURL: user.photoURL,
emailVerified: user.emailVerified,
})
}
}
This works fine but I'm concerned about two things:
1) This sets the user data every time the user is authenticated, even if the user already exists and nothing has changed. A simple page reload will rewrite the user to the database.
2) In order for this to work, the userRef location needs to be writable by the user. This would mean that the emailVerified in the userRef location isn't reliable because the user could potentially modify it himself. I could just rely on the emailVerified returned from onAuthStateChanged which the user could never modify, but I'm wondering if I'm just doing this wrong or if there's a better way.
A possible solution is described in a video found at https://www.youtube.com/watch?v=QEd2lEoXpp40. He creates two sections in the database: users and loginQueue. A user in users is only readable by the authorized user and loginQueue is only writable by an authorized user. When a user is authenticated, his data gets written to the loginQueue. He then uses the on() method to check for a child added to the loginQueue that matches their user.uid and somehow uses the update method to write to the user data to users. This works but I don't understand how. How can is the client able to send an update() to users\uid if it's only readable? You can see his code at 7:00 in the video. This has me stumped. This works but why.
I just implemented the technique as shown in the video and although it worked for him, I encountered a PERMISSION_DENIED error when trying to update the only readable user data. This is what I thought SHOULD happen but in his video he clearly shows this was not happening. Unless I'm missing something which I don't think I am, his method doesn't work anymore. Maybe it was a bug that was later fixed?
UPDATE: Thanks to Doug Stevenson for pointing me to Firebase Cloud Functions. I was able to completely solve my problem by creating a cloud function that responds when new users are authenticated. Here is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.addUserToDB = functions.auth.user().onCreate(event => {
admin.database().ref('/users/' + event.data.uid).set({
name: event.data.displayName,
email: event.data.email
});
});
This is a common strategy.
Authentication shouldn't happen too often. Also, if nothing changed in user record since the last write, nothing should actually happen. You don't pay for the bandwidth for client writes to the database.
Split your user data up into two sections, one that's writable by the current UID, and the other that's not. That will prevent problems with users modifying data that you'd not like them to.
Alternately to this, set aside another location in your database where your clients can push commands to update data elsewhere, and use a Cloud Functions for Firebase trigger to read these commands, act on them with elevated privilege, checking for correctness, and delete them.

Resources