Add AuthService Class for Google and GitHub Authentication

This commit introduces the AuthService class, which encapsulates the logic for signing in with Google and GitHub using Firebase Authentication. The class provides methods for initiating the OAuth flows for both providers and for signing out the user.

- Implemented `signInWithGoogle()` to handle Google Sign-In.
- Implemented `signInWithGitHub()` to handle GitHub Sign-In via popup.
- Added `signOut()` method for logging out the user.
- Added `getCurrentUser()` method to fetch the currently authenticated user.
This commit is contained in:
hunteraraujo
2023-09-15 14:20:18 -07:00
parent 001b795ea0
commit a6541b60fc

View File

@@ -0,0 +1,50 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn(
clientId:
"387936576242-iejdacrjljds7hf99q0p6eqna8rju3sb.apps.googleusercontent.com");
// Sign in with Google
Future<UserCredential?> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
return await _auth.signInWithCredential(credential);
}
} catch (e) {
print("Error during Google Sign-In: $e");
return null;
}
}
// Sign in with GitHub
Future<UserCredential?> signInWithGitHub() async {
try {
final GithubAuthProvider provider = GithubAuthProvider();
return await _auth.signInWithPopup(provider);
} catch (e) {
print("Error during GitHub Sign-In: $e");
return null;
}
}
// Sign out
Future<void> signOut() async {
await _auth.signOut();
}
// Get current user
User? getCurrentUser() {
return _auth.currentUser;
}
}