Skip to content

Instantly share code, notes, and snippets.

@praharshbhatt
Last active December 6, 2019 06:34
Show Gist options
  • Save praharshbhatt/d2d03f5f33b9f8171ccf9fb7a54947d5 to your computer and use it in GitHub Desktop.
Save praharshbhatt/d2d03f5f33b9f8171ccf9fb7a54947d5 to your computer and use it in GitHub Desktop.
Firebase Authentication class for Mobile Flutter
import 'package:cloud_firestore/cloud_firestore.dart' as MobFirebaseFirestore;
import 'package:firebase_auth/firebase_auth.dart' as MobFirebaseAuth;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../main.dart';
MobFirebaseAuth.FirebaseUser firebaseUser;
//For storing user Profile info
Map<String, dynamic> userProfile = new Map();
//This is the main Firebase auth object
MobFirebaseAuth.FirebaseAuth mobAuth = MobFirebaseAuth.FirebaseAuth.instance;
// For google sign in
final GoogleSignIn mobGoogleSignIn = GoogleSignIn();
//CloudFireStore
MobFirebaseFirestore.Firestore dbFirestore = MobFirebaseFirestore.Firestore.instance;
//
//
//
//
bool blIsSignedIn = false;
class AuthService {
// constructor
AuthService() {
checkIsSignedIn().then((_blIsSignedIn) {
//redirect to appropriate screen
mainNavigationPage();
});
}
//Checks if the user has signed in
Future<bool> checkIsSignedIn() async {
//For mobile
if (mobAuth != null && (await mobGoogleSignIn.isSignedIn())) {
firebaseUser = await mobAuth.currentUser();
if (firebaseUser != null) {
//User is already logged in
blIsSignedIn = true;
} else {
blIsSignedIn = false;
}
} else {
blIsSignedIn = false;
}
return blIsSignedIn;
}
//Log in using google
Future<dynamic> googleSignIn() async {
//For mobile
// Step 1
GoogleSignInAccount googleUser = await mobGoogleSignIn.signIn();
// Step 2
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
AuthResult _res = await mobAuth.signInWithCredential(credential);
firebaseUser = _res.user;
return firebaseUser;
return webFirebaseUser;
}
//Gets the userData
getData() async {
//For mobile
dbFirestore.collection("Master").document(firebaseUser.email).snapshots().listen((snapshot) {
if (snapshot.data != null) {
userProfile = snapshot.data;
}
});
}
//Update the data into the database
Future<bool> setData() async {
bool blReturn = false;
//For mobile
await dbFirestore
.collection('Master')
.document(firebaseUser.email)
.setData(userProfile, merge: false)
.then((onValue) async {
blReturn = true;
});
return blReturn;
}
void signOut() {
//For mobile
mobAuth.signOut();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment