Skip to content

Instantly share code, notes, and snippets.

@amirul12
Created October 27, 2022 11:03
Show Gist options
  • Save amirul12/638e65e8686631cb3407384ed4da4370 to your computer and use it in GitHub Desktop.
Save amirul12/638e65e8686631cb3407384ed4da4370 to your computer and use it in GitHub Desktop.
import 'package:bizcard/model/business_card/business_card_model.dart';
import 'package:bizcard/model/user/user_model.dart';
import 'package:bizcard/util/testing.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class FirebaseServiceRepository {
final FirebaseAuth _firebaseAuth;
final GoogleSignIn _googleSignIn;
final FirebaseFirestore _firebaseFirestore;
FirebaseServiceRepository(
{FirebaseAuth? firebaseAuth,
GoogleSignIn? googleSignIn,
FirebaseFirestore? firebaseFirestore})
: _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance,
_firebaseFirestore = firebaseFirestore ?? FirebaseFirestore.instance,
_googleSignIn = googleSignIn ?? GoogleSignIn();
Future<User> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser!.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
await _firebaseAuth.signInWithCredential(credential);
UserModel userModel = UserModel().copyWith(
id: _firebaseAuth.currentUser!.uid,
name: _firebaseAuth.currentUser!.displayName,
email: _firebaseAuth.currentUser!.email,
);
_firebaseFirestore
.collection("users")
.doc(_firebaseAuth.currentUser!.uid)
.set(userModel.toDocument());
return Future.value(_firebaseAuth.currentUser);
} catch (e) {
throw Exception(e.toString());
}
}
Future<dynamic> resetPassword({required String email}) async {
try {
await _firebaseAuth.sendPasswordResetEmail(email: email);
} catch (e) {
throw Exception(e.toString());
}
}
Future<void> signUp(
{required String email,
required String password,
required String displayName}) async {
try {
await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
throw Exception('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
throw Exception('The account already exists for that email.');
}
} catch (e) {
throw Exception(e.toString());
}
var currentUser = _firebaseAuth.currentUser;
//update info
await currentUser!.updateDisplayName(displayName);
}
Future<void> signIn({
required String email,
required String password,
}) async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
throw Exception('No user found for that email.');
} else if (e.code == 'wrong-password') {
throw Exception('Wrong password provided for that user.');
}
}
}
Future<void> signInWithFacebook() async {
try {
// Trigger the sign-in flow
final LoginResult result = await FacebookAuth.instance
.login(permissions: ['email', 'public_profile', 'user_birthday']);
sktPrint(result.status);
if (result.status == LoginStatus.success) {
// Create a credential from the access token
final OAuthCredential facebookAuthCredential =
FacebookAuthProvider.credential(result.accessToken!.token);
final userData = await FacebookAuth.instance.getUserData();
print(userData);
var userEmail = userData['email'];
var name = userData['name'];
var id = userData["id"];
UserModel userModel = UserModel().copyWith(
id: id,
name: name,
email: userEmail,
);
try {
// Once signed in, return the UserCredential
_firebaseAuth.signInWithCredential(facebookAuthCredential);
_firebaseAuth.currentUser;
_firebaseFirestore
.collection("users")
.doc(_firebaseAuth.currentUser!.uid)
.set(userModel.toDocument());
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
throw Exception('No user found for that email.');
} else if (e.code == 'wrong-password') {
throw Exception('Wrong password provided for that user.');
} else {
throw Exception('something went wrong $e');
}
}
} else if (result.status == LoginStatus.failed) {
throw Exception('Error.${result.status}');
} else if (result.status == LoginStatus.cancelled) {
throw Exception('you cancel the login, try again.');
} else {
throw Exception('you cancel the login, try again.${result.status}');
}
} on FirebaseAuthException catch (e) {
sktPrint(e);
if (e.code == 'user-not-found') {
throw Exception('No user found for that email.');
} else if (e.code == 'wrong-password') {
throw Exception('Wrong password provided for that user.');
} else {
throw Exception('Something went wrong. .$e');
}
}
}
Future signOut() async {
try {
return Future.wait([
_firebaseAuth.signOut(),
_googleSignIn.signOut(),
FacebookAuth.instance.logOut(),
]);
} catch (e) {
throw Exception(e);
}
}
Future<bool> isSignedIn() async {
final currentUser = _firebaseAuth.currentUser;
return currentUser != null;
}
Future<String> getUser() async {
return _firebaseAuth.currentUser!.displayName!;
}
Future<void> sendOtp(
String phoneNumber,
Duration timeOut,
PhoneVerificationFailed phoneVerificationFailed,
PhoneVerificationCompleted phoneVerificationCompleted,
PhoneCodeSent phoneCodeSent,
PhoneCodeAutoRetrievalTimeout autoRetrievalTimeout) async {
_firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: timeOut,
verificationCompleted: phoneVerificationCompleted,
verificationFailed: phoneVerificationFailed,
codeSent: phoneCodeSent,
codeAutoRetrievalTimeout: autoRetrievalTimeout);
}
Future<dynamic> verifyAndLogin(String verificationId, String smsCode) async {
AuthCredential authCredential = PhoneAuthProvider.credential(
verificationId: verificationId, smsCode: smsCode);
return _firebaseAuth.signInWithCredential(authCredential);
}
Future<dynamic> getUserS() async {
var user = _firebaseAuth.currentUser!;
return user;
}
Future<void> saveBizCard(BusinessCardModel model) {
_firebaseFirestore
.collection("cards")
.doc(_firebaseAuth.currentUser!.uid)
.collection(model.name! + model.id!)
.add(model.toMap());
return Future.value();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment