Aplikacja_mobilna/cookbook/lib/data/data_sources/firebase_auth_source.dart
2024-02-18 14:30:02 +01:00

82 lines
2.4 KiB
Dart

import 'package:cookbook/data/models/failures/failure_model.dart';
import 'package:cookbook/data/models/firebase_auth_user_model.dart';
import 'package:either_dart/either.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class FirebaseAuthSource {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
/// Returns a [FirebaseAuthUserModel] object with the information of logged User.
/// If the user is not logged, returns null.
Either<FailureModel, FirebaseAuthUserModel?> getLoggedUser() {
if (_auth.currentUser != null) {
return Right(FirebaseAuthUserModel(
displayName: _auth.currentUser!.displayName!,
email: _auth.currentUser!.email!,
uid: _auth.currentUser!.uid,
));
} else {
return const Right(null);
}
}
/// Sign in with Google.
/// Returns a [FirebaseAuthUserModel] object with the information of logged User.
/// If the user is not logged, returns null.
/// If the user is logged then returns a information of logged user.
Future<Either<FailureModel, FirebaseAuthUserModel?>> signInWithGoogle() async {
try {
var currentUser = getLoggedUser();
if (currentUser.isRight && currentUser.right != null) return currentUser;
var googleUser = _googleSignIn.currentUser;
if (googleUser == null) {
await _googleSignIn.signIn();
}
googleUser = _googleSignIn.currentUser;
if (googleUser == null) {
return Left(FailureModel(
message: 'Google User is not logged',
));
}
var googleAuth = await googleUser.authentication;
var credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
currentUser = getLoggedUser();
if (currentUser.isRight) {
return currentUser;
} else {
return Left(FailureModel(
message: 'User is not logged',
));
}
} catch (e) {
return Left(FailureModel(
message: e.toString(),
));
}
}
Future<Either<FailureModel, void>> signOutUser() async {
try {
await _auth.signOut();
return const Right(null);
} catch (e) {
return Left(FailureModel(
message: e.toString(),
));
}
}
}