feat: 落地登录纵切——网络层、认证会话与登录/注册/Splash 三页(ADR-003/ADR-004)
- 新增 lib/core/network/:ApiClient(dio 封装,错误信封→类型化异常,base URL 经 --dart-define=PATBOND_API_BASE_URL 注入)、AuthInterceptor(Bearer + 设备标识)、TokenRefresher(单飞刷新,401/40101 重放一次,仅 40102/再 401 清会话) - 新增 lib/features/auth/:SessionManager(token 只进 flutter_secure_storage)、AuthRepository(login/register/refresh/logout/me,注册带 Idempotency-Key)、Splash(500ms 最短停留/5s 超时/错误态重试+改用账号登录)、登录页与注册页(照 12 号组装稿,错误三层映射,预留区不渲染) - App 根组件改为认证状态机驱动(Splash↔登录↔主壳 300ms fade);个人中心退出登录接入真实 logout - 顺带修复:FIX-1 促销卡渐变改 [primaryStrong, primary]、FIX-2 补 helperStyle: muted、README dart format 命令补 --output=none - 新增依赖:dio ^5.11.1、flutter_secure_storage ^11.0.0、uuid ^4.6.0 - 门禁:dart format(0 changed)/ flutter analyze(No issues)/ flutter test(30 passed,其中新增 23:TokenRefresher 5 + AuthRepository 10 + 登录页 4 + 注册页 4) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 统一页面切换:300ms 淡入淡出(12 号组装稿 §7 流程约束)。
|
||||
Route<T> fadePageRoute<T>(Widget page) {
|
||||
return PageRouteBuilder<T>(
|
||||
transitionDuration: const Duration(milliseconds: 300),
|
||||
reverseTransitionDuration: const Duration(milliseconds: 300),
|
||||
pageBuilder: (context, animation, secondaryAnimation) => page,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) {
|
||||
return FadeTransition(opacity: animation, child: child);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:patbond_flutter/core/network/api_envelope.dart';
|
||||
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||
import 'package:patbond_flutter/core/network/token_refresher.dart';
|
||||
import 'package:patbond_flutter/features/auth/session_manager.dart';
|
||||
|
||||
/// API 基地址:`--dart-define=PATBOND_API_BASE_URL=...` 注入,默认本机后端。
|
||||
const String patbondApiBaseUrl = String.fromEnvironment(
|
||||
'PATBOND_API_BASE_URL',
|
||||
defaultValue: 'http://127.0.0.1:8081',
|
||||
);
|
||||
|
||||
/// 构建全局共用的 Dio 实例。
|
||||
///
|
||||
/// `validateStatus` 放行所有状态码:错误信封由 [ApiClient] 统一解析成
|
||||
/// 类型化异常,不依赖 dio 的 4xx/5xx 抛错路径。
|
||||
Dio buildPatbondDio({required SessionManager session, String? baseUrl}) {
|
||||
final dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: baseUrl ?? patbondApiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
sendTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 10),
|
||||
contentType: Headers.jsonContentType,
|
||||
validateStatus: (_) => true,
|
||||
),
|
||||
);
|
||||
dio.interceptors.add(AuthInterceptor(session));
|
||||
return dio;
|
||||
}
|
||||
|
||||
/// 鉴权拦截器:对标记 [ApiClient.requiresAuthExtra] 的请求附加
|
||||
/// `Authorization: Bearer`,并统一携带设备标识。
|
||||
class AuthInterceptor extends Interceptor {
|
||||
AuthInterceptor(this._session);
|
||||
|
||||
final SessionManager _session;
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
final deviceId = _session.deviceId;
|
||||
if (deviceId != null) {
|
||||
options.headers['X-Device-Id'] = deviceId;
|
||||
}
|
||||
if (options.extra[ApiClient.requiresAuthExtra] == true) {
|
||||
final token = _session.accessToken;
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
}
|
||||
handler.next(options);
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP 客户端封装:错误信封 → 类型化异常,401/40101 → 刷新后重放一次。
|
||||
class ApiClient {
|
||||
ApiClient({
|
||||
required this._dio,
|
||||
required this._session,
|
||||
required this._refresher,
|
||||
});
|
||||
|
||||
/// RequestOptions.extra 标记:该请求需要 Bearer 鉴权。
|
||||
static const requiresAuthExtra = 'patbond.requiresAuth';
|
||||
|
||||
final Dio _dio;
|
||||
final SessionManager _session;
|
||||
final TokenRefresher _refresher;
|
||||
|
||||
/// 发起请求并返回信封中的 `data`。
|
||||
///
|
||||
/// 鉴权请求遇 HTTP 401 或 code 40101 时:经单飞刷新后原样重放一次;
|
||||
/// 重放仍失败则清会话并抛 [SessionExpiredException]。
|
||||
Future<Object?> request(
|
||||
String path, {
|
||||
String method = 'POST',
|
||||
Object? body,
|
||||
Map<String, Object?>? headers,
|
||||
bool requiresAuth = false,
|
||||
}) async {
|
||||
var response = await _send(
|
||||
path,
|
||||
method: method,
|
||||
body: body,
|
||||
headers: headers,
|
||||
requiresAuth: requiresAuth,
|
||||
);
|
||||
|
||||
if (requiresAuth && _isAuthFailure(response)) {
|
||||
await _refresher.refresh();
|
||||
response = await _send(
|
||||
path,
|
||||
method: method,
|
||||
body: body,
|
||||
headers: headers,
|
||||
requiresAuth: requiresAuth,
|
||||
);
|
||||
if (_isAuthFailure(response)) {
|
||||
await _session.clearSession();
|
||||
throw const SessionExpiredException('刷新后重放仍未通过鉴权');
|
||||
}
|
||||
}
|
||||
|
||||
return _unwrap(response);
|
||||
}
|
||||
|
||||
Future<Response<Object?>> _send(
|
||||
String path, {
|
||||
required String method,
|
||||
required bool requiresAuth,
|
||||
Object? body,
|
||||
Map<String, Object?>? headers,
|
||||
}) async {
|
||||
try {
|
||||
return await _dio.request<Object?>(
|
||||
path,
|
||||
data: body,
|
||||
options: Options(
|
||||
method: method,
|
||||
headers: headers,
|
||||
extra: {requiresAuthExtra: requiresAuth},
|
||||
),
|
||||
);
|
||||
} on DioException catch (error) {
|
||||
throw ApiNetworkException('请求失败:${error.type.name}');
|
||||
}
|
||||
}
|
||||
|
||||
bool _isAuthFailure(Response<Object?> response) {
|
||||
if (response.statusCode == 401) return true;
|
||||
return ApiEnvelope.tryParse(response.data)?.code ==
|
||||
ApiCodes.accessTokenInvalid;
|
||||
}
|
||||
|
||||
Object? _unwrap(Response<Object?> response) {
|
||||
final status = response.statusCode ?? 0;
|
||||
if (status == 429) {
|
||||
throw const ApiRateLimitException();
|
||||
}
|
||||
final envelope = ApiEnvelope.tryParse(response.data);
|
||||
if (envelope == null || status >= 500) {
|
||||
throw ApiNetworkException('响应异常:HTTP $status');
|
||||
}
|
||||
if (envelope.code == ApiCodes.ok) {
|
||||
return envelope.data;
|
||||
}
|
||||
throw ApiBusinessException(code: envelope.code, message: envelope.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/// 服务端统一响应信封 `{code, message, data}` 的解析结果。
|
||||
class ApiEnvelope {
|
||||
const ApiEnvelope({required this.code, required this.message, this.data});
|
||||
|
||||
final int code;
|
||||
final String message;
|
||||
final Object? data;
|
||||
|
||||
/// 从响应体解析信封;结构不符(非 JSON 对象 / 无 int code)返回 null。
|
||||
static ApiEnvelope? tryParse(Object? body) {
|
||||
if (body is! Map) return null;
|
||||
final code = body['code'];
|
||||
if (code is! int) return null;
|
||||
return ApiEnvelope(
|
||||
code: code,
|
||||
message: body['message'] is String ? body['message'] as String : '',
|
||||
data: body['data'],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/// 服务端错误信封 `{code, message, data}` 的业务码常量(接口契约冻结稿)。
|
||||
abstract final class ApiCodes {
|
||||
static const ok = 0;
|
||||
|
||||
/// 参数错误。
|
||||
static const paramError = 40000;
|
||||
|
||||
/// 用户名或密码错误。
|
||||
static const badCredentials = 40100;
|
||||
|
||||
/// access token 无效或过期。
|
||||
static const accessTokenInvalid = 40101;
|
||||
|
||||
/// refresh token 已失效。
|
||||
static const refreshTokenInvalid = 40102;
|
||||
|
||||
/// 用户名重复。
|
||||
static const usernameTaken = 40900;
|
||||
|
||||
/// 手机号重复。
|
||||
static const phoneTaken = 40901;
|
||||
}
|
||||
|
||||
/// API 调用的类型化异常。页面按类型映射为三层错误呈现
|
||||
/// (字段级 / 表单横幅 / SnackBar,见 12 号组装稿 §4),
|
||||
/// 服务端原始 message 一律不直接透出给用户。
|
||||
sealed class ApiException implements Exception {
|
||||
const ApiException(this.message);
|
||||
|
||||
/// 服务端返回的原始 message(仅用于日志排查,不上屏)。
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message';
|
||||
}
|
||||
|
||||
/// 系统错误:超时、断网、5xx、响应无法解析。归瞬态层(SnackBar + 重试)。
|
||||
final class ApiNetworkException extends ApiException {
|
||||
const ApiNetworkException([super.message = '网络或服务不可用']);
|
||||
}
|
||||
|
||||
/// 业务错误:错误信封 code != 0(40000/40100/40900/40901 等)。
|
||||
final class ApiBusinessException extends ApiException {
|
||||
const ApiBusinessException({required this.code, required String message})
|
||||
: super(message);
|
||||
|
||||
final int code;
|
||||
}
|
||||
|
||||
/// 限流(HTTP 429):映射为横幅「尝试次数过多,请稍后再试」。
|
||||
final class ApiRateLimitException extends ApiException {
|
||||
const ApiRateLimitException([super.message = '请求过于频繁']);
|
||||
}
|
||||
|
||||
/// 会话已失效:refresh token 失效(40102)或刷新重放后仍 401。
|
||||
/// 抛出前本地会话已被清除,应用会自动回到登录页。
|
||||
final class SessionExpiredException extends ApiException {
|
||||
const SessionExpiredException([super.message = '会话已失效']);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:patbond_flutter/core/network/api_envelope.dart';
|
||||
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||
import 'package:patbond_flutter/features/auth/auth_models.dart';
|
||||
import 'package:patbond_flutter/features/auth/session_manager.dart';
|
||||
|
||||
/// 单飞(single-flight)token 刷新器。
|
||||
///
|
||||
/// 并发触发的多个 401/40101 只发出一次 `POST /auth/refresh`,
|
||||
/// 其余调用共享同一个进行中的刷新结果。
|
||||
///
|
||||
/// 清会话纪律(12 号组装稿 §7):只有服务端明确判定 refresh 失效
|
||||
/// (40102 或 HTTP 401)才清除本地会话;网络失败、5xx 一律保留 token。
|
||||
class TokenRefresher {
|
||||
TokenRefresher({required this._dio, required this._session});
|
||||
|
||||
final Dio _dio;
|
||||
final SessionManager _session;
|
||||
|
||||
Future<void>? _inflight;
|
||||
|
||||
/// 刷新并轮换 token。成功后新 token 已写入 [SessionManager]。
|
||||
///
|
||||
/// 抛出 [SessionExpiredException](会话已被清除)或
|
||||
/// [ApiNetworkException](token 保留,可重试)。
|
||||
Future<void> refresh() {
|
||||
return _inflight ??= _doRefresh().whenComplete(() => _inflight = null);
|
||||
}
|
||||
|
||||
Future<void> _doRefresh() async {
|
||||
await _session.loadFromStorage();
|
||||
final refreshToken = _session.refreshToken;
|
||||
if (refreshToken == null) {
|
||||
await _session.clearSession();
|
||||
throw const SessionExpiredException('本地无 refresh token');
|
||||
}
|
||||
|
||||
final Response<Object?> response;
|
||||
try {
|
||||
response = await _dio.post<Object?>(
|
||||
'/api/v1/auth/refresh',
|
||||
data: {'refreshToken': refreshToken},
|
||||
);
|
||||
} on DioException catch (error) {
|
||||
throw ApiNetworkException('刷新请求失败:${error.type.name}');
|
||||
}
|
||||
|
||||
final envelope = ApiEnvelope.tryParse(response.data);
|
||||
if (response.statusCode == 401 ||
|
||||
envelope?.code == ApiCodes.refreshTokenInvalid) {
|
||||
await _session.clearSession();
|
||||
throw const SessionExpiredException('refresh token 已失效');
|
||||
}
|
||||
if (envelope != null &&
|
||||
envelope.code == ApiCodes.ok &&
|
||||
envelope.data is Map<String, dynamic>) {
|
||||
await _session.updateTokens(
|
||||
AuthTokens.fromJson(envelope.data! as Map<String, dynamic>),
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw ApiNetworkException(
|
||||
'刷新响应异常:HTTP ${response.statusCode},code ${envelope?.code}',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,7 @@ ThemeData buildAppTheme() {
|
||||
borderSide: BorderSide(color: AppColors.error, width: 1.5),
|
||||
),
|
||||
errorStyle: TextStyle(color: AppColors.error, fontSize: 12),
|
||||
helperStyle: TextStyle(color: AppColors.muted, fontSize: 12),
|
||||
),
|
||||
snackBarTheme: const SnackBarThemeData(
|
||||
behavior: SnackBarBehavior.floating,
|
||||
|
||||
Reference in New Issue
Block a user