is it possible to delete firebase account in authentication on flutter? if yes, how to do that? I have been search but not found the way.
Firestore.instance.collection("users").document(uid).delete().then((_){
// delete account on authentication after user data on database is deleted
});
Using flutter, if you want to delete firebase accounts together with the associated firestore user collection document, the following method works fine. (documents in user collection named by the firebase uid).
Database Class
class DatabaseService {
final String uid;
DatabaseService({this.uid});
final CollectionReference userCollection =
Firestore.instance.collection('users');
Future deleteuser() {
return userCollection.document(uid).delete();
}
}
Use Firebase version 0.15.0 or above otherwise, Firebase reauthenticateWithCredential() method throw an error like { noSuchMethod: was called on null }.
Authentication Class
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future deleteUser(String email, String password) async {
try {
FirebaseUser user = await _auth.currentUser();
AuthCredential credentials =
EmailAuthProvider.getCredential(email: email, password: password);
print(user);
AuthResult result = await user.reauthenticateWithCredential(credentials);
await DatabaseService(uid: result.user.uid).deleteuser(); // called from database class
await result.user.delete();
return true;
} catch (e) {
print(e.toString());
return null;
}
}
}
Then use the following code inside the clickable event of a flutter widget tree to achieve the goal;
onTap: () async {
await AuthService().deleteUser(email, password);
}
Code for deleting user:
FirebaseUser user = await FirebaseAuth.instance.currentUser();
user.delete();
To delete a user account, call delete() on the user object.
For more on this, see the reference documentation for FirebaseUser.delete().
User user = FirebaseAuth.instance.currentUser;
user.delete();
From this you can delete user
Related
I want to integrate my app with Calendar API from Google. And in order to use it, I have to have an AuthClient (which is obtained from _googleSignIn.authenticatedClient();). The problem is, my GoogleSignIn().currentUser always return null and I don't know why. I already use Firebase Auth and Google Sign In.
This is my signInWithGoogle method:
Future signInWithGoogle() async {
try {
await GoogleSignIn().disconnect();
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
// Trigger the authentication flow
final GoogleSignInAccount? googleUser = await GoogleSignIn(scopes: [CalendarApi.calendarScope]).signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth =
await googleUser!.authentication;
// Create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Once signed in, return the UserCredential
UserCredential result =
await FirebaseAuth.instance.signInWithCredential(credential);
User user = result.user!;
// note: this line always return null and I don't know why
print('current user auth ${GoogleSignIn().currentUser.toString()}');
return _userFromFirebaseUser(user);
}
Did I do something wrong in my code? Any help will be appreciated, thank you!
I also had the issue of GoogleSignIn().currentUser always being null but managed to (finally!) fix it by only initialising GoogleSignIn() once.
For those who want more details: I did this by creating a class called AuthManager that handles everything authentication-related, and making GoogleSignIn one of the parameters required to initialise it (since I'm using Firebase, this was the other parameter):
class AuthManager {
final FirebaseAuth _auth;
final GoogleSignIn _googleSignIn;
AuthManager(this._auth, this._googleSignIn);
Future signInWithGoogle() async {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
// etc....
}
GoogleSignInAccount? get googleAccount {
return _googleSignIn.currentUser;
}
}
And I initiaised by AuthManager class ONCE at the top of my app in a Provider, meaning that I can access it anywhere in my app.
In main.dart:
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
// To use AuthManager throughout app without initialising it each time
Provider<AuthManager>(
create: (_) => AuthManager(
FirebaseAuth.instance,
GoogleSignIn(scopes:
// Put whatever scopes you need here
),
),
),
// etc...
(Note: I used MultiProvider as I had other things I wanted to put, but if you only have one, you can obviously just go straight to Provider).
Now I can successfully get the current google user by getting googleAccount through my AuthManager class.
I am learning Firebase with Flutter.
Currently making an anonymous login option, here is the class I created:
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// sign in anonymously
Future signInAnonymous() async {
try{
// signs in as anon user
AuthResult signInResult = await _auth.signInAnonymously();
// retruns currently signed in user, else null
FirebaseUser userFromResult = signInResult.user;
return userFromResult; // HERE: if I add .uid, the id object is displayed
}catch(e){
print(e.toString());
return null;
}
}
}
In my login page after creating an instance and using the method, when I print the result I get FirebaseUser(Instance of 'PlatformUser') insted of the user information, here is the code:
onPressed: () async {
dynamic result = await _auth.signInAnonymous();
if(result == null){print('Error signing in.');}
else{
print('Signed in successfully');
print(result);
}
How can I access the user data?
UPDATE: If I change return userFromResult; to return userFromResult.uid; the id string is returned.
I still wonder, however, how to print the full object.
Your Result inside of the onpressed is a dynamic type cast, but it is a FirebaseUser inside.
// onPressed Callback
dynamic result = await _auth.signInAnonymous();
You can change your SignIn method with the right return type and use instead of dynamic the FirebaseUser.
Future<FirebaseUser> signInAnonymous() async {
// [...]
return userFromResult; // HERE: if I add .uid, the id object is displayed
}
onPressed: () async {
FirebaseUser result = await _auth.signInAnonymous();
print(result.uid); // should contain the id
// [...]
The difference is that in version 0.13.x the user data is available, but in the version used in this example the bersion used is 0.16.x.
I'm creating an Hospital App in flutter. My goal is to configure firebase in such a way that the root collection is named User/uid(uid which is automatically generated when user is created)/someText/documentID(automatically generated by Firebase). This is my code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mgm_app/models/vaccList.dart';
class DatabaseService {
final String uid;
DatabaseService({this.uid});
CollectionReference userReg = Firestore.instance.collection('User');
CollectionReference vaccTaken = Firestore.instance.collection('User').document(uid).collection('Vaccine Administered');
Future regUserData(String email) async {
return await userReg.document(uid).setData({
'email': email,
});
}
Future updateUserData(String vaccName,String dateAdmin) async {
return await vaccTaken.document().setData({
'name': vaccName,
'vaccine given': dateAdmin,
}
);
}
When a new user registers, a document with their uid is automatically created in the User collection. But when I'm trying to enter some personal data in the folder User/uid/VaccineAdmnistered,
I am not able to pass the value of the current user uid on this line of code
Firestore.instance.collection('User').document(uid).collection('Vaccine Administered');
The error i'm getting is
Only static members can be accessed in initializers.
You are using the uid inside the method document before the constructor is called. Therefore do the following:
class DatabaseService {
final String uid;
DatabaseService({this.uid});
CollectionReference vaccTaken = Firestore.instance.collection('User');
Future regUserData(String email) async {
return await vaccTaken.document(uid).setData({
'email': email,
});
}
Future updateUserData(String vaccName,String dateAdmin) async {
return await vaccTaken.document(uid).collection('Vaccine Administered').document().setData({
'name': vaccName,
'vaccine given': dateAdmin,
}
);
}
Create a variable vaccTaken which will reference the collection User, then inside the method updateUserData access the uid.
I'm creating a app where I should be able of managing users access. The admin should have permissions of creating, deleting and editing users accounts.
I'm using firebase for creating users account.
Right now individually users can creating, editing and delete their accounts, but the problem is that the admin should do that, and not just the users.
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
class UserLoader {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSIgnIn = new GoogleSignIn();
static final UserLoader _singleton = new UserLoader._internal();
FirebaseUser user;
factory UserLoader() {
return _singleton;
}
UserLoader._internal();
Future<FirebaseUser> signInWithEmailAndPassword(email, password) async {
if (user != null) return user;
_signInAnonymously().then((value) {
if (value != null) {
user = value;
}
}).catchError((e) {
return null;
});
if (user == null) {
FirebaseUser user = await _auth.signInWithEmailAndPassword(
email: email, password: password).catchError(
(onError)
{
print(onError);
});
return user;
} else {
return null;
}
}
Future<FirebaseUser> signInWithGoogle() async {
if (user != null) return user;
_signInAnonymously().then((value) {
if (value != null) {
user = value;
}
}).catchError((e) {
print(e.toString());
});
if (user == null) {
GoogleSignInAccount googleSignInAccount = await googleSIgnIn.signIn();
GoogleSignInAuthentication gSA = await googleSignInAccount.authentication;
FirebaseUser user = await _auth.signInWithGoogle(
idToken: gSA.idToken, accessToken: gSA.accessToken);
return user;
} else {
return null;
}
}
Future<FirebaseUser> _signInAnonymously() async {
if (user != null) return user;
user = await _auth.signInAnonymously();
return user;
}
Future signOut() async {
await _auth.signOut();
await googleSIgnIn.signOut();
user = null;
}
Future changePassword(email) async{
await _auth.sendPasswordResetEmail(email: email);
}
Future createNewUser(email){
_auth.createUserWithEmailAndPassword(email: email, password: "new_pass");
}
Future deleteUser(FirebaseUser firebaseUser){
firebaseUser.delete();
}
}
I think that Firebase Admin should do the trick but I'm not sure.
The Firebase Admin SDK is only available for use in trusted environments, such as your development machine, a server you control, or Cloud Functions for Firebase. It is (intentionally) not available for use in client-side apps, such as those deployed on Android or iOS, neither when you build those with native code, nor when you build them through Flutter.
The only option is to implement the functionality you want with the Admin SDK in a trusted environment, and expose an end-point to your Flutter app. If you end up doing this, make sure to secure access to the end-point so that only the admin users of your app can access it. For an example of how to secure access with Cloud Functions, see this sample in the functions-samples repo.
There isn't an SDK for even dart, so if your server-side application is written in Dart then you'll have to depend on another that is written in node.js, Python, C#, Go or Java as these are the only SDKs that are provided.
If you insist on doing this on your client-side app, then FCM HTTP v1 API is your best shot. You can obtain an access token with Google API Auth to access the Google APIs
Doc: Firebase Documentation
Download the admin SDK:
https://pub.dev/packages/firebase_admin
Use:
import 'package:firebase_admin/firebase_admin.dart';
main() async {
var app = FirebaseAdmin.instance.initializeApp(AppOptions(
credential: ServiceAccountCredential('service-account.json'),
));
String customerUserToken = await app.auth().createCustomToken("userId");
}
First time implementing Firebase Auth, also new to Flutter dev, and I'm looking to use email and passwords, not Google sign-in. The only examples I see of Firebase Auth being used are anonymously or with Google. Is there a resource / tutorial that shows how to properly set up the calls with the signInWithEmailAndPassword method?
Many thanks!
In my app I have an auth class because I don't like to litter my widget classes with non-widget code, but you can plop this code inside your widget class if you want.
In auth.dart I have:
import 'package:firebase_auth/firebase_auth.dart';
class Auth {
final FirebaseAuth auth = FirebaseAuth.instance;
Future<User> handleSignInEmail(String email, String password) async {
UserCredential result =
await auth.signInWithEmailAndPassword(email: email, password: password);
final User user = result.user!;
return user;
}
Future<User> handleSignUp(email, password) async {
UserCredential result = await auth.createUserWithEmailAndPassword(
email: email, password: password);
final User user = result.user!;
return user;
}
}
Then in my login/register screen I create an instance of my auth class:
var authHandler = new Auth();
Finally, in my login buttons onPressed callback I have:
onPressed: () {
authHandler.handleSignInEmail(emailController.text, passwordController.text)
.then((FirebaseUser user) {
Navigator.push(context, new MaterialPageRoute(builder: (context) => new HomePage()));
}).catchError((e) => print(e));
}
Here is one example from my service. I ask for the email, name and password fields.
registerWithEmail(String name, String email, String password) async {
First I check if the email is already registered with facebook or something.
List<String> providers = await firebaseAuth.fetchProvidersForEmail(email: email);
This is not ideal solution, but you want to handle if the user is already registered, and than link email with current user
if (providers != null && providers.length > 0) {
print("already has providers: ${providers.toString()}");
return handleProviders(providers);
}
Create new User
FirebaseUser newUser = await firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
await newUser.sendEmailVerification();
This is basically it. I update the name filed of the user, since I have it.
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await firebaseAuth.updateProfile(userUpdateInfo);
await newUser.reload();
And later You can save the user inside your firestore, where user uid is document ID. So I can get it later.
Git repo with full explanation example for Email/Password Sign in Firebase using flutter
This may help you.
Git Repo: https://github.com/myvsparth/firebase_email_signin
Full Article Step by Step: https://www.c-sharpcorner.com/article/how-to-do-simple-login-with-email-id-in-flutter-using-google-firebase/
This code is for register new user
fb_auth.UserCredential userCredential = await fb_auth
.FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
And this is for login previous user
fb_auth.UserCredential userCredential = await fb_auth
.FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password)
And that fb_auth is
import 'package:firebase_auth/firebase_auth.dart' as fb_auth;