feat(client): C 端 1-2 账号链路(邮箱登录/注册 + 令牌与 401 + 匿名/登录分叉)
为什么:客户端此前完全没有账号概念(mine 页的"登录"只是本地 demo 开关), 而受限动作(收藏/评论)要对到具体账号。本批把账号链路接上,为后续互动、进度同步、下载打底。 - AuthApi + AuthController + AuthSessionStore:注册/登录/登出/刷新,令牌与设备号存 shared_preferences (用 SharedPreferencesAsync,与 engagement 仓库同一套 API) - ApiClient:统一带 Authorization 与 X-Device-Id;401 自动刷新一次并重试,刷新失败清登录态走 onUnauthorized - 登录/注册页(pages/auth,沿用 binding/logic/view 与现有视觉):邮箱格式、密码 8-64 位含字母数字本地先校验, 错误提示走 l10n;登录/注册一键切换 - 匿名/登录分叉:首页、发现、详情保持匿名可看;收藏/点赞等受限动作走 ensureSignedIn() 弹底部提示引导登录 - mine 页展示真实账号(昵称 + uid),拿不到才回落到演示文案 - 测试:新增 auth 控制器(注册落盘/401 刷新重试/刷新失败清会话/登出)与登录页(校验/切换)用例; widget_test 改为预置本地会话(账号不再是本地开关);修掉 playback 用例对 host 大小写的环境依赖断言 门禁:flutter analyze 0 问题;flutter test 148 全过。
This commit is contained in:
1 parent
77d5748dbb
commit
e1b98df509
24 files changed
+2871
-1016
No files matched your search
@@ -0,0 +1,51 @@
|
||||
/// 登录态:服务端下发的令牌与用户摘要。
|
||||
///
|
||||
/// 只保留客户端真正要用的字段(uid / 昵称 / 头像),不做整份 AppUserRespVO 的映射 ——
|
||||
/// 首页卡片、个人页需要的都在这里,避免为用不到的字段维护一份平行模型。
|
||||
class AuthUser {
|
||||
const AuthUser({required this.uid, required this.nickname, this.avatarUrl = ''});
|
||||
|
||||
final String uid;
|
||||
final String nickname;
|
||||
final String avatarUrl;
|
||||
|
||||
factory AuthUser.fromJson(Map<String, dynamic> json) => AuthUser(
|
||||
uid: json['uid'] as String? ?? '',
|
||||
nickname: json['nickname'] as String? ?? '',
|
||||
avatarUrl: json['avatarUrl'] as String? ?? '',
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'uid': uid,
|
||||
'nickname': nickname,
|
||||
'avatarUrl': avatarUrl,
|
||||
};
|
||||
}
|
||||
|
||||
class AuthSession {
|
||||
const AuthSession({
|
||||
required this.accessToken,
|
||||
required this.refreshToken,
|
||||
this.expiresIn = 0,
|
||||
required this.user,
|
||||
});
|
||||
|
||||
final String accessToken;
|
||||
final String refreshToken;
|
||||
final int expiresIn;
|
||||
final AuthUser user;
|
||||
|
||||
factory AuthSession.fromJson(Map<String, dynamic> json) => AuthSession(
|
||||
accessToken: json['accessToken'] as String? ?? '',
|
||||
refreshToken: json['refreshToken'] as String? ?? '',
|
||||
expiresIn: (json['expiresIn'] as num?)?.toInt() ?? 0,
|
||||
user: AuthUser.fromJson((json['user'] as Map?)?.cast<String, dynamic>() ?? const {}),
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'accessToken': accessToken,
|
||||
'refreshToken': refreshToken,
|
||||
'expiresIn': expiresIn,
|
||||
'user': user.toJson(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../config/app_config.dart';
|
||||
|
||||
/// 接口异常:code 为后端业务码,message 可直接展示。
|
||||
class ApiException implements Exception {
|
||||
const ApiException(this.code, this.message);
|
||||
|
||||
final int code;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'ApiException($code, $message)';
|
||||
}
|
||||
|
||||
/// 后端统一响应壳 `{code, message, data}` 的解析入口。
|
||||
class ApiClient {
|
||||
ApiClient({
|
||||
String? baseUrl,
|
||||
http.Client? client,
|
||||
this.accessTokenReader,
|
||||
this.tokenRefresher,
|
||||
this.onUnauthorized,
|
||||
this.deviceIdReader,
|
||||
})
|
||||
: baseUrl = baseUrl ?? AppConfig.apiBaseUrl,
|
||||
_client = client ?? http.Client();
|
||||
|
||||
final String baseUrl;
|
||||
final http.Client _client;
|
||||
|
||||
/// 取当前 access token(未登录返回 null)
|
||||
final String? Function()? accessTokenReader;
|
||||
|
||||
/// 刷新令牌:返回 true 表示刷新成功,可以重试原请求
|
||||
final Future<bool> Function()? tokenRefresher;
|
||||
|
||||
/// 刷新也失败时回调(清本地登录态、回收 UI)
|
||||
final void Function()? onUnauthorized;
|
||||
|
||||
/// 设备号(`X-Device-Id`):注册风控、后续下载绑定都要用
|
||||
final Future<String> Function()? deviceIdReader;
|
||||
|
||||
Future<Object?> get(String path, {Map<String, String>? query}) {
|
||||
return _send('GET', path, query: query);
|
||||
}
|
||||
|
||||
Future<Object?> post(
|
||||
String path, {
|
||||
Object? body,
|
||||
Map<String, String>? query,
|
||||
bool skipAuthRetry = false,
|
||||
}) {
|
||||
return _send('POST', path, body: body, query: query, skipAuthRetry: skipAuthRetry);
|
||||
}
|
||||
|
||||
Future<Object?> _send(
|
||||
String method,
|
||||
String path, {
|
||||
Object? body,
|
||||
Map<String, String>? query,
|
||||
bool retried = false,
|
||||
bool skipAuthRetry = false,
|
||||
}) async {
|
||||
final uri = Uri.parse(
|
||||
'$baseUrl$path',
|
||||
).replace(queryParameters: query?.isEmpty ?? true ? null : query);
|
||||
final headers = await _headers(withBody: body != null);
|
||||
final response = await (method == 'GET'
|
||||
? _client.get(uri, headers: headers)
|
||||
: _client.post(
|
||||
uri,
|
||||
headers: headers,
|
||||
body: body == null ? null : jsonEncode(body),
|
||||
))
|
||||
.timeout(AppConfig.requestTimeout);
|
||||
|
||||
Map<String, dynamic> shell = const {};
|
||||
try {
|
||||
shell = (jsonDecode(utf8.decode(response.bodyBytes)) as Map)
|
||||
.cast<String, dynamic>();
|
||||
} catch (_) {
|
||||
shell = const {};
|
||||
}
|
||||
final code = shell['code'] as int? ?? -1;
|
||||
|
||||
// 令牌过期:刷新一次再重试原请求;刷新失败就清登录态并抛给调用方
|
||||
if (code == 401 && !retried && !skipAuthRetry && tokenRefresher != null) {
|
||||
final refreshed = await tokenRefresher!.call();
|
||||
if (refreshed) {
|
||||
return _send(
|
||||
method,
|
||||
path,
|
||||
body: body,
|
||||
query: query,
|
||||
retried: true,
|
||||
skipAuthRetry: skipAuthRetry,
|
||||
);
|
||||
}
|
||||
onUnauthorized?.call();
|
||||
throw ApiException(401, shell['message'] as String? ?? '登录已过期');
|
||||
}
|
||||
|
||||
if (code == -1) {
|
||||
throw ApiException(response.statusCode, 'HTTP ${response.statusCode}');
|
||||
}
|
||||
if (code != 0) {
|
||||
throw ApiException(code, shell['message'] as String? ?? '请求失败');
|
||||
}
|
||||
return shell['data'];
|
||||
}
|
||||
|
||||
Future<Map<String, String>> _headers({required bool withBody}) async {
|
||||
final headers = <String, String>{'Accept': 'application/json'};
|
||||
if (withBody) headers['Content-Type'] = 'application/json';
|
||||
final token = accessTokenReader?.call();
|
||||
if (token != null && token.isNotEmpty) {
|
||||
headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
final deviceId = await deviceIdReader?.call();
|
||||
if (deviceId != null && deviceId.isNotEmpty) {
|
||||
headers['X-Device-Id'] = deviceId;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
void close() => _client.close();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import '../models/auth_session.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
/// 账号相关接口(/app/auth/**)。
|
||||
///
|
||||
/// 注册/登录都用「邮箱 + 密码」;邮箱注册不需要验证码(后端按 targetType 放开),
|
||||
/// 手机号注册仍要验证码 —— 客户端这一批只开放邮箱入口。
|
||||
class AuthApi {
|
||||
const AuthApi(this._client);
|
||||
|
||||
final ApiClient _client;
|
||||
|
||||
Future<AuthSession> register({
|
||||
required String email,
|
||||
required String password,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
'/app/auth/register',
|
||||
body: {
|
||||
'targetType': 'EMAIL',
|
||||
'target': email,
|
||||
'password': password,
|
||||
'countryCode': 'ID',
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||
}
|
||||
|
||||
Future<AuthSession> login({
|
||||
required String email,
|
||||
required String password,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
'/app/auth/login',
|
||||
body: {
|
||||
'targetType': 'EMAIL',
|
||||
'target': email,
|
||||
'password': password,
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||
}
|
||||
|
||||
Future<AuthSession> refresh(String refreshToken) async {
|
||||
final data = await _client.post(
|
||||
'/app/auth/refresh',
|
||||
body: {'refreshToken': refreshToken},
|
||||
// 刷新请求本身不带旧令牌重试,失败就是失败
|
||||
skipAuthRetry: true,
|
||||
);
|
||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||
}
|
||||
|
||||
Future<void> logout(String refreshToken) async {
|
||||
await _client.post(
|
||||
'/app/auth/logout',
|
||||
body: {'refreshToken': refreshToken},
|
||||
skipAuthRetry: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/auth_session.dart';
|
||||
import '../remote/api_client.dart';
|
||||
import '../remote/auth_api.dart';
|
||||
import 'auth_session_store.dart';
|
||||
|
||||
/// 登录态的唯一来源。
|
||||
///
|
||||
/// 职责:本地会话的读写([AuthSessionStore])、注册/登录/登出、令牌刷新;
|
||||
/// 也是 [ApiClient] 的 `accessTokenReader` / `tokenRefresher` / `onUnauthorized` 实现方 ——
|
||||
/// 401 → 刷新 → 重试失败就清会话,UI 通过 [isSignedIn] 自动回到未登录态。
|
||||
class AuthController extends ChangeNotifier {
|
||||
AuthController(this._api, this._store);
|
||||
|
||||
final AuthApi _api;
|
||||
final AuthSessionStore _store;
|
||||
|
||||
AuthSession? _session;
|
||||
String _deviceId = '';
|
||||
bool _loaded = false;
|
||||
|
||||
bool get isLoaded => _loaded;
|
||||
bool get isSignedIn => _session != null;
|
||||
AuthUser? get user => _session?.user;
|
||||
String? get accessToken => _session?.accessToken;
|
||||
String get deviceId => _deviceId;
|
||||
|
||||
/// App 启动时调用:恢复本地令牌与设备号。
|
||||
Future<void> load() async {
|
||||
_deviceId = await _store.deviceId();
|
||||
_session = await _store.read();
|
||||
_loaded = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> register({required String email, required String password}) async {
|
||||
final session = await _api.register(
|
||||
email: email,
|
||||
password: password,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
|
||||
Future<void> signIn({required String email, required String password}) async {
|
||||
final session = await _api.login(
|
||||
email: email,
|
||||
password: password,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
final refreshToken = _session?.refreshToken ?? '';
|
||||
_session = null;
|
||||
await _store.clear();
|
||||
notifyListeners();
|
||||
if (refreshToken.isNotEmpty) {
|
||||
// 服务端吊销失败不影响本地已登出,异常直接吞掉
|
||||
try {
|
||||
await _api.logout(refreshToken);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 供 [ApiClient] 调用:刷新令牌并落盘。失败时清本地会话。
|
||||
Future<bool> refresh() async {
|
||||
final refreshToken = _session?.refreshToken ?? '';
|
||||
if (refreshToken.isEmpty) {
|
||||
await clear();
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await _apply(await _api.refresh(refreshToken));
|
||||
return true;
|
||||
} catch (_) {
|
||||
await clear();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
if (_session == null) return;
|
||||
_session = null;
|
||||
await _store.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _apply(AuthSession session) async {
|
||||
_session = session;
|
||||
await _store.save(session);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
String get _platform {
|
||||
if (kIsWeb) return 'WEB';
|
||||
return defaultTargetPlatform == TargetPlatform.iOS ? 'IOS' : 'ANDROID';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/auth_session.dart';
|
||||
|
||||
/// 令牌与设备号的本地持久化。
|
||||
///
|
||||
/// 用 `SharedPreferencesAsync`(与项目里 engagement 仓库一致):旧的
|
||||
/// `SharedPreferences.getInstance()` 在新版本里已标注弃用,两套混用还会让
|
||||
/// widget 测试只 mock 到其中一套。
|
||||
///
|
||||
/// 设备号是后端注册风控与后续"下载设备绑定"的依据,所以**首次生成后就固定下来**;
|
||||
/// 不引 UUID 库(保持极简依赖),用「时间戳 + 随机数」拼一个够用的 id。
|
||||
class AuthSessionStore {
|
||||
static const _kAccessToken = 'auth.accessToken';
|
||||
static const _kRefreshToken = 'auth.refreshToken';
|
||||
static const _kUser = 'auth.user';
|
||||
static const _kDeviceId = 'device.id';
|
||||
|
||||
String? _cachedDeviceId;
|
||||
|
||||
Future<String> deviceId() async {
|
||||
if (_cachedDeviceId != null) return _cachedDeviceId!;
|
||||
final prefs = SharedPreferencesAsync();
|
||||
var value = await prefs.getString(_kDeviceId) ?? '';
|
||||
if (value.isEmpty) {
|
||||
final random = Random();
|
||||
value =
|
||||
'd-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-'
|
||||
'${random.nextInt(1 << 32).toRadixString(36)}';
|
||||
await prefs.setString(_kDeviceId, value);
|
||||
}
|
||||
_cachedDeviceId = value;
|
||||
return value;
|
||||
}
|
||||
|
||||
Future<AuthSession?> read() async {
|
||||
final prefs = SharedPreferencesAsync();
|
||||
final accessToken = await prefs.getString(_kAccessToken) ?? '';
|
||||
final refreshToken = await prefs.getString(_kRefreshToken) ?? '';
|
||||
if (accessToken.isEmpty || refreshToken.isEmpty) return null;
|
||||
final rawUser = await prefs.getString(_kUser);
|
||||
Map<String, dynamic> user = const {};
|
||||
if (rawUser != null && rawUser.isNotEmpty) {
|
||||
try {
|
||||
user = (jsonDecode(rawUser) as Map).cast<String, dynamic>();
|
||||
} catch (_) {
|
||||
user = const {};
|
||||
}
|
||||
}
|
||||
return AuthSession(
|
||||
accessToken: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
user: AuthUser.fromJson(user),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> save(AuthSession session) async {
|
||||
final prefs = SharedPreferencesAsync();
|
||||
await prefs.setString(_kAccessToken, session.accessToken);
|
||||
await prefs.setString(_kRefreshToken, session.refreshToken);
|
||||
await prefs.setString(_kUser, jsonEncode(session.user.toJson()));
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
final prefs = SharedPreferencesAsync();
|
||||
await prefs.remove(_kAccessToken);
|
||||
await prefs.remove(_kRefreshToken);
|
||||
await prefs.remove(_kUser);
|
||||
// 设备号不清:它代表"这台设备",与登录态无关
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../../pages/auth/auth_view.dart';
|
||||
import '../data/services/auth_controller.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
|
||||
/// 打开登录 / 注册页(沿用现有 Navigator 风格,不引路由库)
|
||||
Future<void> openAuthPage(BuildContext context, {bool signUpMode = false}) {
|
||||
return Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => AuthPage(signUpMode: signUpMode),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 受限动作的登录闸:已登录返回 true;未登录弹底部提示并引导登录,返回 false。
|
||||
///
|
||||
/// 首页/发现/详情保持匿名可看,只有收藏、点赞、评论这类"要对到具体账号"的动作才走这里。
|
||||
Future<bool> ensureSignedIn(BuildContext context) async {
|
||||
final auth = context.read<AuthController>();
|
||||
if (auth.isSignedIn) return true;
|
||||
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final go = await showModalBottomSheet<bool>(
|
||||
context: context,
|
||||
backgroundColor: AppColors.card,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(18)),
|
||||
),
|
||||
builder: (sheetContext) => SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 18, 20, 20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.authGateTitle,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
l10n.authGateMessage,
|
||||
style: const TextStyle(color: AppColors.muted, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: () => Navigator.of(sheetContext).pop(false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: AppColors.blue,
|
||||
),
|
||||
onPressed: () => Navigator.of(sheetContext).pop(true),
|
||||
child: Text(l10n.authGateAction),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (go == true && context.mounted) {
|
||||
await openAuthPage(context);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Reference in new issue
Block a user