Repository navigation
Expand file tree
/
Copy pathlogin_page.dart
More file actions
676 lines (641 loc) · 25.2 KB
/
Copy pathlogin_page.dart
File metadata and controls
676 lines (641 loc) · 25.2 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*
SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD
SPDX-License-Identifier: MIT
*/
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:stack_chan/app_state.dart';
import 'package:stack_chan/model/model.dart';
import 'package:stack_chan/model/registration_response.dart';
import 'package:stack_chan/network/http.dart';
import 'package:stack_chan/network/urls.dart';
import 'package:stack_chan/util/blue_util.dart';
import 'package:stack_chan/util/value_constant.dart';
import 'package:stack_chan/view/app.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key, this.isWelCome});
final bool? isWelCome;
@override
State<StatefulWidget> createState() => _LoginPageState();
}
///loginAPIresponsemodel
class LoginResponseModel {
String? token;
///Constructorfunction
LoginResponseModel({this.token});
///from JSON maptoasmodelobject
factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
return LoginResponseModel(token: json['token'] as String?);
}
///willmodelobjecttoas JSON map
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['token'] = token;
return data;
}
}
class _LoginPageState extends State<LoginPage> {
String username = "";
String password = "";
late TextEditingController nameTextEditingController;
late TextEditingController passwordTextEditingController;
bool _obscurePassword = true;
RxBool loading = false.obs;
@override
void initState() {
super.initState();
nameTextEditingController = TextEditingController();
passwordTextEditingController = TextEditingController();
}
@override
void dispose() {
nameTextEditingController.dispose();
passwordTextEditingController.dispose();
super.dispose();
}
Future<void> login() async {
// Guard against double taps starting several requests.
if (loading.value) {
return;
}
// Validate before showing the spinner so a validation error never hides
// the form behind an endless spinner.
if (username.isEmpty) {
AppState.shared.showToast(
"Please enter your account number or email address.",
);
return;
}
if (password.isEmpty) {
AppState.shared.showToast("Please enter the password.");
return;
}
if (!Urls.isConfigured) {
AppState.shared.showToast("Backend server is not configured.");
return;
}
loading.value = true;
try {
final Map<String, dynamic> map = {
ValueConstant.username: username,
ValueConstant.password: password,
};
final response = await Http.instance.post(Urls.login, data: map);
// --- existing server-response handling (unchanged) ---
if (response.data != null) {
Model<LoginResponseModel> responseData = Model.fromJsonT(
response.data,
factory: (value) => LoginResponseModel.fromJson(value),
);
if (responseData.isSuccess()) {
final token = responseData.data?.token;
if (token != null) {
AppState.shared.setIsLogin(true);
await AppState.asyncPrefs.setString(ValueConstant.token, token);
AppState.shared.showToast("Login successful");
if (mounted) {
AppState.shared.getUserInfo();
AppState.shared.getDevices();
if (widget.isWelCome != true) {
CupertinoSheetRoute.popSheet(context);
} else {
Navigator.of(context).pop();
}
BlueUtil.shared.cachedDeviceMacs = [];
}
}
} else {
showLoginErrMessage(responseData.message);
}
} else {
AppState.shared.showToast(response.statusMessage);
}
} on FormatException catch (error, stackTrace) {
// e.g. RSA key parsing when encryption keys are not configured.
debugPrint("Login configuration/format error: $error");
debugPrintStack(stackTrace: stackTrace);
AppState.shared.showToast(
"The application encryption keys are not configured.",
);
} on DioException catch (error, stackTrace) {
// Network / server errors (timeout, DNS, TLS, HTTP status, bad body).
debugPrint("Login network error: ${error.type}");
debugPrintStack(stackTrace: stackTrace);
AppState.shared.showToast(
"Login failed. Check the internet connection or server configuration.",
);
} catch (error, stackTrace) {
debugPrint("Unexpected login error: $error");
debugPrintStack(stackTrace: stackTrace);
AppState.shared.showToast("An unexpected login error occurred.");
} finally {
// Always release the spinner, whatever happened above.
loading.value = false;
}
}
void showLoginErrMessage(String? text) {
if (text == "[[error:invalid-login-credentials]]") {
///passworderror
App.showDialog(
"Incorrect password or account number (the account will be locked for one hour after five incorrect attempts)",
);
return;
} else if (text == "[[error:account-locked]]") {
App.showDialog(
"Your account has been locked. Please wait for a moment before trying again",
);
return;
} else {
//defaulthint
String errorMessage = "Login failed";
if (text != null && text.isNotEmpty) {
//match [[error:xxx]] ,Extractinerrorcontent
final regExp = RegExp(r'\[\[error:(.*?)\]\]');
final match = regExp.firstMatch(text);
if (match != null) {
//Extracttocustomerrorcontent
errorMessage = match.group(1)!.trim();
} else {
//texterror,directuse
errorMessage = text.trim();
}
}
// Toast
AppState.shared.showToast(errorMessage);
}
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground.resolveFrom(
context,
),
child: GestureDetector(
onTap: () {
if (mounted) {
FocusScope.of(context).unfocus();
}
},
behavior: .opaque,
child: Obx(() {
if (loading.value) {
return Center(child: CupertinoActivityIndicator());
} else {
return Column(
children: [
Expanded(
child: CustomScrollView(
slivers: [
CupertinoSliverNavigationBar(
largeTitle: Text("Login"),
trailing: widget.isWelCome != true
? CupertinoButton(
padding: .zero,
child: Icon(
CupertinoIcons.xmark_circle_fill,
size: 25,
color: CupertinoColors.separator.resolveFrom(
context,
),
),
onPressed: () {
Navigator.of(
context,
rootNavigator: true,
).pop();
},
)
: SizedBox.shrink(),
),
SliverList.list(
children: [
Row(
children: [
SizedBox(width: 20),
Image.asset(
"assets/lateral_image.png",
height: 120,
width: 120,
),
SizedBox(width: 20),
Expanded(
child: Text(
"M5Stack account is used across UiFlow, M5Burner and forum 😊",
),
),
SizedBox(width: 20),
],
),
SizedBox(height: 15),
AutofillGroup(
child: Column(
mainAxisSize: .min,
spacing: 0,
children: [
CupertinoListSection.insetGrouped(
header: Text("username or email"),
children: [
CupertinoListTile(
padding: .zero,
title: CupertinoTextField(
placeholder: "username or email",
controller: nameTextEditingController,
placeholderStyle: TextStyle(
fontSize: 20,
color:
CupertinoColors.placeholderText,
),
style: TextStyle(
fontSize: 20,
color: CupertinoColors.label,
),
keyboardType: .emailAddress,
padding: .only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(),
autofocus: true,
textInputAction: .next,
onChanged: (value) {
username = value;
},
autofillHints: const [
AutofillHints.username,
],
),
),
],
),
CupertinoListSection.insetGrouped(
header: Text("password"),
children: [
CupertinoListTile(
padding: .zero,
title: CupertinoTextField(
controller:
passwordTextEditingController,
placeholder: "password",
obscureText: _obscurePassword,
style: TextStyle(
fontSize: 20,
color: CupertinoColors.label,
),
placeholderStyle: TextStyle(
fontSize: 20,
color:
CupertinoColors.placeholderText,
),
padding: .only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(),
keyboardType: .visiblePassword,
textInputAction: .go,
onSubmitted: (value) {
TextInput.finishAutofillContext();
login();
},
onChanged: (value) {
password = value;
},
autofillHints: const [
AutofillHints.password,
],
suffix: CupertinoButton(
child: Icon(
_obscurePassword
? CupertinoIcons.eye_slash
: CupertinoIcons.eye,
size: 22,
color: CupertinoColors.systemGrey
.resolveFrom(context),
),
onPressed: () {
setState(() {
_obscurePassword =
!_obscurePassword;
});
},
),
),
),
],
),
],
),
),
SizedBox(height: 15),
Row(
spacing: 0,
children: [
Spacer(),
Text("Don't have an account? "),
CupertinoButton(
onPressed: () {
TextInput.finishAutofillContext();
if (mounted) {
FocusScope.of(context).unfocus();
}
Navigator.of(context).push(
CupertinoPageRoute(
builder: (context) {
return RegistrationPage();
// return WebPage(
// url:
// "https://community.m5stack.com/register",
// previousPageTitle: "Login",
// );
},
),
);
},
minimumSize: .zero,
padding: .zero,
child: Text("Register now"),
),
Spacer(),
],
),
SizedBox(height: 15),
],
),
],
),
),
Padding(
padding: .only(
top: 15,
left: 15,
right: 15,
bottom: 15 + MediaQuery.paddingOf(context).bottom,
),
child: CupertinoButton.filled(
sizeStyle: .large,
child: SizedBox(
width: .infinity,
child: Center(child: Text("Login")),
),
onPressed: () {
login();
},
),
),
],
);
}
}),
),
);
}
}
class RegistrationPage extends StatefulWidget {
const RegistrationPage({super.key});
@override
State<StatefulWidget> createState() => _RegistrationPageState();
}
class _RegistrationPageState extends State<RegistrationPage> {
late final TextEditingController usernameController;
late final TextEditingController passwordController;
late final TextEditingController emailController;
@override
void initState() {
super.initState();
usernameController = TextEditingController();
passwordController = TextEditingController();
emailController = TextEditingController();
}
@override
void dispose() {
usernameController.dispose();
passwordController.dispose();
emailController.dispose();
super.dispose();
}
Future<void> register() async {
final username = usernameController.text.trim();
final password = passwordController.text.trim();
final email = emailController.text.trim();
if (username.isEmpty) {
AppState.shared.showToast("Please enter your username.");
return;
}
if (password.isEmpty) {
AppState.shared.showToast("Please enter the password.");
return;
}
if (email.isEmpty || !email.contains('@')) {
AppState.shared.showToast("Please enter a valid email address.");
return;
}
final Map<String, dynamic> requestData = {
ValueConstant.username: username,
ValueConstant.password: password,
ValueConstant.email: email,
};
final response = await Http.instance.post(
Urls.registration,
data: requestData,
);
if (response.data != null) {
Model<RegistrationResponse> responseData = Model.fromJsonT(
response.data,
factory: (value) => RegistrationResponse.fromJson(value),
);
if (responseData.isSuccess()) {
AppState.shared.showToast("Registration successful!");
if (mounted) {
Navigator.pop(context); //returnlogin
}
} else {
showLoginErrMessage(responseData.message);
}
} else {
AppState.shared.showToast(response.statusMessage ?? "Register failed");
}
}
void showLoginErrMessage(String? text) {
//defaulthint
String errorMessage = "Register failed";
if (text != null && text.isNotEmpty) {
//match [[error:xxx]] ,Extractinerrorcontent
final regExp = RegExp(r'\[\[error:(.*?)\]\]');
final match = regExp.firstMatch(text);
if (match != null) {
//Extracttocustomerrorcontent
errorMessage = match.group(1)!.trim();
} else {
//texterror,directuse
errorMessage = text.trim();
}
}
// Toast
AppState.shared.showToast(errorMessage);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground.resolveFrom(
context,
),
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
behavior: .opaque,
child: Column(
children: [
Expanded(
child: CustomScrollView(
slivers: [
CupertinoSliverNavigationBar(
largeTitle: Text("Register"),
padding: .only(start: 8, end: 8),
leading: CupertinoNavigationBarBackButton(
previousPageTitle: "Login",
),
),
SliverList.list(
children: [
CupertinoListSection.insetGrouped(
header: Text("Username"),
children: [
CupertinoListTile(
padding: .zero,
title: CupertinoTextField(
controller: usernameController,
placeholder: "username",
placeholderStyle: TextStyle(
fontSize: 20,
color: CupertinoColors.placeholderText
.resolveFrom(context),
),
style: TextStyle(
fontSize: 20,
color: CupertinoColors.label.resolveFrom(
context,
),
),
keyboardType: .name,
padding: .only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(),
autofocus: true,
textInputAction: .next,
),
),
],
),
CupertinoListSection.insetGrouped(
header: Text("Password"),
children: [
CupertinoListTile(
padding: .zero,
title: CupertinoTextField(
controller: passwordController,
placeholder: "password",
placeholderStyle: TextStyle(
fontSize: 20,
color: CupertinoColors.placeholderText
.resolveFrom(context),
),
style: TextStyle(
fontSize: 20,
color: CupertinoColors.label.resolveFrom(
context,
),
),
keyboardType: .visiblePassword,
padding: .only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(),
autofocus: true,
textInputAction: .next,
),
),
],
),
CupertinoListSection.insetGrouped(
header: Text("Email"),
children: [
CupertinoListTile(
padding: .zero,
title: CupertinoTextField(
controller: emailController,
placeholder: "email",
placeholderStyle: TextStyle(
fontSize: 20,
color: CupertinoColors.placeholderText
.resolveFrom(context),
),
style: TextStyle(
fontSize: 20,
color: CupertinoColors.label.resolveFrom(
context,
),
),
keyboardType: .emailAddress,
padding: .only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(),
autofocus: true,
textInputAction: .go,
onSubmitted: (value) {
if (mounted) {
FocusScope.of(context).unfocus();
}
register();
},
),
),
],
),
],
),
],
),
),
Padding(
padding: .only(
top: 15,
left: 15,
right: 15,
bottom: 15 + MediaQuery.paddingOf(context).bottom,
),
child: CupertinoButton.filled(
sizeStyle: .large,
child: SizedBox(
width: .infinity,
child: Center(child: Text("Submit")),
),
onPressed: () {
if (mounted) {
FocusScope.of(context).unfocus();
}
register();
},
),
),
],
),
),
);
}
}