Firebase Auth Reset Password (Flutter) - Get the new password - flutter

In my Flutter app, there's an admin who creates employee accounts including their passwords. They can however change their passwords later.
The admin can also remove employees
await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: employee.email,
password: employee.password);
await FirebaseAuth.instance.currentUser!.delete();
I call the signInWithEmailAndPassword with the employee email & password & then delete the user from the admin panel
However, if the employee resets the password, the admin can no longer remove this employee as I lose track of the new password
How can I get the new password when someone calls
await FirebaseAuth.instance
.sendPasswordResetEmail(email: email,)
.then((value) {});

That's pretty odd! Why would an admin need to know the passwords of every employee?
I'd suggest you set up a backend cloud function to do the removal process. On Firebase Admin SDK you can simply call the deleteUser method on the Auth object.
getAuth()
.deleteUser(uid)
.then(() => {
console.log('Successfully deleted user');
})
.catch((error) => {
console.log('Error deleting user:', error);
});
Here's the detailed document: https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user

Related

Linking Firebase Authenticated user with 'users' collection in Flutter

New to flutter, and first post here!
I am building a mobile app with flutter, using Firebase and Cloud Firestore. Each user, when authenticated (by email and password), is also currently then added to a 'users' collection in Firestore - like this:
sign up method:
Future signUp() async {
if (passwordConfirmed()) {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text.trim(),
password: _passwordController.text.trim(),
);
// add user details
addUserDetails(
_firstNameController.text.trim(),
_lastNameController.text.trim(),
_emailController.text.trim(),
_baseStationController.text.trim(),
);
}
}
Future addUserDetails(String firstName, String lastName, String email,
String baseStation) async {
await FirebaseFirestore.instance.collection('users').add({
'first name': firstName,
'last name': lastName,
'email': email,
'base station': baseStation,
});
}
The signup() method is called when they input their information into text fields within a form, and click a button. This works successfully, and my user collection receives the data, and sign in/out works as it should.
Those users have a 'base station' (which is stored as a field within that users document in Firestore) which is their place of work. I want to show a welcome screen when they log in, so that the current users 'base station' is displayed.
I can access their email address using:
final thisUser = FirebaseAuth.instance.currentUser!;
and then for example to show this when they log in:
Text('Hello, ${thisUser.email!}')
this works no problem, however...
I can't work out how their authentication then links to the collection, so I want to show the 'base station' for the 'currentUser' for example when they log in (I don't want them to have to select their base station every time from a picker when they've already provided the information on sign up.
As an aside - I can also (separately) successfully read the data from the collection and (for example) create a listView builder with the users collection information, but this is for all users, and not specifically the 'currentUser' that is logged in.
All help gratefully received, apologies if I have missed anything.
update addUserDetails as follows
Future addUserDetails(String firstName, String lastName, String email,
String baseStation) async {
await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).set({
'first name': firstName,
'last name': lastName,
'email': email,
'base station': baseStation,
});
if you then want to get specific user detail then use the code as follows
final user = await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).get();

Add aditional user information when signup supabase

I am trying to add additional data in a user record in supabase, I have created a trigger that is called after a record has been inserted in auth user that should add the user id and username in the profiles table. This happens but it doesn't add the user name, it's still null in the profiles table. That data is supposed to go in the raw_user_meta_data column but it still doesn't add in the column
Trigger function:
BEGIN
INSERT INTO public.profiles(id, username)
VALUES (
NEW.id,
NEW.raw_user_meta_data -> 'username'
);
RETURN NEW;
END;
Front:
const createNewUser = async() => {
const { username, email, password } = credentials;
await supabase.auth.signUp({
email: email,
password: password,
data: {
"username": 'hello'
}
});
}
Just to follow up. Maybe this is the change with supabase v2 and supabasejs update, but now it seems to work with one argument, but slightly different than you had it in first post. Here is the link:
https://supabase.com/docs/reference/javascript/auth-signup#sign-up-with-additional-user-metadata
and the code:
const { data, error } = await supabase.auth.signUp({
email: userEmail.value,
password: password,
options: {
data: {
user_name: userName.value,
},
},
});
I found the solution reading over there, in case it helps anyone. My mistake was that in the signUp function I passed only 1 argument that had included the additional data that would be included in the trigger function. However, this signUp function must be passed 2 objects as arguments and it is this second argument that is passed that saves the object with the username extracted from the function in the front in the raw_user_meta_data column.
As additional data that can help you in the search for the error. You can know what the logs of the authentication process print. You can also insert a record directly in auth.users so you can see why it does not add additional data and be able to review the logs, I attach an example:
insert into auth.users(id, email, encrypted_password, raw_user_meta_data)
values (
'eb23060d-71ea-4112-a1c7-203d6f87fa2d',
'example#mail.com',
'$2y$10$WpAA2remsZRnZivgRaM9L.1BcjvAtUa966AICxv1RGte68BICsZkS',
'{"username": "user_example"}'
)
Final solution:
const { user, session, error } = await supabase.auth.signUp(
{
email: 'example#email.com',
password: 'example-password',
},
{
data: {
username: 'John'(variable)
}
}
)

User is authenticated but their data is not saved in Cloud Firestore

I am fairly new to flutter and firebase and I've been following Reed Barger's guide to "Build a Social Network with Flutter and Firebase" https://www.udemy.com/course/build-a-social-network-with-flutter-and-firebase. I have successfully done authentication with Google but I face a problem with creating a user in Firestore. The method for that is
createUserInFirestore() async {
//1) check if user exists in user's collection in database (according to their id)
final GoogleSignInAccount user = googleSignIn.currentUser;
final DocumentSnapshot docu = await usersRef.doc(user.id).get();
//2) If user doesn't exist, take them to create account page
if (!docu.exists) {
final username = await Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateAccount()));
//3) get user name from create account and use it to create new user's document in user's collection
usersRef.doc(user.id).set({
"id": user.id,
"username": username,
"photoUrl": user.photoUrl,
"email": user.email,
"displayName": user.displayName,
"bio": "",
"timestamp": timestamp
});
}
}
The problem is that it doesn't take a new user to the CreateAccount page and the Firestore database is also not updated. Instead, the home page is loaded and I get the error
E/flutter (17311): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'doc' was called on null.
E/flutter (17311): Receiver: null
E/flutter (17311): Tried calling: doc("1148131790923706651234")
Also, the user is not added in the Firebase Console under Users in Authentication. For now, I'm only working on Android.
Where have I gone wrong?
What is a usersRef? You haven't defined it, so it is null. You are calling method 'doc' on null variable usersRef. Try something like this to initialize usersRef:
CollectionReference usersRef = FirebaseFirestore.instance.collection('Users');

How to validate Unique username to all users in Flutter social media app?

I am creating a Memer social media app. So in this everything is ready but I am confused in providing Unique display name for all users. User name are given by users. But how to validate that it is really present or not? All data are stored in firebase cloud firestore. So can anybody can help me?
Username is stored is like this: collection "users" -> document "userId" ->field "username"
For this I made a new collection with the name username. And before creating the account i was calling this function to check availability:-
checkUsernameIsUnique(String username)async
{
QuerySnapshot querySnapshot;
setState(() {
loading=true;
});
querySnapshot=await FirebaseFirestore.instance.collection('username').where("username",isEqualTo: username).getDocuments();
print(querySnapshot.documents.isNotEmpty);
return querySnapshot.documents.isEmpty;
}
checkUsernameIsUnique('username to be checked').then((val){
if(val)
{
//create the user and store the username in username collection also
FirebaseFirestore.instance.collection('username').document(widget.username).setData({
"username":widget.username,
});
}
else
//username is taken
});
u can create cloud function which will get username and returns bool if its unique or not.

How to add users manually to Meteor.users collection?

I am having super user which I added manually and this user can other users manually through a form I give him.
lets say if I save the input entered by the user like the code shown below:
Session.set('name', t.find('#name').value);
Session.set('password', t.find('#pass').value);
Session.set('email', t.find('#email').value);
how do I store those values in those sessions in the Meteor.users, after checking that there is no match in the email and username?
and how do I encrypt the password before storing it in my database?
This code when called from the client side as:
Meteor.call('createUser','someemail#gmail.com','password123',function(err,res){
.....
})
creates a user in Meteor.users collection with the id given below in the method
Meteor.methods({
createUser(email,password){
check(email,String);
check(password,String);
let id = Accounts.createUser({
email: email,
password: password,
profile: {} //anything you like to add to profile.
})
}
})