修复工作人员端令牌失效后的登录恢复
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// 功能描述:封装工作人员端 HTTP 请求,并将服务端错误转换为安全、可读的中文提示。
|
||||
// 版本:1.1.0
|
||||
// 版本:1.2.0
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
@@ -84,20 +84,33 @@ class ApiException implements Exception {
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 表示鉴权会话已经失效;页面层应等待路由跳转,不再展示普通网络错误。
|
||||
class SessionExpiredException extends ApiException {
|
||||
const SessionExpiredException() : super(401, '登录状态已失效,请重新登录');
|
||||
}
|
||||
|
||||
/// 接收被服务端拒绝的请求令牌,用于安全地失效对应会话。
|
||||
typedef UnauthorizedCallback = void Function(String rejectedToken);
|
||||
|
||||
/// 负责工作人员端统一 HTTP 请求、鉴权头和响应解析。
|
||||
class ApiClient {
|
||||
ApiClient(this._tokenProvider, {http.Client? client, String? baseUrl})
|
||||
: _client = client ?? http.Client(),
|
||||
baseUrl =
|
||||
baseUrl ??
|
||||
const String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: 'http://10.0.2.2:12426',
|
||||
);
|
||||
ApiClient(
|
||||
this._tokenProvider, {
|
||||
http.Client? client,
|
||||
String? baseUrl,
|
||||
this.onUnauthorized,
|
||||
}) : _client = client ?? http.Client(),
|
||||
baseUrl =
|
||||
baseUrl ??
|
||||
const String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: 'http://10.0.2.2:12426',
|
||||
);
|
||||
|
||||
final String baseUrl;
|
||||
final String Function() _tokenProvider;
|
||||
final http.Client _client;
|
||||
final UnauthorizedCallback? onUnauthorized;
|
||||
|
||||
Future<Object?> get(String path, {bool authenticated = true}) =>
|
||||
_send('GET', path, authenticated: authenticated);
|
||||
@@ -116,7 +129,8 @@ class ApiClient {
|
||||
'POST',
|
||||
Uri.parse('$baseUrl/upload/file'),
|
||||
);
|
||||
request.headers['authorization'] = _tokenProvider();
|
||||
final requestToken = _tokenProvider();
|
||||
if (requestToken.isNotEmpty) request.headers['authorization'] = requestToken;
|
||||
request.fields['declared_content_type'] = contentType;
|
||||
request.files.add(
|
||||
http.MultipartFile.fromBytes(
|
||||
@@ -126,7 +140,11 @@ class ApiClient {
|
||||
),
|
||||
);
|
||||
final response = await _sendRequest(request);
|
||||
final details = _decode(response);
|
||||
final details = _decode(
|
||||
response,
|
||||
authenticated: true,
|
||||
requestToken: requestToken,
|
||||
);
|
||||
return jsonMap(details)['uri'] as String? ?? '';
|
||||
}
|
||||
|
||||
@@ -138,15 +156,21 @@ class ApiClient {
|
||||
}) async {
|
||||
final request = http.Request(method, Uri.parse('$baseUrl$path'));
|
||||
request.headers['accept'] = 'application/json';
|
||||
if (authenticated && _tokenProvider().isNotEmpty) {
|
||||
request.headers['authorization'] = _tokenProvider();
|
||||
var requestToken = '';
|
||||
if (authenticated) {
|
||||
requestToken = _tokenProvider();
|
||||
if (requestToken.isNotEmpty) request.headers['authorization'] = requestToken;
|
||||
}
|
||||
if (body != null) {
|
||||
request.headers['content-type'] = 'application/json; charset=UTF-8';
|
||||
request.body = jsonEncode(body);
|
||||
}
|
||||
final response = await _sendRequest(request);
|
||||
return _decode(response);
|
||||
return _decode(
|
||||
response,
|
||||
authenticated: authenticated,
|
||||
requestToken: requestToken,
|
||||
);
|
||||
}
|
||||
|
||||
/// 发送请求并统一处理网络连接异常。
|
||||
@@ -159,7 +183,14 @@ class ApiClient {
|
||||
}
|
||||
|
||||
/// 解析统一响应结构,并按错误码生成中文提示。
|
||||
Object? _decode(http.Response response) {
|
||||
Object? _decode(
|
||||
http.Response response, {
|
||||
required bool authenticated,
|
||||
required String requestToken,
|
||||
}) {
|
||||
if (authenticated && response.statusCode == 401 && requestToken.isNotEmpty) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw ApiException(response.statusCode, '网络请求失败(${response.statusCode})');
|
||||
}
|
||||
@@ -174,6 +205,9 @@ class ApiClient {
|
||||
}
|
||||
final code = (decoded['code'] as num?)?.toInt() ?? 500;
|
||||
if (code != 0) {
|
||||
if (authenticated && requestToken.isNotEmpty && _isAuthenticationFailure(code)) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
throw ApiException(
|
||||
code,
|
||||
localizeApiErrorMessage(code, decoded['message'] as String?),
|
||||
@@ -181,8 +215,17 @@ class ApiClient {
|
||||
}
|
||||
return decoded['details'];
|
||||
}
|
||||
|
||||
/// 通知会话层并抛出专用异常,避免页面把鉴权失败误报为网络问题。
|
||||
Never _rejectSession(String rejectedToken) {
|
||||
onUnauthorized?.call(rejectedToken);
|
||||
throw const SessionExpiredException();
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断服务端稳定错误码是否表示登录会话无效。
|
||||
bool _isAuthenticationFailure(int code) => (code >= 1301 && code <= 1314) || code == 1715;
|
||||
|
||||
Map<String, Object?> jsonMap(Object? value) {
|
||||
if (value is Map<String, Object?>) return value;
|
||||
if (value is Map) return value.map((key, item) => MapEntry(key.toString(), item));
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
// 功能描述:封装工作人员端会话上下文的安全持久化接口与平台实现。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
class SecureSessionStore {
|
||||
/// 定义工作人员会话持久化能力,便于会话逻辑隔离具体存储实现。
|
||||
abstract interface class SessionStore {
|
||||
Future<String?> read(String key);
|
||||
|
||||
Future<void> write(String key, String value);
|
||||
|
||||
Future<void> delete(String key);
|
||||
}
|
||||
|
||||
/// 使用平台安全存储保存工作人员会话上下文。
|
||||
class SecureSessionStore implements SessionStore {
|
||||
SecureSessionStore({FlutterSecureStorage? storage})
|
||||
: _storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) => _storage.read(key: key);
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) => _storage.write(key: key, value: value);
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) => _storage.delete(key: key);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user