login_controller.dart
8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import 'dart:async';
import 'dart:convert';
import 'package:doublefeel_flutter/core/config/app_environment_config.dart';
import 'package:doublefeel_flutter/core/constants/app_const.dart';
import 'package:doublefeel_flutter/core/logging/app_logger.dart';
import 'package:doublefeel_flutter/data/models/local/user_preferences.dart';
import 'package:doublefeel_flutter/l10n/gen/app_localizations.dart';
import 'package:doublefeel_flutter/pigeon/platform_api.g.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:doublefeel_flutter/core/util/app_toast.dart';
import 'package:doublefeel_flutter/core/network/api/user_api.dart';
import 'package:doublefeel_flutter/core/network/api/vip_api.dart';
import 'package:doublefeel_flutter/core/services/user_state_service.dart';
import 'package:doublefeel_flutter/data/local/local_storage.dart';
import 'package:doublefeel_flutter/data/local/user_account_storage.dart';
import 'package:doublefeel_flutter/data/local/user_preferences_storage.dart';
import 'package:doublefeel_flutter/data/models/user/user_models.dart';
import 'package:doublefeel_flutter/data/models/vip/vip_info.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
class LoginController extends GetxController {
final UserApi _userApi = Get.find<UserApi>();
final VipApi _vipApi = Get.find<VipApi>();
final UserPreferencesStorage _userPrefs = Get.find<UserPreferencesStorage>();
final UserAccountStorage _userAccount = Get.find<UserAccountStorage>();
final UserStateService _userStateService = Get.find<UserStateService>();
final phoneController = TextEditingController();
final codeController = TextEditingController();
final phoneInput = ''.obs;
final codeInput = ''.obs;
final isSendingCode = false.obs;
final countdownSeconds = 0.obs;
Timer? _countdownTimer;
final isLoggingIn = false.obs;
final hasSentCode = false.obs;
final termsChecked = false.obs;
AppleSignInModel? appleSignInModel;
void toggleTermsChecked() {
termsChecked.value = !termsChecked.value;
}
void onPhoneLoginPressed() {
if (!termsChecked.value) {
AppToast.show(AppLocalizations.of(Get.context!)!.loginAgreeToTermsToast);
return;
}
Get.toNamed(AppRoutes.phoneLogin);
}
void onAppleLoginPressed() async {
if (!termsChecked.value) {
AppToast.show(AppLocalizations.of(Get.context!)!.loginAgreeToTermsToast);
return;
}
final result = await PlatformHostApi().requestAppleSignIn();
// result 为 null 或 identityToken 为空,说明用户取消或苹果授权失败
if (result == null || result.identityToken?.isNotEmpty != true) {
appleSignInModel = null;
return;
}
appleSignInModel = result;
await _loginWithApple(result);
}
void onDebugPressed() {
Get.toNamed(AppRoutes.debugEnvironment);
}
void openUserTerms() {
Get.toNamed(
AppRoutes.webview,
parameters: {'url': AppConst.userTerms},
);
}
void openPrivacyPolicy() {
Get.toNamed(
AppRoutes.webview,
parameters: {'url': AppConst.privacyPolicy},
);
}
@override
void onInit() {
super.onInit();
phoneController.addListener(() {
phoneInput.value = phoneController.text;
});
codeController.addListener(() {
codeInput.value = codeController.text;
});
}
@override
void onClose() {
_countdownTimer?.cancel();
phoneController.dispose();
codeController.dispose();
super.onClose();
}
String get cleanPhone => phoneInput.value.replaceAll(' ', '');
bool get canRequestCode =>
cleanPhone.length == 11 &&
!isSendingCode.value &&
countdownSeconds.value == 0;
bool get canLogin =>
cleanPhone.length == 11 &&
codeInput.value.isNotEmpty &&
!isLoggingIn.value;
Future<void> requestVerifyCode() async {
if (!canRequestCode) return;
if (cleanPhone.length < 11) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidPhone);
return;
}
isSendingCode.value = true;
final request = VerifyCodeRequest.login(cleanPhone);
final result = await _userApi.requestVerifyCode(request);
isSendingCode.value = false;
if (result is AppSuccess<void>) {
AppToast.show(
AppLocalizations.of(Get.context!)!.phoneLoginCodeSentSuccess);
_startCountdown();
}
}
void _startCountdown() {
hasSentCode.value = true;
_countdownTimer?.cancel();
countdownSeconds.value = 60;
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (countdownSeconds.value > 1) {
countdownSeconds.value--;
} else {
countdownSeconds.value = 0;
timer.cancel();
}
});
}
Future<void> login() async {
if (!canLogin) return;
if (cleanPhone.length < 11) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidPhone);
return;
}
if (codeInput.value.isEmpty) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidCode);
return;
}
isLoggingIn.value = true;
final loginRes = await _userApi.login(
telephone: cleanPhone,
verifyCode: codeInput.value,
);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data);
} else {
isLoggingIn.value = false;
}
}
Future<void> _loginWithApple(AppleSignInModel appleModel) async {
isLoggingIn.value = true;
final loginRes = await _userApi.loginWithApple(appleModel);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data, isApple: true);
} else {
isLoggingIn.value = false;
}
}
/// 登录/注册成功后的公共处理逻辑(手机号登录与苹果登录共用)
Future<void> _handleLoginSuccess(
LoginResponse loginData, {
bool isApple = false,
}) async {
final isRegister = loginData.isNewUser == true;
String accessToken = loginData.accessToken;
if (isRegister && !isApple) {
// 苹果登录时后端直接完成注册,无需二次注册请求
final regRes = await _userApi.register(
telephone: cleanPhone,
verifyCode: codeInput.value,
);
if (regRes is AppSuccess<RegisterResponse>) {
accessToken = regRes.data.accessToken;
} else {
isLoggingIn.value = false;
return;
}
}
// Fetch user info and VIP info
final userInfoResFuture = _userApi.getUserInfo(accessToken: accessToken);
final vipInfoResFuture = isRegister
? Future.value(null)
: _vipApi.getVipInfo(accessToken: accessToken);
final results = await Future.wait([userInfoResFuture, vipInfoResFuture]);
final userInfoRes = results[0];
final vipInfoRes = results[1];
if (userInfoRes is AppSuccess<UserInfoResponse>) {
final me = userInfoRes.data;
UserInfoResponse? partner;
if ((me.pairId ?? 0) > 0) {
final partnerRes =
await _userApi.getPartnerUserInfo(accessToken: accessToken);
if (partnerRes is AppSuccess<BoundUserInfoResponse>) {
partner = partnerRes.data.partnerUserInfo;
}
}
VipInfo? vip;
if (vipInfoRes is AppSuccess<VipInfo>) {
vip = vipInfoRes.data;
}
await _userPrefs.updateFromLogin(
accessToken: accessToken,
me: me,
partner: partner,
vip: vip,
);
try {
if (Get.isRegistered<AppEnvironmentConfig>()) {
var env = Get.find<AppEnvironmentConfig>();
await PlatformHostApi().updateLoginInfo(
jsonEncode(UserPreferences(
accessToken: accessToken,
meUserInfo: me,
partnerUserInfo: partner,
vipInfo: vip != null
? UserPreferencesVipInfo.fromVipInfo(vip)
: null,
)),
env.serverBaseUrl);
}
} on Exception catch (e) {
AppLogger.e(e);
}
await _userStateService.onLogin();
// 用户登录成功即代表同意了协议,持久化到本地供冷启动时 SDK 初始化判断使用
await Get.find<LocalStorage>().setTermsAgreed(true);
isLoggingIn.value = false;
// 根据引导完成状态决定跳转目标
final userId = me.id ?? 0;
if (_userAccount.hasCompletedOnboarding(userId)) {
// 该账号已完成引导,直接进主页
Get.offAllNamed(AppRoutes.home);
} else {
// 新用户或未完成引导,进入引导页(支持断点续做)
final resumeStage = _userAccount.onboardingResumeStage(userId);
Get.offAllNamed(
AppRoutes.userOnboarding,
arguments: resumeStage != null ? {'resumeStage': resumeStage} : null,
);
}
} else {
isLoggingIn.value = false;
}
}
}