Files
eatvio_app/lib/features/registration_v2/cubit/registration_cubit.dart
alex-chevski cba2689406 feat(session): centralize session teardown and refresh
Add SessionLifecycleService to reset user-scoped cubits, analytics, socket id and account-scoped preferences on logout, 401 or account deletion. Run the same refresh after every successful auth path, including registration v1/v2, and ignore 401 responses from stale tokens so an old request cannot terminate the new user's session.

Refs: #1113
2026-10-30 15:15:28 +03:00

302 lines
9.0 KiB
Dart

import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/core/utils/validation_utils.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart';
import 'package:eatvio_app/features/registration_v2/models/registration_model.dart';
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:eatvio_app/core/error_reporting/report_from.dart';
import 'package:gpassword/gpassword.dart';
class RegistrationCubitV2 extends Cubit<RegistrationStateV2> {
final RegistrationRepositoryV2 registrationRepository;
final FirebaseApi firebaseApi;
final SessionLifecycleService sessionLifecycleService;
RegistrationCubitV2({
required this.registrationRepository,
required this.firebaseApi,
required this.sessionLifecycleService,
}) : super(const RegistrationStateV2());
void setFirstName(String firstName) {
emit(state.copyWith(firstName: firstName));
validateFirstName();
}
void setLastName(String lastName) {
emit(state.copyWith(lastName: lastName));
validateLastName();
}
void setEmail(String email) {
emit(state.copyWith(email: email));
validateEmail();
}
void setPhone(String phone) {
emit(state.copyWith(phone: phone));
validatePhone();
}
void setBirthday(DateTime birthday) {
emit(state.copyWith(birthday: birthday));
validateBirthday();
}
void setGender(String gender) {
emit(state.copyWith(gender: gender));
validateGender();
}
void setWeight(int weight) {
emit(state.copyWith(weight: weight));
validateWeight();
}
void setHeight(int height) {
emit(state.copyWith(height: height));
validateHeight();
}
void setActivityCoefficient(double activityCoefficient) {
emit(state.copyWith(activityCoefficient: activityCoefficient));
validateActivityCoefficient();
}
void setPassword(String password) {
emit(state.copyWith(password: password));
}
bool validateFirstName() {
if (state.firstName.isEmpty) {
emit(state.copyWith(isFirstNameValid: false));
return false;
}
emit(state.copyWith(isFirstNameValid: true));
return true;
}
bool validateLastName() {
if (state.lastName.isEmpty) {
emit(state.copyWith(isLastNameValid: false));
return false;
}
emit(state.copyWith(isLastNameValid: true));
return true;
}
bool validateEmail() {
if (state.email.isEmpty) {
emit(state.copyWith(isEmailValid: false));
return false;
}
emit(state.copyWith(isEmailValid: true));
return true;
}
bool validatePhone() {
if (state.phone.isEmpty) {
emit(state.copyWith(isPhoneValid: false));
return false;
}
emit(state.copyWith(isPhoneValid: true));
return true;
}
bool validateGender() {
if (state.gender.isEmpty) {
emit(state.copyWith(isGenderValid: false));
return false;
}
emit(state.copyWith(isGenderValid: true));
return true;
}
bool validateWeight() {
if (state.weight == 0) {
emit(state.copyWith(isWeightValid: false));
return false;
}
emit(state.copyWith(isWeightValid: true));
return true;
}
bool validateHeight() {
if (state.height == 0) {
emit(state.copyWith(isHeightValid: false));
return false;
}
emit(state.copyWith(isHeightValid: true));
return true;
}
bool validateActivityCoefficient() {
if (state.activityCoefficient == 0) {
emit(state.copyWith(isActivityCoefficientValid: false));
return false;
}
emit(state.copyWith(isActivityCoefficientValid: true));
return true;
}
bool validateBirthday() {
if (state.birthday == null) {
emit(state.copyWith(isBirthdayValid: false));
return false;
}
emit(state.copyWith(isBirthdayValid: true));
return true;
}
void nextStep() {
emit(state.copyWith(step: 1));
}
void prevStep() {
emit(state.copyWith(step: 0));
}
bool validateAllFields() {
if (!validateFirstName() ||
!validateLastName() ||
!validateEmail() ||
!validatePhone() ||
!validateGender() ||
!validateWeight() ||
!validateHeight() ||
!validateActivityCoefficient() ||
!validateBirthday()) {
return false;
}
return true;
}
Future<(bool, bool)> register() async {
if (!validateAllFields()) {
return (false, true);
}
final birthday = state.birthday?.format('yyyy-MM-dd');
if (birthday == null) {
validateBirthday();
return (false, true);
}
final password = await _generatePassword();
final registrationModel = RegistrationModel(
firstName: state.firstName,
lastName: state.lastName,
email: state.email,
phone: ValidationUtils.normalizePhone(state.phone),
gender: state.gender,
password: password,
confirmPassword: password,
weight: state.weight,
height: state.height,
activityCoefficient: state.activityCoefficient,
birthday: birthday,
);
bool didApiComplainOnValidation = false;
String errorMessage = '';
try {
final token = await registrationRepository.register(
registrationModel: registrationModel,
);
if (token != null) {
await TokenStorage.saveTokenInStorage(token);
await sessionLifecycleService.onAuthenticated();
emit(state.copyWith(registrationError: null));
return (true, false);
}
} on DioException catch (e, st) {
await reportFrom(e, st, this);
final errors = e.response?.data['errors'] as Map<String, dynamic>?;
final emailErrors = errors?['email'] as List<dynamic>?;
final phoneErrors = errors?['phone'] as List<dynamic>?;
final dateOfBirth = errors?['date_of_birth'] as List<dynamic>?;
// Собираем все ошибки для отображения в диалоге
List<String> allErrors = [];
if (emailErrors != null && emailErrors.isNotEmpty) {
for (var error in emailErrors) {
allErrors.add(error.toString());
if (error.toString() == 'Некорректный формат email') {
emit(
state.copyWith(
isEmailValid: false,
emailDisplayError: 'Некорректный формат email',
),
);
didApiComplainOnValidation = true;
}
if (error.toString() == 'Такой Эл. почта уже существует.') {
emit(
state.copyWith(
isEmailValid: false,
emailDisplayError: 'Такая Эл. почта уже существует.',
),
);
didApiComplainOnValidation = true;
}
}
}
if (phoneErrors != null && phoneErrors.isNotEmpty) {
for (var error in phoneErrors) {
allErrors.add(error.toString());
if (error.toString() == 'Такой phone уже существует.') {
emit(
state.copyWith(
isPhoneValid: false,
phoneDisplayError: 'Такой номер телефона уже существует.',
),
);
didApiComplainOnValidation = true;
}
}
}
if (dateOfBirth != null && dateOfBirth.isNotEmpty) {
for (var error in dateOfBirth) {
allErrors.add(error.toString());
if (error.toString() == 'Некорректный формат даты рождения') {
emit(
state.copyWith(
isBirthdayValid: false,
dateOfBirthDisplayError: 'Некорректный формат даты рождения',
),
);
didApiComplainOnValidation = true;
}
}
}
// Сохраняем все ошибки для отображения в диалоге
if (allErrors.isNotEmpty) {
errorMessage = allErrors.join('\n');
emit(state.copyWith(registrationError: errorMessage));
} else {
// Если нет конкретных ошибок, берем общее сообщение
final message = e.response?.data['message'] as String?;
errorMessage = message ?? 'Ошибка при регистрации';
emit(state.copyWith(registrationError: errorMessage));
}
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString());
errorMessage = e.toString();
emit(state.copyWith(registrationError: errorMessage));
}
return (false, didApiComplainOnValidation);
}
Future<String> _generatePassword() async {
final generator = GPassword();
final password = generator.generate(passwordLength: 10);
emit(state.copyWith(password: password));
return password;
}
}