Files
social-app/apps/lib/features/auth/presentation/bloc/auth_bloc.dart
T
qzl 0661016827 feat(auth): transition from email to phone-based OTP authentication
- Replace Email+Password login with Phone+OTP flow
- Remove RegisterCubit and registration screens (email verification)
- Remove ResetPasswordCubit and reset password screens
- Add phone normalization and international dial code support
- Update LoginCubit with sendCode/resend cooldown logic
- Add new widgets: phone prefix selector, confirm sheet
- Update all auth API endpoints: /otp/send, /phone-session
- Update form inputs: Email -> Phone with E.164 validation
- Update tests for new auth flow
2026-03-19 18:42:05 +08:00

81 lines
2.2 KiB
Dart

import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/auth_repository.dart';
import 'auth_event.dart';
import 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository _repository;
AuthBloc(this._repository) : super(AuthInitial()) {
on<AuthStarted>(_onStarted);
on<AuthLoggedIn>(_onLoggedIn);
on<AuthLoggedOut>(_onLoggedOut);
on<AuthSessionInvalidated>(_onSessionInvalidated);
}
Future<void> _onStarted(AuthStarted event, Emitter<AuthState> emit) async {
emit(AuthLoading());
try {
final refreshToken = await _repository.getRefreshToken();
if (refreshToken != null) {
final response = await _repository.refreshSession(refreshToken);
emit(
AuthAuthenticated(
user: AuthUser(id: response.user.id, phone: response.user.phone),
),
);
return;
}
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut),
);
} catch (_) {
try {
await _repository.clearSessionLocalOnly();
} catch (_) {
// Keep state convergence even when storage cleanup fails.
} finally {
emit(
const AuthUnauthenticated(
reason: AuthUnauthenticatedReason.startupRecoveryFailed,
),
);
}
}
}
void _onLoggedIn(AuthLoggedIn event, Emitter<AuthState> emit) {
emit(AuthAuthenticated(user: event.user));
}
Future<void> _onLoggedOut(
AuthLoggedOut event,
Emitter<AuthState> emit,
) async {
try {
await _repository.deleteSession();
} catch (_) {
// Keep state convergence even when logout cleanup fails.
} finally {
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut),
);
}
}
Future<void> _onSessionInvalidated(
AuthSessionInvalidated event,
Emitter<AuthState> emit,
) async {
try {
await _repository.clearSessionLocalOnly();
} catch (_) {
// Keep state convergence even when local cleanup fails.
} finally {
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.expired),
);
}
}
}