Firestore and google auth with role base authorization in Flutter

Viewed 380

At the time when user sign in to my app using google sign in with firebase how can I check that if user already have data or not in firestore database if yes then my app will check for user role and redirect user to the screen acc. to the role else it will create a document in firestore database with name, email, role and uid stored. but the problem is we cannot differentiate between signup and sign in with google auth like we can do in email and password auth. when user make purchase in our app his/her role will be changed to expert but due calling the signinwithgoogle in login page the user role is again being set to basic in database. hope you understood the problem.

Here is my auth.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:gfd_official/User/User.dart';
import 'package:gfd_official/services/database.dart';
import 'package:google_sign_in/google_sign_in.dart';

String photoUrl;

class AuthService {
 final FirebaseAuth _auth = FirebaseAuth.instance;

 // create user obj based on firebase user
 Userdat _userFromFirebaseUser(User user) {
  return user != null ? Userdat(uid: user.uid) : null;
 }

 // auth change user stream
 Stream<Userdat> get user {
  return _auth
    .authStateChanges()
    //.map((FirebaseUser user) => _userFromFirebaseUser(user));
    .map(_userFromFirebaseUser);
  }

 Future signInWithGoogle() async {
GoogleSignIn googleSignIn = GoogleSignIn();
final acc = await googleSignIn.signIn();
final auth = await acc.authentication;
final credential = GoogleAuthProvider.credential(
    accessToken: auth.accessToken, idToken: auth.idToken);
try {
  final res = await _auth.signInWithCredential(credential);
  User user = res.user;
  photoUrl = user.photoURL;
 //create a new document for the user with the uid
  await DatabaseService(uid: user.uid)
      .updateUserData(user.displayName, user.email, 'basic', user.uid);
  return _userFromFirebaseUser(user);
} catch (e) {
  print(e.toString());
  return null;
}
}

Future logOut() {
try {
  GoogleSignIn().signOut();
  return _auth.signOut();
} catch (e) {
  print(e.toString());
  return null;
}
}
}

class UserHelper {
static FirebaseFirestore _db = FirebaseFirestore.instance;

static saveUser(User user) async {
Map<String, dynamic> userData = {
  "name": user.displayName,
  "email": user.email,
  "role": "basic",
};
try {
  final userRef = _db.collection("users").doc(user.uid);
  if ((await userRef.get()).exists) {
    await userRef.update({});
  } else {
    await _db.collection("users").doc(user.uid).set(userData);
  }
} catch (e) {
  print(e.toString());
}
}
}

This is my loginpage.dart

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';
import 'package:gfd_official/Login_data/auth.dart';

class Loginpage extends StatefulWidget {
@override
_LoginpageState createState() => _LoginpageState();
}

class _LoginpageState extends State<Loginpage> {
final AuthService _authService = AuthService();

@override
 Widget build(BuildContext context) {
 return Scaffold(
  backgroundColor: Colors.red[50],
  body: Container(
    child: Column(
      children: [
        SizedBox(
          height: 360,
        ),
        Text(
          'Yaha par Login Kare',
          style: TextStyle(
            fontSize: 30,
            color: Colors.grey[800],
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(
          height: 50,
        ),
        Center(
          child: GoogleSignInButton(
            onPressed: () async {
              dynamic result = await _authService.signInWithGoogle();
              if (result == null) {
              } else {
                
              }
            },
            darkMode: true,
            textStyle: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                fontFamily: "Roboto",
                color: Colors.white),
            borderRadius: 20,
          ),
        ),
      ],
    ),
  ),
);
}
 }

this is my database class

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:gfd_official/User/User.dart';

class DatabaseService {
final String uid;
DatabaseService({this.uid});

//collection  reference
 final CollectionReference userCollection =
  FirebaseFirestore.instance.collection('users');

Future updateUserData(String name, String email, String role, String 
userId) 
 async {
 return await userCollection.doc(uid).set({
  'name': name,
  'email': email,
  'role': role,
  'userId': userId,
},
SetOptions(merge: true));
}

//user data from snapshot
 UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
  final usersn = snapshot.data();
  return UserData(
  uid: uid,
  name: usersn['name'],
  email: usersn['email'],
  role: usersn['role'],
 );
}

//get user data
Stream<QuerySnapshot> get userrole {
return userCollection.snapshots();
 }

//get user doc stream
 Stream<UserData> get userData {
return userCollection.doc(uid).snapshots().map(_userDataFromSnapshot);
}
}
0 Answers
Related