97 lines
2.7 KiB
Dart
97 lines
2.7 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:google_sign_in/google_sign_in.dart';
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
import '../../domain/usecases/send_otp.dart';
|
|
import '../../domain/usecases/verify_otp.dart';
|
|
|
|
part 'auth_event.dart';
|
|
part 'auth_state.dart';
|
|
|
|
class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
|
final SendOTP sendOTPUseCase;
|
|
final VerifyOTP verifyOTPUseCase;
|
|
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
|
|
|
|
String _timeStamp = "";
|
|
String _timeDue = "";
|
|
|
|
String get timeStamp => _timeStamp;
|
|
String get timeDue => _timeDue;
|
|
|
|
AuthBloc({
|
|
required this.sendOTPUseCase,
|
|
required this.verifyOTPUseCase,
|
|
}) : super(AuthInitial()) {
|
|
on<SendOTPEvent>(_onSendOTP);
|
|
on<VerifyOTPEvent>(_onVerifyOTP);
|
|
on<SignInWithGoogleEvent>(_onSignInWithGoogle);
|
|
}
|
|
|
|
Future<void> _onSendOTP(SendOTPEvent event, Emitter<AuthState> emit) async {
|
|
emit(AuthLoading());
|
|
final result = await sendOTPUseCase(SendOTPParams(phoneNumber: event.phoneNumber));
|
|
if (result.isSuccess && result.data != null) {
|
|
_timeStamp = result.data!.timeStamp;
|
|
_timeDue = result.data!.timeDue;
|
|
emit(AuthSuccess(
|
|
phoneNumber: event.phoneNumber,
|
|
timeStamp: _timeStamp,
|
|
timeDue: _timeDue,
|
|
));
|
|
} else {
|
|
emit(AuthError('Error sending code. Please try again.'));
|
|
}
|
|
}
|
|
|
|
Future<void> _onVerifyOTP(VerifyOTPEvent event, Emitter<AuthState> emit) async {
|
|
emit(AuthLoading());
|
|
final result = await verifyOTPUseCase(VerifyOTPParams(
|
|
otpCode: event.otpCode,
|
|
phoneNumber: event.phoneNumber,
|
|
));
|
|
if (result.isSuccess && result.data == true) {
|
|
emit(OTPVerified());
|
|
} else {
|
|
emit(AuthError('The code entered is incorrect. Please try again.'));
|
|
}
|
|
}
|
|
|
|
Future<void> _onSignInWithGoogle(
|
|
SignInWithGoogleEvent event,
|
|
Emitter<AuthState> emit,
|
|
) async {
|
|
emit(AuthLoading());
|
|
try {
|
|
final GoogleSignIn googleSignIn = GoogleSignIn(
|
|
scopes: ['email'],
|
|
);
|
|
|
|
final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
|
|
|
|
if (googleUser == null) {
|
|
emit(AuthInitial());
|
|
return;
|
|
}
|
|
|
|
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
|
|
|
|
final credential = GoogleAuthProvider.credential(
|
|
accessToken: googleAuth.accessToken,
|
|
idToken: googleAuth.idToken,
|
|
);
|
|
|
|
final UserCredential userCredential =
|
|
await _firebaseAuth.signInWithCredential(credential);
|
|
|
|
if (userCredential.user != null) {
|
|
emit(GoogleSignInSuccess());
|
|
} else {
|
|
emit(AuthError("Error signing in with Google"));
|
|
}
|
|
|
|
} catch (e) {
|
|
emit(AuthError("Error signing in with Google: ${e.toString()}"));
|
|
}
|
|
}
|
|
|
|
} |