feat(mobile): login, password change and logout screens
P3 Task 3 移动端(对接 Task 2 api client + 本任务新增的后端契约): - 登录页实装:账号/密码表单(空值客户端校验)→ api.login(会话自动 持久化)→ pushReplacement /home;错误码本地化(AUTH_INVALID_ CREDENTIALS / AUTH_RATE_LIMITED(含稍后再试文案)/ 网络 / 校验); 提交加载态防重复提交。 - 修改密码页(设置页入口):当前/新/确认三字段,客户端校验(≥8 位、 两次一致)→ api.changePassword → toast + pop;成功后本地会话不变 (服务端保留当前会话);旧密码错误(401 AUTH_INVALID_CREDENTIALS) 显示「当前密码错误」且不触发 401 驱逐。 - 退出登录:设置页按钮 → api.logout 尽力而为 → 清会话 → 清栈回 /login;App 壳 initState 注册 onUnauthorized(业务 401 → 清栈 /login), 根 navigatorKey 接线;password-change 的 401 豁免会话驱逐(拦截器 豁免集合与令牌附加分离)。 - l10n:新增 16 组 zh/en 文案;错误码 → 文案解析扩展 (core/error_l10n.dart,errorCode→AppLocalizations)。 - 测试:ApiClient.changePassword 单测 ×2(Bearer+请求体;旧密码 401 不驱逐);widget 测试 ×12(登录 5:空值/成功跳转/凭据错误/限速文案/ 加载禁用;改密 4:过短/不一致/旧密码错误文案+会话保留/成功 toast+pop 且令牌不变;设置 2:改密入口跳转/登出清会话回登录;App 壳 1:401 清栈回 /login)。flutter analyze 0 issue;flutter test 81/81。 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,23 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../pages/home_page.dart';
|
||||
import '../pages/login_page.dart';
|
||||
import '../pages/password_change_page.dart';
|
||||
import 'locale_controller.dart';
|
||||
import 'theme.dart';
|
||||
|
||||
/// App 根组件:主题 + l10n 委托 + 基线路由。
|
||||
/// 根导航键:[ApiClient.onUnauthorized](非 UI 上下文触发)跳转 /login 用。
|
||||
final GlobalKey<NavigatorState> rootNavigatorKey =
|
||||
GlobalKey<NavigatorState>();
|
||||
|
||||
/// App 根组件:主题 + l10n 委托 + 命名路由 + 401 驱逐接线。
|
||||
///
|
||||
/// 基线路由为命名路由(/login → /home);Task 3+ 随页面增长再评估
|
||||
/// 是否迁移 go_router,当前保持零额外依赖。
|
||||
class PhotoLiveApp extends ConsumerWidget {
|
||||
/// 基线路由为命名路由(/login → /home → /password-change);随页面增长再
|
||||
/// 评估是否迁移 go_router,当前保持零额外依赖。
|
||||
/// initState 注册 [ApiClient.onUnauthorized]:任意业务端点 401(会话过期)
|
||||
/// 即清空栈回到 /login(登录/修改密码端点自身的 401 不触发,见 ApiClient)。
|
||||
class PhotoLiveApp extends ConsumerStatefulWidget {
|
||||
const PhotoLiveApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
ConsumerState<PhotoLiveApp> createState() => _PhotoLiveAppState();
|
||||
}
|
||||
|
||||
class _PhotoLiveAppState extends ConsumerState<PhotoLiveApp> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
ref.read(apiClientProvider).onUnauthorized = () {
|
||||
rootNavigatorKey.currentState
|
||||
?.pushNamedAndRemoveUntil('/login', (route) => false);
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final locale = ref.watch(localeSettingsProvider);
|
||||
return MaterialApp(
|
||||
navigatorKey: rootNavigatorKey,
|
||||
onGenerateTitle: (context) => AppLocalizations.of(context).appName,
|
||||
theme: AppTheme.light,
|
||||
darkTheme: AppTheme.dark,
|
||||
@@ -27,6 +50,7 @@ class PhotoLiveApp extends ConsumerWidget {
|
||||
routes: {
|
||||
'/login': (context) => const LoginPage(),
|
||||
'/home': (context) => const HomePage(),
|
||||
'/password-change': (context) => const PasswordChangePage(),
|
||||
},
|
||||
home: const LoginPage(),
|
||||
);
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
/// - Bearer 注入:请求拦截器从 [SessionStore] 读取令牌(登录端点豁免)。
|
||||
/// - 401 处理:清空会话并触发 [onUnauthorized](App 壳注册的监听回调,
|
||||
/// 负责跳转 /login);并发的后续 401 只通知一次,直至新会话写入。
|
||||
/// 登录端点自身的 401(凭据错误)不触发会话驱逐。
|
||||
/// 登录端点自身的 401(凭据错误)与修改密码端点的 401(旧密码错误)
|
||||
/// 不是会话过期语义,不触发会话驱逐。
|
||||
/// - 错误归一:HTTP 错误体 `{code, message, requestId}` 与网络层失败一律
|
||||
/// 抛 [AppException](码表见 [ErrorCodes];l10n 文案解析留在 UI 层)。
|
||||
library;
|
||||
@@ -64,10 +65,15 @@ class ApiClient {
|
||||
|
||||
void close({bool force = false}) => _dio.close(force: force);
|
||||
|
||||
/// 登录端点:401 = 凭据错误而非会话过期,不驱逐会话、不附加令牌。
|
||||
static bool _isAuthExemptPath(String path) =>
|
||||
/// 登录端点:不附加令牌(未认证端点)。
|
||||
static bool _isLoginPath(String path) =>
|
||||
path.endsWith('/v1/auth/password');
|
||||
|
||||
/// 401 驱逐豁免:登录(凭据错误)与修改密码(旧密码错误)的 401 都不是
|
||||
/// 会话过期语义,不得清会话/触发跳登录;其余端点 401 一律驱逐。
|
||||
static bool _evictsSessionOn401(String path) =>
|
||||
!_isLoginPath(path) && !path.endsWith('/v1/auth/password-change');
|
||||
|
||||
// ── 拦截器 ──
|
||||
|
||||
Future<void> _attachSession(
|
||||
@@ -75,7 +81,7 @@ class ApiClient {
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
try {
|
||||
if (!_isAuthExemptPath(options.path)) {
|
||||
if (!_isLoginPath(options.path)) {
|
||||
final session = await _session.read();
|
||||
if (session != null &&
|
||||
session.token.isNotEmpty &&
|
||||
@@ -95,7 +101,7 @@ class ApiClient {
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
if (e.response?.statusCode == 401 &&
|
||||
!_isAuthExemptPath(e.requestOptions.path)) {
|
||||
_evictsSessionOn401(e.requestOptions.path)) {
|
||||
try {
|
||||
// 先同步置位去重标记再做异步清除:并发 401 下仅首个触发通知。
|
||||
final shouldNotify = !_unauthorizedNotified;
|
||||
@@ -256,6 +262,20 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// operationId `changePassword`(POST /auth/password-change → 204,
|
||||
/// P3 Task 3 契约增补)。
|
||||
///
|
||||
/// 服务端成功后撤销其他会话、**保留当前会话**——本地令牌继续有效,
|
||||
/// 无需重登录。旧密码错误 → 401 AUTH_INVALID_CREDENTIALS(不驱逐会话,
|
||||
/// 见 [_evictsSessionOn401])。
|
||||
Future<void> changePassword(String oldPassword, String newPassword) =>
|
||||
_send(
|
||||
() => _dio.post<void>(
|
||||
'/v1/auth/password-change',
|
||||
data: {'oldPassword': oldPassword, 'newPassword': newPassword},
|
||||
),
|
||||
);
|
||||
|
||||
// ── albums / members / categories / admin ──
|
||||
|
||||
/// operationId `listAlbums`(GET /albums,游标分页)。
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/// 错误码 → 本地化文案解析(P3 计划 Task 3)。
|
||||
///
|
||||
/// 契约约定(openapi.yaml info.description):客户端按稳定 `code` 映射
|
||||
/// 多语言文案,`message` 仅供诊断。本扩展覆盖 UI 常见展示的契约码与客户端
|
||||
/// 伪码([ErrorCodes]);未映射的码回退通用文案(errorGeneric)。
|
||||
///
|
||||
/// 页面可对特定码做更贴切的覆写后再回退到本方法(例:修改密码页把
|
||||
/// AUTH_INVALID_CREDENTIALS 显示为「当前密码错误」而非「账号或密码错误」)。
|
||||
library;
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
import 'app_exception.dart';
|
||||
import 'error_codes.dart';
|
||||
|
||||
extension AppLocalizationsErrorX on AppLocalizations {
|
||||
/// 按稳定错误码解析展示文案。
|
||||
String messageForErrorCode(String code) {
|
||||
switch (code) {
|
||||
case ErrorCodes.authInvalidCredentials:
|
||||
return errorAuthInvalidCredentials;
|
||||
case ErrorCodes.authRateLimited:
|
||||
case ErrorCodes.rateLimited:
|
||||
return errorAuthRateLimited;
|
||||
case ErrorCodes.authTokenExpired:
|
||||
case ErrorCodes.syncAuthFailed: // App 侧实际不可达,防御性同文案。
|
||||
return errorAuthTokenExpired;
|
||||
case ErrorCodes.validationFailed:
|
||||
return errorValidation;
|
||||
case ErrorCodes.networkError:
|
||||
return errorNetwork;
|
||||
case ErrorCodes.networkTimeout:
|
||||
return errorNetworkTimeout;
|
||||
case ErrorCodes.internalError:
|
||||
return errorInternal;
|
||||
default:
|
||||
return errorGeneric;
|
||||
}
|
||||
}
|
||||
|
||||
/// [AppException] 展示文案(按错误码解析)。
|
||||
String messageForError(AppException error) => messageForErrorCode(error.code);
|
||||
}
|
||||
@@ -20,5 +20,21 @@
|
||||
"homeTabAlbums": "Albums",
|
||||
"homeTabQueue": "Queue",
|
||||
"homeTabSettings": "Settings",
|
||||
"loginHint": "Sign in with your staff account"
|
||||
"loginHint": "Sign in with your staff account",
|
||||
"fieldRequired": "This field is required",
|
||||
"passwordChangeTitle": "Change password",
|
||||
"currentPassword": "Current password",
|
||||
"newPassword": "New password",
|
||||
"confirmNewPassword": "Confirm new password",
|
||||
"passwordMinLength": "New password must be at least 8 characters",
|
||||
"passwordMismatch": "New passwords do not match",
|
||||
"passwordChangeSuccess": "Password changed",
|
||||
"errorAuthInvalidCredentials": "Incorrect account or password",
|
||||
"errorOldPasswordIncorrect": "Current password is incorrect",
|
||||
"errorAuthRateLimited": "Too many attempts. Please try again later",
|
||||
"errorAuthTokenExpired": "Session expired. Please sign in again",
|
||||
"errorValidation": "Invalid input. Please check and retry",
|
||||
"errorNetwork": "Network error. Check your connection and retry",
|
||||
"errorNetworkTimeout": "Network timed out. Please retry",
|
||||
"errorInternal": "Service temporarily unavailable. Please retry later"
|
||||
}
|
||||
|
||||
@@ -223,6 +223,102 @@ abstract class AppLocalizations {
|
||||
/// In zh, this message translates to:
|
||||
/// **'使用工作人员账号登录'**
|
||||
String get loginHint;
|
||||
|
||||
/// No description provided for @fieldRequired.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'此项为必填项'**
|
||||
String get fieldRequired;
|
||||
|
||||
/// No description provided for @passwordChangeTitle.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'修改密码'**
|
||||
String get passwordChangeTitle;
|
||||
|
||||
/// No description provided for @currentPassword.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'当前密码'**
|
||||
String get currentPassword;
|
||||
|
||||
/// No description provided for @newPassword.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'新密码'**
|
||||
String get newPassword;
|
||||
|
||||
/// No description provided for @confirmNewPassword.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'确认新密码'**
|
||||
String get confirmNewPassword;
|
||||
|
||||
/// No description provided for @passwordMinLength.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'新密码至少需要 8 个字符'**
|
||||
String get passwordMinLength;
|
||||
|
||||
/// No description provided for @passwordMismatch.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'两次输入的新密码不一致'**
|
||||
String get passwordMismatch;
|
||||
|
||||
/// No description provided for @passwordChangeSuccess.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'密码已修改'**
|
||||
String get passwordChangeSuccess;
|
||||
|
||||
/// No description provided for @errorAuthInvalidCredentials.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'账号或密码错误'**
|
||||
String get errorAuthInvalidCredentials;
|
||||
|
||||
/// No description provided for @errorOldPasswordIncorrect.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'当前密码错误'**
|
||||
String get errorOldPasswordIncorrect;
|
||||
|
||||
/// No description provided for @errorAuthRateLimited.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'尝试次数过多,请稍后再试'**
|
||||
String get errorAuthRateLimited;
|
||||
|
||||
/// No description provided for @errorAuthTokenExpired.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'会话已过期,请重新登录'**
|
||||
String get errorAuthTokenExpired;
|
||||
|
||||
/// No description provided for @errorValidation.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'输入有误,请检查后重试'**
|
||||
String get errorValidation;
|
||||
|
||||
/// No description provided for @errorNetwork.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'网络连接失败,请检查网络后重试'**
|
||||
String get errorNetwork;
|
||||
|
||||
/// No description provided for @errorNetworkTimeout.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'网络超时,请重试'**
|
||||
String get errorNetworkTimeout;
|
||||
|
||||
/// No description provided for @errorInternal.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'服务暂时不可用,请稍后重试'**
|
||||
String get errorInternal;
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate
|
||||
|
||||
@@ -70,4 +70,54 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
|
||||
@override
|
||||
String get loginHint => 'Sign in with your staff account';
|
||||
|
||||
@override
|
||||
String get fieldRequired => 'This field is required';
|
||||
|
||||
@override
|
||||
String get passwordChangeTitle => 'Change password';
|
||||
|
||||
@override
|
||||
String get currentPassword => 'Current password';
|
||||
|
||||
@override
|
||||
String get newPassword => 'New password';
|
||||
|
||||
@override
|
||||
String get confirmNewPassword => 'Confirm new password';
|
||||
|
||||
@override
|
||||
String get passwordMinLength => 'New password must be at least 8 characters';
|
||||
|
||||
@override
|
||||
String get passwordMismatch => 'New passwords do not match';
|
||||
|
||||
@override
|
||||
String get passwordChangeSuccess => 'Password changed';
|
||||
|
||||
@override
|
||||
String get errorAuthInvalidCredentials => 'Incorrect account or password';
|
||||
|
||||
@override
|
||||
String get errorOldPasswordIncorrect => 'Current password is incorrect';
|
||||
|
||||
@override
|
||||
String get errorAuthRateLimited =>
|
||||
'Too many attempts. Please try again later';
|
||||
|
||||
@override
|
||||
String get errorAuthTokenExpired => 'Session expired. Please sign in again';
|
||||
|
||||
@override
|
||||
String get errorValidation => 'Invalid input. Please check and retry';
|
||||
|
||||
@override
|
||||
String get errorNetwork => 'Network error. Check your connection and retry';
|
||||
|
||||
@override
|
||||
String get errorNetworkTimeout => 'Network timed out. Please retry';
|
||||
|
||||
@override
|
||||
String get errorInternal =>
|
||||
'Service temporarily unavailable. Please retry later';
|
||||
}
|
||||
|
||||
@@ -70,4 +70,52 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
|
||||
@override
|
||||
String get loginHint => '使用工作人员账号登录';
|
||||
|
||||
@override
|
||||
String get fieldRequired => '此项为必填项';
|
||||
|
||||
@override
|
||||
String get passwordChangeTitle => '修改密码';
|
||||
|
||||
@override
|
||||
String get currentPassword => '当前密码';
|
||||
|
||||
@override
|
||||
String get newPassword => '新密码';
|
||||
|
||||
@override
|
||||
String get confirmNewPassword => '确认新密码';
|
||||
|
||||
@override
|
||||
String get passwordMinLength => '新密码至少需要 8 个字符';
|
||||
|
||||
@override
|
||||
String get passwordMismatch => '两次输入的新密码不一致';
|
||||
|
||||
@override
|
||||
String get passwordChangeSuccess => '密码已修改';
|
||||
|
||||
@override
|
||||
String get errorAuthInvalidCredentials => '账号或密码错误';
|
||||
|
||||
@override
|
||||
String get errorOldPasswordIncorrect => '当前密码错误';
|
||||
|
||||
@override
|
||||
String get errorAuthRateLimited => '尝试次数过多,请稍后再试';
|
||||
|
||||
@override
|
||||
String get errorAuthTokenExpired => '会话已过期,请重新登录';
|
||||
|
||||
@override
|
||||
String get errorValidation => '输入有误,请检查后重试';
|
||||
|
||||
@override
|
||||
String get errorNetwork => '网络连接失败,请检查网络后重试';
|
||||
|
||||
@override
|
||||
String get errorNetworkTimeout => '网络超时,请重试';
|
||||
|
||||
@override
|
||||
String get errorInternal => '服务暂时不可用,请稍后重试';
|
||||
}
|
||||
|
||||
@@ -20,5 +20,21 @@
|
||||
"homeTabAlbums": "相册",
|
||||
"homeTabQueue": "队列",
|
||||
"homeTabSettings": "设置",
|
||||
"loginHint": "使用工作人员账号登录"
|
||||
"loginHint": "使用工作人员账号登录",
|
||||
"fieldRequired": "此项为必填项",
|
||||
"passwordChangeTitle": "修改密码",
|
||||
"currentPassword": "当前密码",
|
||||
"newPassword": "新密码",
|
||||
"confirmNewPassword": "确认新密码",
|
||||
"passwordMinLength": "新密码至少需要 8 个字符",
|
||||
"passwordMismatch": "两次输入的新密码不一致",
|
||||
"passwordChangeSuccess": "密码已修改",
|
||||
"errorAuthInvalidCredentials": "账号或密码错误",
|
||||
"errorOldPasswordIncorrect": "当前密码错误",
|
||||
"errorAuthRateLimited": "尝试次数过多,请稍后再试",
|
||||
"errorAuthTokenExpired": "会话已过期,请重新登录",
|
||||
"errorValidation": "输入有误,请检查后重试",
|
||||
"errorNetwork": "网络连接失败,请检查网络后重试",
|
||||
"errorNetworkTimeout": "网络超时,请重试",
|
||||
"errorInternal": "服务暂时不可用,请稍后重试"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// 主壳:底部导航(相册 / 队列 / 设置)。
|
||||
@@ -89,12 +91,19 @@ class QueueTab extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置(桩)。Task 10:App 内语言切换(zh / en / 跟随系统)持久化。
|
||||
class SettingsTab extends StatelessWidget {
|
||||
/// 设置页(P3 Task 3:修改密码入口 + 退出登录;Task 10 补语言切换持久化)。
|
||||
class SettingsTab extends ConsumerWidget {
|
||||
const SettingsTab({super.key});
|
||||
|
||||
Future<void> _logout(BuildContext context, WidgetRef ref) async {
|
||||
// api.logout 尽力而为(服务端撤销失败也照常本地清会话——客户端内已处理)。
|
||||
await ref.read(apiClientProvider).logout();
|
||||
if (!context.mounted) return;
|
||||
Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(l10n.settings)),
|
||||
@@ -105,6 +114,16 @@ class SettingsTab extends StatelessWidget {
|
||||
title: Text(l10n.language),
|
||||
subtitle: Text(l10n.localeFollowSystem),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.password_outlined),
|
||||
title: Text(l10n.passwordChangeTitle),
|
||||
onTap: () => Navigator.of(context).pushNamed('/password-change'),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.logout),
|
||||
title: Text(l10n.logout),
|
||||
onTap: () => _logout(context, ref),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,14 +1,65 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../core/app_exception.dart';
|
||||
import '../core/error_l10n.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// 登录页(桩)。
|
||||
/// 登录页(P3 计划 Task 3)。
|
||||
///
|
||||
/// Task 3 实现:真实登录、错误本地化(含 AUTH_RATE_LIMITED / 429 重试等待)、
|
||||
/// 会话持久化与退出登录。
|
||||
class LoginPage extends StatelessWidget {
|
||||
/// 账号/密码表单 → [ApiClient.login](会话由客户端自动持久化到
|
||||
/// SessionStore)→ 成功 pushReplacement /home;失败按错误码本地化提示
|
||||
/// (AUTH_RATE_LIMITED 文案自带「稍后再试」;网络/校验错误各有专属文案)。
|
||||
/// 提交期间按钮进入加载态防重复提交。
|
||||
class LoginPage extends ConsumerStatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginPage> createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends ConsumerState<LoginPage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _accountController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
bool _submitting = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_accountController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
setState(() => _submitting = true);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final navigator = Navigator.of(context);
|
||||
try {
|
||||
await ref.read(apiClientProvider).login(
|
||||
_accountController.text.trim(),
|
||||
_passwordController.text,
|
||||
);
|
||||
navigator.pushReplacementNamed('/home');
|
||||
} on AppException catch (error) {
|
||||
// 429(AUTH_RATE_LIMITED)等文案经错误码映射;登录页的
|
||||
// AUTH_INVALID_CREDENTIALS 即「账号或密码错误」。
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.messageForError(error))),
|
||||
);
|
||||
} on Object {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.errorGeneric)),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _submitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
@@ -19,40 +70,60 @@ class LoginPage extends StatelessWidget {
|
||||
constraints: const BoxConstraints(maxWidth: 420),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextField(
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.username,
|
||||
border: const OutlineInputBorder(),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _accountController,
|
||||
autofillHints: const [AutofillHints.username],
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.username,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) =>
|
||||
(value == null || value.trim().isEmpty)
|
||||
? l10n.fieldRequired
|
||||
: null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
obscureText: true,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.password,
|
||||
border: const OutlineInputBorder(),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
onFieldSubmitted: (_) => _submitting ? null : _submit(),
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.password,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) => (value == null || value.isEmpty)
|
||||
? l10n.fieldRequired
|
||||
: null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
// 桩:直接进入主壳;Task 3 接真实认证。
|
||||
onPressed: () =>
|
||||
Navigator.of(context).pushReplacementNamed('/home'),
|
||||
child: Text(l10n.login),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
l10n.loginHint,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _submitting ? null : _submit,
|
||||
child: _submitting
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(l10n.login),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
l10n.loginHint,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../core/app_exception.dart';
|
||||
import '../core/error_codes.dart';
|
||||
import '../core/error_l10n.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// 修改密码页(P3 计划 Task 3;入口在设置页)。
|
||||
///
|
||||
/// 当前/新/确认三字段;客户端校验(新密码 ≥8 位、两次一致)先行,
|
||||
/// 服务端 [ApiClient.changePassword] 成功后 204——当前会话被服务端保留,
|
||||
/// 无需重登录:toast 提示后直接 pop 回设置页。
|
||||
/// AUTH_INVALID_CREDENTIALS 在本页语义为「当前密码错误」(覆写通用映射)。
|
||||
class PasswordChangePage extends ConsumerStatefulWidget {
|
||||
const PasswordChangePage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<PasswordChangePage> createState() =>
|
||||
_PasswordChangePageState();
|
||||
}
|
||||
|
||||
class _PasswordChangePageState extends ConsumerState<PasswordChangePage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _oldController = TextEditingController();
|
||||
final _newController = TextEditingController();
|
||||
final _confirmController = TextEditingController();
|
||||
|
||||
bool _obscureAll = true;
|
||||
bool _submitting = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_oldController.dispose();
|
||||
_newController.dispose();
|
||||
_confirmController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
setState(() => _submitting = true);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final navigator = Navigator.of(context);
|
||||
try {
|
||||
await ref.read(apiClientProvider).changePassword(
|
||||
_oldController.text,
|
||||
_newController.text,
|
||||
);
|
||||
// 成功路径:先弹提示再 pop;pop 后 SnackBar 仍挂在根 messenger 上可见。
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.passwordChangeSuccess)),
|
||||
);
|
||||
navigator.pop();
|
||||
} on AppException catch (error) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
error.code == ErrorCodes.authInvalidCredentials
|
||||
? l10n.errorOldPasswordIncorrect
|
||||
: l10n.messageForError(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
} on Object {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.errorGeneric)),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _submitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(l10n.passwordChangeTitle)),
|
||||
body: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 420),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _oldController,
|
||||
obscureText: _obscureAll,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.currentPassword,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) => (value == null || value.isEmpty)
|
||||
? l10n.fieldRequired
|
||||
: null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _newController,
|
||||
obscureText: _obscureAll,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.newPassword,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return l10n.fieldRequired;
|
||||
}
|
||||
if (value.length < 8) return l10n.passwordMinLength;
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _confirmController,
|
||||
obscureText: _obscureAll,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
onFieldSubmitted: (_) => _submitting ? null : _submit(),
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.confirmNewPassword,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return l10n.fieldRequired;
|
||||
}
|
||||
if (value != _newController.text) {
|
||||
return l10n.passwordMismatch;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: IconButton(
|
||||
onPressed: () =>
|
||||
setState(() => _obscureAll = !_obscureAll),
|
||||
icon: Icon(
|
||||
_obscureAll
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: _submitting ? null : _submit,
|
||||
child: _submitting
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(l10n.passwordChangeTitle),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user