Files
pangolin/client/lib/state/auth_provider.dart
T
wangjia aee9ba7b72
ci-pangolin / Lint — shellcheck (push) Has been cancelled
ci-pangolin / OpenAPI Sync Check (push) Has been cancelled
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Has been cancelled
ci-pangolin / Flutter — analyze + test (push) Has been cancelled
feat(client): 登录体验 — 记住邮箱 + 密码显隐 + 7天免登陆
1. 记住邮箱:登录页预填上次邮箱(TokenStore.saveLastEmail,登录/注册成功时存,
   退出登录不清除)。
2. 密码显隐:登录/注册密码框加眼睛按钮切换明文(PangolinIcons.eye/eyeOff)。
3. 7天免登陆:RootFlow 改为响应 authProvider——启动时有有效会话直接进主界面;
   AuthNotifier.refresh() 在服务端拒绝(refresh 过期/超 7 天)时 logout 回登录页,
   网络错误则保留会话。会话恢复期间显示极简启动屏。

flutter analyze 0 error;114 tests passed。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 06:28:49 +08:00

89 lines
3.2 KiB
Dart

// auth_provider.dart — 认证状态(JWT 令牌生命周期)
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/api_config.dart';
import '../services/auth_api.dart';
import '../services/token_store.dart';
// ── 状态 ────────────────────────────────────────────────────────────
class AuthState {
const AuthState({this.accessToken, this.isLoading = false});
final String? accessToken;
final bool isLoading;
bool get isLoggedIn => accessToken != null && accessToken!.isNotEmpty;
AuthState copyWith({String? accessToken, bool? isLoading}) => AuthState(
accessToken: accessToken ?? this.accessToken,
isLoading: isLoading ?? this.isLoading,
);
}
// ── 状态机 ───────────────────────────────────────────────────────────
class AuthNotifier extends StateNotifier<AuthState> {
AuthNotifier(this._store, {AuthApi? api})
: _api = api ?? AuthApi(baseUrl: kApiBaseUrl),
super(const AuthState(isLoading: true)) {
_loadFromStore();
}
final TokenStore _store;
final AuthApi _api;
Future<void> _loadFromStore() async {
try {
final token = await _store.loadAccessToken();
state = AuthState(accessToken: token);
} catch (_) {
// FlutterSecureStorage 在测试环境 / 未初始化时抛异常,视为未登录。
state = const AuthState();
}
}
/// 登录 / 注册成功后保存令牌。
Future<void> saveTokens(AuthTokens tokens) async {
await _store.saveTokens(
access: tokens.accessToken,
refresh: tokens.refreshToken,
);
state = AuthState(accessToken: tokens.accessToken);
}
/// 用存储的 refresh token 刷新令牌(供 ApiClient 在 401 时调用)。
/// 成功写入新令牌并更新状态返回 true;无 refresh token / 刷新失败返回 false。
Future<bool> refresh() async {
final rt = await _store.loadRefreshToken();
if (rt == null || rt.isEmpty) return false;
try {
await saveTokens(await _api.refresh(rt));
return true;
} on AuthApiException catch (e) {
// 服务端明确拒绝(refresh 过期/失效,超出 7 天)→ 退出登录回登录页;
// 网络错误(statusCode<=0)则保留会话,稍后重试。
if (e.statusCode > 0) await logout();
return false;
} catch (_) {
return false;
}
}
/// 退出登录:清除本地令牌。
Future<void> logout() async {
await _store.clear();
state = const AuthState();
}
}
// ── Providers ────────────────────────────────────────────────────────
/// 可在测试中 override,注入 stub TokenStore(避免 FlutterSecureStorage 平台依赖)。
final tokenStoreProvider = Provider<TokenStore>((_) => const TokenStore());
final authProvider =
StateNotifierProvider<AuthNotifier, AuthState>(
(ref) => AuthNotifier(ref.watch(tokenStoreProvider)),
);