flutter firebase authnetication using getx - forget password & delete account

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial we will continue the Integration of Firebase Authentication using GetX flutter library.

Video Tutorial 

Check Out Part 1 of this Firebase Authentication using GetX Library.

https://protocoderspoint.com/flutter-firebase-authentication-using-getx-library-velocity-x/

In the continuation of previous tutorial, We are going to add feature like Flutter Firebase Forget password(using this user can send password reset email flutter) and Firebase Delete auth Account (using which user can permanently delete firebase auth account from firebase auth authentication)

So let’s begin

Flutter Firebase Authentication using GetX library – Forgot password & Delete Account (Part 2)

Forget password / Firebase send password reset email

So if a user forgot his authentication and then he want to reset his firebase password then a developer can make use of a firebase function

sendPasswordResetEmail

that will help developer to send password reset email to user email address,

To build this we need a UI from where a user can request for a password reset,
Note: For this user should atleast remember his email account using which he had create user account on firebase console authentication.

Understanding the process of Authentication password Change/forgot password change

1st Step: User will click Forgot Password button or text

2nd Step: User will be in reset password UI page where he enter his email and the submit

forgot password screen UI flutter

3rd Step : User will get email on his email with a link to reset firebase email auth password

firebase password reset email

4th Step : Clicking on that link user will change the password



Snippet Code / Method to send password reset email 

Called this method will send a request to firebase auth to send a email link to reset the password

void sendpasswordresetemail(String email) async{
    await _auth.sendPasswordResetEmail(email: email).then((value) {
      Get.offAll(LoginPage());
      Get.snackbar("Password Reset email link is been sent", "Success");
    }).catchError((onError)=> Get.snackbar("Error In Email Reset", onError.message) );
 }

So from UI or reset password UI page you need to called this method and  pass a parameter email i.e. entered by the user. (Complete code is below)


Deleting account / Firebase auth delete created account

Note: To delete a account, the user must enter his email and password to re-check his authentication, In other words we need to check if the account holder is the one who want to delete his account.

Understanding the process of firebase Authentication delete account

1st Step: Create a user for deleting account UI
              Using which user can delete his account 

delete firebase auth account

2nd Step: Pass parameter email and password to method

Code is below

3rd Step: Check for Firebase AuthCredential using EmailAuthProvider.credential

4th Step: Then make use of user and reauthentictewithcredential to check if credential get successed or failed.

5th Step : Depending on the credential result if credential pass then just delete the user account and move the user to LoginPage()  

Below Snippet Code

void deleteuseraccount(String email,String pass) async{
    User user = await _auth.currentUser;

    AuthCredential credential = EmailAuthProvider.credential(email: email, password: pass);

    await user.reauthenticateWithCredential(credential).then((value) {
      value.user.delete().then((res) {
        Get.offAll(LoginPage());
        Get.snackbar("User Account Deleted ", "Success");
      });
    }

    ).catchError((onError)=> Get.snackbar("Credential Error", "Failed"));
  }


So from UI or delete firebase auth account UI page you need to called this method and  pass a parameter email and password i.e. entered by the user. (Complete code is below)

Complete source code – Firebase Forget password & delete auth account

https://github.com/RajatPalankar8/Flutter_Login_Registration_UI

FirebaseController.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class FirebaseController extends GetxController{

  FirebaseAuth _auth = FirebaseAuth.instance;

  Rx<User> _firebaseUser = Rx<User>();

  String get user => _firebaseUser.value?.email;

  @override
  void onInit() {
    _firebaseUser.bindStream(_auth.authStateChanges());
  }


  // function to createuser, login and sign out user

 void createUser(String firstname,String lastname,String email,String password) async
 {
   CollectionReference reference = FirebaseFirestore.instance.collection("Users");

   Map<String,String> userdata ={
     "First Name": firstname,
      "Last Name": lastname,
      "Email":email
   };

   await _auth.createUserWithEmailAndPassword(email: email, password: password).
   then((value) {

     reference.add(userdata).then((value) =>  Get.offAll(LoginPage()));
   }).catchError((onError)=>
       Get.snackbar("Error while creating account ", onError.message),
   );
 }

 void login(String email,String password) async
 {
   await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) => Get.offAll(Dashboard())).
       catchError((onError)=>
   Get.snackbar("Error while sign in ", onError.message));
 }

 void signout() async{
 await _auth.signOut().then((value) => Get.offAll(LoginPage()));

 }


 void sendpasswordresetemail(String email) async{
    await _auth.sendPasswordResetEmail(email: email).then((value) {
      Get.offAll(LoginPage());
      Get.snackbar("Password Reset email link is been sent", "Success");
    }).catchError((onError)=> Get.snackbar("Error In Email Reset", onError.message) );
 }

 void deleteuseraccount(String email,String pass) async{
    User user = await _auth.currentUser;

    AuthCredential credential = EmailAuthProvider.credential(email: email, password: pass);


    await user.reauthenticateWithCredential(credential).then((value) {
      value.user.delete().then((res) {
        Get.offAll(LoginPage());
        Get.snackbar("User Account Deleted ", "Success");
      });
    }

    ).catchError((onError)=> Get.snackbar("Credential Error", "Failed"));
  }

}


Forgot Password.dart

Here i have TextField to enter email and a button when press the sendpasswordresetemail method will be called and email will passed.

then forgot password process starts as above.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:velocity_x/velocity_x.dart';

class ForgotPassword extends GetWidget<FirebaseController> {

  TextEditingController email = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Reset Password".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(
                        20
                    ),


                    GestureDetector(
                        onTap: (){

                          controller.sendpasswordresetemail(email.text);

                        },
                        child: "Reset Password".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),

                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>RegistrationPage()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Register Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }



}





DeleteAccount.dart

In delete account page we have 2 textfield to enter Email & Password then a button that called deleteaccount method by passing email,password as parameter.

then the delete auth account process will start as above.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:velocity_x/velocity_x.dart';

class DeleteAccount extends GetWidget<FirebaseController> {

  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Delete Account".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: pass,
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(20),

                    GestureDetector(
                        onTap: (){
                          print("Login Clicked Event");
                          controller.deleteuseraccount(email.text, pass.text);
                        },
                        child: "Delete Account".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),


                  ],
                ),
              )
            ],
          ),
        ),

    );
  }

  void _login() {

    controller.login(email.text, pass.text);
  }

}