How to make Role-Based login with Flutter and Firbase

This is my auth.dart page to authenticate user. Now I want to go to Firebase collections 'users' table, if the value of the 'type' is 'Admin' navigate to AdminPage(), if it's 'Student' than navigate to StudentPage(). I have tried many thing but I couldn't find the answer.

1

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:modernlogintute/pages/admin_page.dart';
import 'package:modernlogintute/pages/location_page.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:modernlogintute/pages/login_page.dart';
import 'home_page.dart';
import 'login_or_register_page.dart';

class AuthPage extends StatelessWidget {
  const AuthPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          // user is logged in
          if (snapshot.hasData) {
            return LocationPage();
          }

          // user is NOT logged in
          else {
            return LoginOrRegisterPage();
          }
        },
      ),
    );
  }
}

Upvotes: 0

Views: 1267

Answers (1)

Amin Arshadinia
Amin Arshadinia

Reputation: 306

Instead of return LocationPage direclry , do something like code below. You may need to change it a bit according to your code.

Or you can follow this video so you can fully understand what is going on : Tutorial on how to handle simple role base login

User? user = FirebaseAuth.instance.currentUser;
var firebaseData = FirebaseFirestore.instance
        .collection('users')
        .doc(user!.uid)
        .get()
        .then((DocumentSnapshot documentSnapshot) {
  if (documentSnapshot.exists) {
    if (documentSnapshot.get('type') == "Admin") {
       Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) =>  AdminPage(),
      ),
    );
    }else{
      Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) =>  StudentPage(),
      ),
    );
    }
  } else {
    print('Document doesn't exist on the DB');
  }
});

Upvotes: 0

Related Questions