forked from eatvio/eatvio_app
feat(auth): align password policy and handle 429 responses
- map 429 Retry-After to a localized toast in AuthCubit - enforce the 8-character minimum on registration v1 and add the hint - surface errors.password in registration v2 - show password errors from 422 responses in the reset flow - add ru/en localization strings and regenerate l10n - add a regression test for the 429/Retry-After path
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||
@@ -9,6 +10,7 @@ import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart';
|
||||
import 'package:eatvio_app/features/auth/repositories/auth_repository.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
import 'package:flutter_native_splash/flutter_native_splash.dart';
|
||||
@@ -42,6 +44,25 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
if (e is DioException && e.response?.statusCode == 429) {
|
||||
final response = e.response;
|
||||
final data = response?.data;
|
||||
final error = data is Map ? data['error'] : null;
|
||||
final retryAfter =
|
||||
response?.headers.value('retry-after') ??
|
||||
(error is Map ? error['retry_after']?.toString() : null);
|
||||
final serverMessage = error is Map && error['message'] is String
|
||||
? error['message'] as String
|
||||
: data is Map && data['message'] is String
|
||||
? data['message'] as String
|
||||
: null;
|
||||
final message = retryAfter != null && retryAfter.isNotEmpty
|
||||
? S.current.too_many_login_attempts(int.tryParse(retryAfter) ?? 0)
|
||||
: serverMessage ?? S.current.too_many_login_attempts_no_retry;
|
||||
showErrorToast(message);
|
||||
emit(AuthState.error(errorMessage: message));
|
||||
return false;
|
||||
}
|
||||
showErrorToast('Неверный адрес электронной почты или пароль');
|
||||
emit(AuthState.error(errorMessage: '$e'));
|
||||
return false;
|
||||
|
||||
@@ -8,7 +8,10 @@ class ResetPasswordCubit extends Cubit<ResetPasswordState> {
|
||||
|
||||
ResetPasswordCubit({required this.resetPasswordRepository}) : super(const ResetPasswordState.empty());
|
||||
|
||||
String? get errorMessage => resetPasswordRepository.lastError;
|
||||
|
||||
Future<void> trySendEmailCode(String email) async {
|
||||
resetPasswordRepository.clearError();
|
||||
emit(const ResetPasswordState.loadingSendEmailCode());
|
||||
try {
|
||||
if (await resetPasswordRepository.sendEmailCodeForPasswordChange(email)) {
|
||||
@@ -23,6 +26,7 @@ class ResetPasswordCubit extends Cubit<ResetPasswordState> {
|
||||
}
|
||||
|
||||
Future<void> tryResetPassword(String email, String code, String password, String passwordConfirmation) async {
|
||||
resetPasswordRepository.clearError();
|
||||
emit(const ResetPasswordState.loadingResetPassword());
|
||||
try {
|
||||
if (await resetPasswordRepository.confirmPasswordChange(code, password, passwordConfirmation, email)) {
|
||||
|
||||
@@ -108,10 +108,10 @@ class _ForgetPasswordScreenState extends State<ForgetPasswordScreen> {
|
||||
showSuccessToast('Код на почту успешно отправлен');
|
||||
}
|
||||
if (state is ResetPasswordStateCodeSendError) {
|
||||
showErrorToast('Ошибка отправки кода. Проверьте правильность ввёдной почты');
|
||||
showErrorToast(context.read<ResetPasswordCubit>().errorMessage ?? 'Ошибка отправки кода. Проверьте правильность ввёдной почты');
|
||||
}
|
||||
if (state is ResetPasswordStateResetPasswordError) {
|
||||
showErrorToast('Ошибка смены пароля. Проверьте правильность ввёднного кода и совпадение пароля');
|
||||
showErrorToast(context.read<ResetPasswordCubit>().errorMessage ?? 'Ошибка смены пароля. Проверьте правильность ввёднного кода и совпадение пароля');
|
||||
}
|
||||
if (state is ResetPasswordStateResetPassowrdSuccess) {
|
||||
GoRouter.of(context).pop();
|
||||
|
||||
@@ -7,6 +7,41 @@ class ResetPasswordRepository {
|
||||
required this.resetPasswordService,
|
||||
});
|
||||
|
||||
String? _lastError;
|
||||
|
||||
String? get lastError => _lastError;
|
||||
|
||||
void clearError() {
|
||||
_lastError = null;
|
||||
}
|
||||
|
||||
void _readError(dynamic data) {
|
||||
_lastError = null;
|
||||
if (data is! Map) {
|
||||
return;
|
||||
}
|
||||
|
||||
final errors = data['errors'];
|
||||
if (errors is Map) {
|
||||
final passwordErrors = errors['password'];
|
||||
if (passwordErrors is List && passwordErrors.isNotEmpty) {
|
||||
_lastError = passwordErrors.join('\n');
|
||||
return;
|
||||
}
|
||||
for (final value in errors.values) {
|
||||
if (value is List && value.isNotEmpty) {
|
||||
_lastError = value.join('\n');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final message = data['message'];
|
||||
if (message is String) {
|
||||
_lastError = message;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> sendEmailCodeForPasswordChange(String email) async {
|
||||
final response = await resetPasswordService.sendEmailCodeForPasswordChange(
|
||||
data: {
|
||||
@@ -15,8 +50,10 @@ class ResetPasswordRepository {
|
||||
);
|
||||
int statusCode = response.response.statusCode ?? 0;
|
||||
if (statusCode >= 200 && statusCode < 300) {
|
||||
_lastError = null;
|
||||
return true;
|
||||
} else {
|
||||
_readError(response.response.data);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -38,8 +75,10 @@ class ResetPasswordRepository {
|
||||
);
|
||||
int statusCode = response.response.statusCode ?? 0;
|
||||
if (statusCode >= 200 && statusCode < 300) {
|
||||
_lastError = null;
|
||||
return true;
|
||||
} else {
|
||||
_readError(response.response.data);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,9 @@ class _CredentialsScreenState extends State<CredentialsScreen> {
|
||||
textInputAction: TextInputAction.next,
|
||||
onChanged: (newValue) {
|
||||
final registrationCubit = context.read<RegistrationCubit>();
|
||||
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(email: newValue));
|
||||
registrationCubit.updateSheet(
|
||||
registrationCubit.state.sheet.copyWith(email: newValue),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
@@ -71,15 +73,24 @@ class _CredentialsScreenState extends State<CredentialsScreen> {
|
||||
});
|
||||
},
|
||||
icon: Icon(
|
||||
hidePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||
hidePassword
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
onChanged: (newValue) {
|
||||
final registrationCubit = context.read<RegistrationCubit>();
|
||||
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(password: newValue));
|
||||
registrationCubit.updateSheet(
|
||||
registrationCubit.state.sheet.copyWith(password: newValue),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
s.password_hint,
|
||||
style: const TextStyle(fontSize: 12, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(s.password_confirmation),
|
||||
const SizedBox(height: 4),
|
||||
@@ -95,13 +106,19 @@ class _CredentialsScreenState extends State<CredentialsScreen> {
|
||||
});
|
||||
},
|
||||
icon: Icon(
|
||||
hidePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||
hidePassword
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
onChanged: (newValue) {
|
||||
final registrationCubit = context.read<RegistrationCubit>();
|
||||
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(passwordConfirmation: newValue));
|
||||
registrationCubit.updateSheet(
|
||||
registrationCubit.state.sheet.copyWith(
|
||||
passwordConfirmation: newValue,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
@@ -353,7 +353,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
|
||||
errors.add(s.email_empty);
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
if (password.length < 8) {
|
||||
errors.add(s.password_short);
|
||||
}
|
||||
|
||||
|
||||
@@ -272,6 +272,12 @@ class RegistrationCubitV2 extends Cubit<RegistrationStateV2> {
|
||||
}
|
||||
}
|
||||
}
|
||||
final passwordErrors = errors?['password'] as List<dynamic>?;
|
||||
if (passwordErrors != null && passwordErrors.isNotEmpty) {
|
||||
for (var error in passwordErrors) {
|
||||
allErrors.add(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем все ошибки для отображения в диалоге
|
||||
if (allErrors.isNotEmpty) {
|
||||
|
||||
@@ -86,18 +86,21 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
static String m26(planName) =>
|
||||
"Завтра начнется прохождение плана «${planName}»";
|
||||
|
||||
static String m27(name, planName) =>
|
||||
"Пользователь ${name} отменил подписку на план «${planName}»";
|
||||
static String m27(seconds) =>
|
||||
"Too many login attempts. Try again in ${seconds} sec.";
|
||||
|
||||
static String m28(name, planName) =>
|
||||
"Пользователь ${name} оплатил план «${planName}»";
|
||||
"Пользователь ${name} отменил подписку на план «${planName}»";
|
||||
|
||||
static String m29(name, planName) =>
|
||||
"Пользователь ${name} оплатил план «${planName}»";
|
||||
|
||||
static String m30(name, planName) =>
|
||||
"Пользователь ${name} подписался на план «${planName}»";
|
||||
|
||||
static String m30(percent) => "Downloading… ${percent}%";
|
||||
static String m31(percent) => "Downloading… ${percent}%";
|
||||
|
||||
static String m31(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
static String m32(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
@@ -838,8 +841,11 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"password_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"Пароль обязателен для заполнения",
|
||||
),
|
||||
"password_hint": MessageLookupByLibrary.simpleMessage(
|
||||
"At least 8 characters, avoid common passwords",
|
||||
),
|
||||
"password_short": MessageLookupByLibrary.simpleMessage(
|
||||
"В пароле должно быть минимум 6 символов",
|
||||
"В пароле должно быть минимум 8 символов",
|
||||
),
|
||||
"pay": MessageLookupByLibrary.simpleMessage("Оплатить"),
|
||||
"pay_by_qr_code": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -1084,6 +1090,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"to_order": MessageLookupByLibrary.simpleMessage("Заказать"),
|
||||
"tommorowPlanWithUserWillStart": m25,
|
||||
"tomorrowYourPlanWillStart": m26,
|
||||
"too_many_login_attempts": m27,
|
||||
"too_many_login_attempts_no_retry": MessageLookupByLibrary.simpleMessage(
|
||||
"Too many login attempts. Please try again later.",
|
||||
),
|
||||
"try_again": MessageLookupByLibrary.simpleMessage("Попробовать снова"),
|
||||
"try_again_2": MessageLookupByLibrary.simpleMessage("Попробуйте ещё раз"),
|
||||
"typeAmoutOfReturn": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -1117,7 +1127,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Верхние показатели давления:",
|
||||
),
|
||||
"upper": MessageLookupByLibrary.simpleMessage("Верхнее"),
|
||||
"userCanceldThePlanSubscription": m27,
|
||||
"userCanceldThePlanSubscription": m28,
|
||||
"userConfirmedPlanCompletion": MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана. В ближайшее время Вы получите",
|
||||
),
|
||||
@@ -1125,8 +1135,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана.",
|
||||
),
|
||||
"userPaidThePlan": m28,
|
||||
"userSubscribedToPlan": m29,
|
||||
"userPaidThePlan": m29,
|
||||
"userSubscribedToPlan": m30,
|
||||
"user_authorization": MessageLookupByLibrary.simpleMessage(
|
||||
"Аутентификация",
|
||||
),
|
||||
@@ -1213,7 +1223,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage(
|
||||
"Downloading…",
|
||||
),
|
||||
"video_call_recordings_downloading_percent": m30,
|
||||
"video_call_recordings_downloading_percent": m31,
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"No video consultations yet",
|
||||
),
|
||||
@@ -1307,7 +1317,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"youCanComplain": MessageLookupByLibrary.simpleMessage(
|
||||
"Если вас что-то не устроило, вы можете подать жалобу",
|
||||
),
|
||||
"youCanceledSubscriptionToPlan": m31,
|
||||
"youCanceledSubscriptionToPlan": m32,
|
||||
"youShureYouWantToCancelOrder": MessageLookupByLibrary.simpleMessage(
|
||||
"Вы уверены, что хотите отменить заказ?",
|
||||
),
|
||||
|
||||
@@ -71,7 +71,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
|
||||
static String m23(date) => "Старт: ${date}";
|
||||
|
||||
static String m30(percent) => "Скачивание… ${percent}%";
|
||||
static String m27(seconds) =>
|
||||
"Слишком много попыток входа. Повторите через ${seconds} сек.";
|
||||
|
||||
static String m31(percent) => "Скачивание… ${percent}%";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
@@ -485,8 +488,11 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"password_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"Пароль обязателен для заполнения",
|
||||
),
|
||||
"password_hint": MessageLookupByLibrary.simpleMessage(
|
||||
"Минимум 8 символов, не используйте распространённые пароли",
|
||||
),
|
||||
"password_short": MessageLookupByLibrary.simpleMessage(
|
||||
"В пароле должно быть минимум 6 символов",
|
||||
"В пароле должно быть минимум 8 символов",
|
||||
),
|
||||
"pay_by_qr_code": MessageLookupByLibrary.simpleMessage(
|
||||
"Оплатить по QR-коду",
|
||||
@@ -620,6 +626,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"three_options": MessageLookupByLibrary.simpleMessage("3 опции"),
|
||||
"toOffer": MessageLookupByLibrary.simpleMessage("Предложить"),
|
||||
"to_draft": MessageLookupByLibrary.simpleMessage("В черновик"),
|
||||
"too_many_login_attempts": m27,
|
||||
"too_many_login_attempts_no_retry": MessageLookupByLibrary.simpleMessage(
|
||||
"Слишком много попыток входа. Попробуйте позже.",
|
||||
),
|
||||
"unfavorite_foods": MessageLookupByLibrary.simpleMessage(
|
||||
"Нелюбимые продукты",
|
||||
),
|
||||
@@ -708,7 +718,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage(
|
||||
"Скачивание…",
|
||||
),
|
||||
"video_call_recordings_downloading_percent": m30,
|
||||
"video_call_recordings_downloading_percent": m31,
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"Пока нет видеоконсультаций",
|
||||
),
|
||||
|
||||
@@ -529,16 +529,46 @@ class S {
|
||||
);
|
||||
}
|
||||
|
||||
/// `В пароле должно быть минимум 6 символов`
|
||||
/// `В пароле должно быть минимум 8 символов`
|
||||
String get password_short {
|
||||
return Intl.message(
|
||||
'В пароле должно быть минимум 6 символов',
|
||||
'В пароле должно быть минимум 8 символов',
|
||||
name: 'password_short',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `At least 8 characters, avoid common passwords`
|
||||
String get password_hint {
|
||||
return Intl.message(
|
||||
'At least 8 characters, avoid common passwords',
|
||||
name: 'password_hint',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Too many login attempts. Try again in {seconds} sec.`
|
||||
String too_many_login_attempts(int seconds) {
|
||||
return Intl.message(
|
||||
'Too many login attempts. Try again in $seconds sec.',
|
||||
name: 'too_many_login_attempts',
|
||||
desc: '',
|
||||
args: [seconds],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Too many login attempts. Please try again later.`
|
||||
String get too_many_login_attempts_no_retry {
|
||||
return Intl.message(
|
||||
'Too many login attempts. Please try again later.',
|
||||
name: 'too_many_login_attempts_no_retry',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Имя пользователя обязательно для заполнения`
|
||||
String get name_empty {
|
||||
return Intl.message(
|
||||
|
||||
@@ -55,7 +55,17 @@
|
||||
"email_empty": "Необходимо ввести адрес электронной почты",
|
||||
"email_invalid": "Некорректный адрес электронной почты",
|
||||
"password_empty": "Пароль обязателен для заполнения",
|
||||
"password_short": "В пароле должно быть минимум 6 символов",
|
||||
"password_short": "В пароле должно быть минимум 8 символов",
|
||||
"password_hint": "At least 8 characters, avoid common passwords",
|
||||
"too_many_login_attempts": "Too many login attempts. Try again in {seconds} sec.",
|
||||
"@too_many_login_attempts": {
|
||||
"placeholders": {
|
||||
"seconds": {
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
"too_many_login_attempts_no_retry": "Too many login attempts. Please try again later.",
|
||||
"name_empty": "Имя пользователя обязательно для заполнения",
|
||||
"name_short": "В имени пользователя должно быть минимум 6 символов",
|
||||
"password_confirmation_mismatch": "Пароли не совпадают",
|
||||
|
||||
@@ -55,7 +55,17 @@
|
||||
"email_empty": "Необходимо ввести адрес электронной почты",
|
||||
"email_invalid": "Некорректный адрес электронной почты",
|
||||
"password_empty": "Пароль обязателен для заполнения",
|
||||
"password_short": "В пароле должно быть минимум 6 символов",
|
||||
"password_short": "В пароле должно быть минимум 8 символов",
|
||||
"password_hint": "Минимум 8 символов, не используйте распространённые пароли",
|
||||
"too_many_login_attempts": "Слишком много попыток входа. Повторите через {seconds} сек.",
|
||||
"@too_many_login_attempts": {
|
||||
"placeholders": {
|
||||
"seconds": {
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
"too_many_login_attempts_no_retry": "Слишком много попыток входа. Попробуйте позже.",
|
||||
"name_empty": "Имя пользователя обязательно для заполнения",
|
||||
"name_short": "В имени пользователя должно быть минимум 6 символов",
|
||||
"password_confirmation_mismatch": "Пароли не совпадают",
|
||||
|
||||
Reference in New Issue
Block a user