Home > Software engineering >  Flutter Firebase web authentication setup issue
Flutter Firebase web authentication setup issue

Time:08-05

Description:

Trying to setup firebase authentication for web. Please guide how to implement and the steps needed for it. Or if there is some tutorial that explain it well. Need to way to implement authencication for web version only. Any help would be appreciated alot.

Here is I tried but not working for auth and getx. Thank you.

Future<void> checkLoginAndRediect() async {
  Authentication authentication = Authentication();
  final UserController userController = Get.find(tag: 'userController');

  await authentication.autoLogin();

  if (userController.previouslyLoggedIn) {
    Get.offAll(
      const Home(),
    );
  } else {
    Get.offAll(
      const SignupPage(),
    );
  }

Future<bool> init() async {
    if (userID.isNotEmpty) {
      userController.userID = userID;
      var document = await FirebaseFirestore.instance
          .collection('users')
          .doc(userID)
          .get();
      if (document.exists) {
        //updaiting user data locally from firebase
        userController.setUser(
          userID,
          document.data()!['name'],
          document.data()!['phone'],
          document.data()!['email'],
          document.data()!['username'],
          document.data()!['profilePictureLink'] ??
              "https://firebasestorage.googleapis.com/v0/b/matab-a53a8.appspot.com/o/DefaultProfile.png?alt=media&token=716eca5e-b939-4dfa-8e8e-72b0efc75f7f", //there is always a default profile picture but for those user which are reqistered earlier it will replace their as soon as they sign in, with default dummy pic
        );
        //fetching user's addresss from firebase
        addressDatabaseService
            .getAddress(userID)
            .then((value) {})
            .catchError((error) {
          return false;
        });
        //fetching bank details here
        var bankDetails =
            FirebaseFirestore.instance.collection('bankDetails').doc("1").get();
        bankDetails.then((value) {
          transactionController.setBankDetails(
              value.data()!['bankName'],
              value.data()!['accountNumber'],
              value.data()!['accountTitle'],
              value.data()!['bankBranch']);
          orderController.userID = userID;
        }).catchError((error) {
          debugPrint(error.toString());
        });
        //fetching user optional details from firebase if already exists there
        optionalProfileDetailsController.getProfileDetails(
            userID); //this will fetch and store user optional details in controller, controller calls database service itself to fetch data from database

        userController.previouslyLoggedIn =
            true; //updating user already exists flag to true

      }

      return true;
    } else {
      return false;
    }
  }

  Future<void> autoLogin() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool userStatus = prefs.containsKey('uid');
    if (userStatus) {
      String? uid = prefs.getString('uid');
      userID = uid!;

      userController.userID = userID;
      await init();

      userController.previouslyLoggedIn = true;
    } else {
      userController.previouslyLoggedIn =
          false; //if this is false then in main.dart=>checkLoginAndRediect we will check for this and redirect user to signup page
      debugPrint("not connected");
    }
  }

  login(String identifier, String password) async {
    String errorMessage;
    final auth = FirebaseAuth.instance;
    try {
      final UserCredential userCredential = await auth
          .signInWithEmailAndPassword(email: identifier, password: password);
      final User? user = userCredential.user;
      if (user != null) {
        if (!user.emailVerified) {
          Get.snackbar(" Email not Verified ", "Please verify your email.",
              colorText: whiteColor,
              backgroundColor: Colors.red,
              duration: const Duration(seconds: 5),
              snackPosition: SnackPosition.BOTTOM);
          return;
        } else {
          userID = user.uid;
          userController.userID = userID;
          SharedPreferences prefs = await SharedPreferences.getInstance();
          prefs.setString('uid', userCredential.user!.uid);

          await init();

          Get.offAll(() => const Home());
        }
      }
    } on FirebaseAuthException catch (error) {
      switch (error.code) {
        case "user-not-found":
          errorMessage = "Incorrect Email or Password".tr;
          break;
        case "wrong-password":
          errorMessage = "Incorrect Password".tr;
          break;
        case "invalid-email":
          errorMessage = "Email is not valid.".tr;
          break;

        default:
          errorMessage = "Something Went Wrong,";
      }
      Get.snackbar(errorMessage, "Please Try Again".tr,
          snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.red);
    }
  }

  signUp(String name, String phone, int usercnic, String email, String password,
      String confirmPassword) async {
    //below is a default image link, it will be replaced by user's profile picture when he/she sign up for the first time later on he can updateq his/her profile picture
    String profilePictureLink =
        "https://firebasestorage.googleapis.com/v0/b/matab-a53a8.appspot.com/o/DefaultProfile.png?alt=media&token=716eca5e-b939-4dfa-8e8e-72b0efc75f7f";
    final auth = FirebaseAuth.instance;
    String errorMessage;
    if (confirmPassword != password) {
      generateError("Incorrect Confirm password".tr, "Please try again".tr);
      return;
    }

    try {
      final UserCredential signUPResponse =
          await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      User? user = signUPResponse.user;
      if (user != null) {
        userDBService.addUser(
            user.uid, name, phone, email, usercnic, profilePictureLink);
        userController.setUser(
            user.uid, name, phone, email, usercnic, profilePictureLink);
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('uid', user.uid);
        await user.sendEmailVerification();
        Get.snackbar(
          "Email Verification",
          "Please verify your email",
          snackPosition: SnackPosition.BOTTOM,
        );
        var bankDetails =
            FirebaseFirestore.instance.collection('bankDetails').doc("1").get();
        bankDetails.then((value) {
          transactionController.setBankDetails(
              value.data()!['bankName'],
              value.data()!['accountNumber'],
              value.data()!['accountTitle'],
              value.data()!['bankBranch']);
        }).catchError((error) {
          throw (error);
        });
      }

      Get.offAll(() => const LoginPage());
    } on FirebaseAuthException catch (error) {
      switch (error.code) {
        case "user-not-found":
          errorMessage = "Incorrect Email or Password";
          break;
        case "wrong-password":
          errorMessage = "Incorrect Password";
          break;
        case "email-already-in-use":
          errorMessage = "Email already in use";
          break;
        case "invalid-email":
          errorMessage = "Email is not valid.";
          break;
        case "weak-password":
          errorMessage = "Password should be at least 6 characters ";
          break;

        default:
          errorMessage = error.code;
      }
      // Get.snackbar(errorMessage.tr, "Please Try Again.".tr,
      //     snackPosition: SnackPosition.BOTTOM);
      generateError(errorMessage.tr, "Please Try Again.".tr);
    }
  }

CodePudding user response:

You should read the setup documentation, which has a step-by-step guide for Flutter Web. Then, read the auth documentation to finish your setup.

My best advice would be to do so in a super simple project first, without any external libraries, so that you actually understand one library at a time.

CodePudding user response:

You need to start by adding the lib

flutter pub add firebase_auth

then you need to make sure you installed firebase core and it's working from your app to firebase,

flutter pub add firebase_core

to init your firebase app, start by setting the options

class DefaultFirebaseOptions {
  static FirebaseOptions get currentPlatform {
    if (kIsWeb) {
      return web;
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        return android;
      case TargetPlatform.iOS:
        return ios;
      case TargetPlatform.macOS:
        return macos;
      case TargetPlatform.windows:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for windows - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
      case TargetPlatform.linux:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for linux - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
      default:
        throw UnsupportedError(
          'DefaultFirebaseOptions are not supported for this platform.',
        );
    }
  }
  static const FirebaseOptions web = FirebaseOptions(
    apiKey: ,
    appId: ,
    messagingSenderId: ,
    projectId: ,
    authDomain: ,
    storageBucket: ,
    measurementId: ,
  );

and the initialization of your app

    switch (defaultTargetPlatform) {
      case TargetPlatform.windows:
        _app = await desktop.Firebase.initializeApp(
          options: DefaultFirebaseOptions.currentPlatform,
        );
        break;
      default:
        _app = await Firebase.initializeApp(
            options: DefaultFirebaseOptions.currentPlatform);
    }
await Firebase.initializeApp();

and todo simple log in try

try {
  final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: emailAddress,
    password: password,
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'weak-password') {
    print('The password provided is too weak.');
  } else if (e.code == 'email-already-in-use') {
    print('The account already exists for that email.');
  }
} catch (e) {
  print(e);
}

for more info please follow: https://pub.dev/packages/fireflutter

  • Related