171 lines
5.8 KiB
Dart
171 lines
5.8 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:common_utils/common_utils.dart';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:dio/io.dart';
|
|
import 'package:flutter_easyloading/flutter_easyloading.dart';
|
|
import 'package:get/get.dart';
|
|
|
|
import 'package:pj_supermarket_cloud/common/index.dart';
|
|
|
|
const ignoreMsg = ["账号未登录"];
|
|
|
|
class HttpManage {
|
|
static const _tag = "http管理";
|
|
|
|
static final HttpManage _instance = HttpManage._internal();
|
|
|
|
factory HttpManage() => _instance;
|
|
|
|
late Dio dio;
|
|
|
|
HttpManage._internal() {
|
|
BaseOptions globalOptions = BaseOptions(
|
|
baseUrl: Constants.apiUrl,
|
|
connectTimeout: const Duration(seconds: 10),
|
|
responseType: ResponseType.json,
|
|
);
|
|
dio = Dio(globalOptions);
|
|
// 拦截
|
|
dio.interceptors.add(
|
|
InterceptorsWrapper(
|
|
onRequest: (RequestOptions options, handler) async {
|
|
options.headers["CLIENT-TOC"] = "Y";
|
|
final userInfo = await AppSettingTool.getUserSetting();
|
|
if (!options.path.contains(Constants.oauth2AppApiUrl)) {
|
|
if (ObjectUtil.isNotEmpty(userInfo.accessToken)) {
|
|
options.headers['Authorization'] =
|
|
"Bearer ${userInfo.accessToken}";
|
|
}
|
|
}
|
|
options.headers["TENANT-ID"] = userInfo.tenantId ?? 1;
|
|
return handler.next(options);
|
|
},
|
|
onResponse: (e, handler) async {
|
|
// 先判断是不是登录接口
|
|
late ServiceBase serviceData;
|
|
if (e.requestOptions.path.contains(Constants.oauth2AppApiUrl)) {
|
|
serviceData = ServiceBase(msg: "", code: 0, data: e.data);
|
|
} else {
|
|
serviceData = ServiceBase.fromJson(e.data);
|
|
}
|
|
if (serviceData.code == 401 &&
|
|
ObjectUtil.isNotEmpty(serviceData.msg)) {
|
|
if (!ignoreMsg.contains(serviceData.msg)) {
|
|
Toast.error(msg: serviceData.msg ?? "服务器未知错误");
|
|
}
|
|
final isLogin = await _autoLogin();
|
|
if (!isLogin) {
|
|
Get.offAndToNamed(RouteNames.login);
|
|
}
|
|
} else if (serviceData.code != 0) {
|
|
Toast.error(msg: serviceData.msg ?? "服务器未知错误");
|
|
}
|
|
// 续一下token
|
|
if (!e.realUri.path.contains("refresh-token")) {
|
|
// _refreshToken();
|
|
}
|
|
e.data = serviceData.data;
|
|
handler.next(e);
|
|
},
|
|
onError: (e, handler) async {
|
|
final response = e.response;
|
|
final statusCode = response?.statusCode;
|
|
if (statusCode != null) {
|
|
if (statusCode == 424) {
|
|
final isLogin = await _autoLogin();
|
|
if (!isLogin) {
|
|
Get.offAndToNamed(RouteNames.login);
|
|
}
|
|
handler.next(e);
|
|
}
|
|
}
|
|
if (response != null && response.data != null) {
|
|
ServiceBase data = ServiceBase.fromJson(response.data);
|
|
if (data.code != 0) {
|
|
Toast.error(msg: data.msg ?? "服务器未知错误");
|
|
EasyLoading.dismiss();
|
|
handler.next(e);
|
|
return;
|
|
}
|
|
}
|
|
return handler.next(e);
|
|
},
|
|
),
|
|
);
|
|
|
|
dio.httpClientAdapter = IOHttpClientAdapter(
|
|
createHttpClient: () {
|
|
final HttpClient client =
|
|
HttpClient(context: SecurityContext(withTrustedRoots: false));
|
|
client.badCertificateCallback = (cert, host, port) => true;
|
|
return client;
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<bool> _autoLogin() async {
|
|
final userSetting = await AppSettingTool.getUserSetting();
|
|
final sysSetting = await AppSettingTool.getSysSetting();
|
|
if (ObjectUtil.isEmpty(userSetting.username) ||
|
|
ObjectUtil.isEmpty(userSetting.password) ||
|
|
ObjectUtil.isEmpty(userSetting.accessToken)) {
|
|
return false;
|
|
}
|
|
final pa = <String, dynamic>{
|
|
'username': userSetting.username,
|
|
'password': userSetting.password,
|
|
'sysType': sysSetting.sysType.name,
|
|
'grant_type': 'password',
|
|
'scope': 'server',
|
|
};
|
|
try {
|
|
final data = await UserApi.login(pa);
|
|
if (data != null) throw Error();
|
|
userSetting.userId = data['user_id'];
|
|
userSetting.accessToken = data['access_token'];
|
|
userSetting.refreshToken = data['refresh_token'];
|
|
userSetting.expiresTime = int.tryParse("${data['exp']}");
|
|
await AppSettingTool.setUserSetting(userSetting);
|
|
return true;
|
|
} catch (e) {
|
|
await AppSettingTool.setUserSetting(UserSetting());
|
|
logger.e("|$_tag|自动登录意外的错误error:|$e|");
|
|
}
|
|
return false;
|
|
}
|
|
|
|
Future<void> _refreshToken() async {
|
|
final userSetting = await AppSettingTool.getUserSetting();
|
|
if (ObjectUtil.isEmpty(userSetting.refreshToken) ||
|
|
ObjectUtil.isEmpty(userSetting.expiresTime)) {
|
|
return;
|
|
}
|
|
final now = DateTime.now().millisecondsSinceEpoch;
|
|
final remain = userSetting.expiresTime! - now;
|
|
logger.i("|$_tag|token还有${remain / 1000 / 60}分钟${remain / 1000}秒过期");
|
|
if (remain > 1000 * 60 * 20) return;
|
|
final pa = {"refreshToken": userSetting.refreshToken};
|
|
try {
|
|
final res = await UserApi.refreshToken(pa);
|
|
if (res.code != 0) throw Error();
|
|
final data = res.data as ServiceAuth;
|
|
if (ObjectUtil.isNotEmpty(data.userId)) {
|
|
userSetting.userId = data.userId;
|
|
}
|
|
if (ObjectUtil.isNotEmpty(data.accessToken)) {
|
|
userSetting.accessToken = data.accessToken;
|
|
}
|
|
if (ObjectUtil.isNotEmpty(data.refreshToken)) {
|
|
userSetting.refreshToken = data.refreshToken;
|
|
}
|
|
if (ObjectUtil.isNotEmpty(data.expiresTime)) {
|
|
userSetting.expiresTime = data.expiresTime;
|
|
}
|
|
await AppSettingTool.setUserSetting(userSetting);
|
|
} catch (e) {
|
|
logger.e("|$_tag|续存token意外的错误error:|$e|");
|
|
}
|
|
}
|
|
}
|