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

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 :)

Related

Flutter skip firebase signin when creating new user with email and password

I m recently coding an app, where i use firebase as backend.
I created a method to sign up with firebase but I dont want it to sign in with the new user recently created. Is it possible to keep firebase auth signed in with the current user who adds the new user?
Is it possible to keep firebase auth signed in with the current user
who adds the new user?
With the clients SDKs/plugins (FlutterFire, JavaScript SDK, etc.) this is not possible.
One way is to use the Admin SDK to create your users. For example you can create a Callable Cloud Function which creates the users and which is called by the end-user from the front-end.
I've written an article that details the entire approach with the corresponding code.

How to import many users to firebase auth using flutter

I want to import 30 users using flutter to firebase, I couldn't find any sources to do so, the only thing I found out was this : https://firebase.google.com/docs/auth/admin/import-users ,
But I don't no how to implement this in my app
I wanted to store user data in a google docs and convert it into a ".csv" format and upload this from the flutter app to firebase ' Gmail password' authentication
The document you found uses the Firebase CLI. Unfortunately, you can't do this in dart/flutter. But if you want to implement it in flutter you can loop through a list of user objects.
Example:
List list = [{"email":"user1#example.com","Password":"strong password"},{"email":"use2r#example.com","Password":"strong password"},{"email":"user3#example.com","Password":"strong password"}];
final _auth = FirebaseAuth.instance;
list.forEach((element) async{
await _auth.createUserWithEmailAndPassword(email: element.email, password: element.password);
});
You can send a list of users to the firebase function or your backend service and perform an import like in the document you found.

Fake users in firebase with #gmail.com accounts

I have a firebase project.
The next sign-in methods auth are enabled:
Google
Facebook
Apple
Anonymous
A mobile app interacts with the firebase.
Each day I get some weird new users sign-ups with fake accounts with the pattern: [name][numbers]#gmail.com. They don't do anything except sign up via google oauth once.
Is it possible to prevent it? Maybe I missed something with the google oauth configuration?
Updated:
Also, I noticed that these sign-ups started to occur when I had sent out the mobile app to google/apple verification. May these two events are correlated?
New accounts created coz of Play market Pre Launch Report
You can change Pre Launch Report settings to change it's behaviour (e.g. specify test account to use in auth)
If you are sure those fake users have a specific pattern from their email address, I would make a trigger function on Cloud Functions for Firebase.
You can use functions.auth.user().onCreate() event handler like below.
exports.checkFakeUser = functions.auth.user().onCreate((user) => {
// You can check if the user has suspicious email patterns and delete them here.
});
Or you can also make a Schedule function on Cloud Functions for Firebase and daily check if there are fake users and automatically delete them.
Plus, it would be a good step if you figure out that fake users still joining even you didn't expose your mobile app anywhere if you want to find out the reason how they are joining.
Add the following Cloud Function will help you on check the email and delete the fake user
exports.checkFakeUser = functions.auth.user().onCreate((user) => {
const list = user.email.split(".")[1].split("#")
const isFake = list[0].length === 5 && list[1] === 'gmail'
if(isFake){
admin.auth().deleteUser(user.uid)
.catch(function(error) {
console.log('Error deleting user:', error);
});
}
});
You can't stop specific accounts from being created, as the underlying Google Auth APIs are accessible to anyone with an account. You could manually delete them, or write a program to delete them (bearing in mind that you could also be deleting actual user accounts).
Or if you suspect abusive behavior, you can contact Firebase support to report that.
Check, these e-mail addresses will be re-logged when they upload a new version to google play. The most likely reason for this is that google keeps your application to a number of tests with its automation infrastructure.

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

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.

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