login.dart 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. import 'dart:convert';
  2. import 'package:auto_route/auto_route.dart';
  3. import 'package:cached_network_image/cached_network_image.dart';
  4. import 'package:easy_localization/easy_localization.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  8. import 'package:jwt_decoder/jwt_decoder.dart';
  9. import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
  10. import 'package:telnow_mobile_new/src/api/api_auth_repository.dart';
  11. import 'package:telnow_mobile_new/src/api/jwt_token.dart';
  12. import 'package:telnow_mobile_new/src/injector/injector.dart';
  13. import 'package:telnow_mobile_new/src/layouts/components/template.dart';
  14. import 'package:telnow_mobile_new/src/model/login/login_body.dart';
  15. import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
  16. import 'package:telnow_mobile_new/src/utils/C.dart';
  17. import 'package:telnow_mobile_new/src/utils/U.dart';
  18. import 'package:telnow_mobile_new/src/utils/ui_service.dart';
  19. import 'package:telnow_mobile_new/src/utils/cache_manager.dart';
  20. import 'package:toggle_switch/toggle_switch.dart';
  21. import 'package:url_launcher/url_launcher.dart';
  22. import 'package:telnow_mobile_new/src/model/token/token.dart';
  23. @RoutePage()
  24. class LoginPage extends StatefulWidget {
  25. const LoginPage({super.key});
  26. @override
  27. State<LoginPage> createState() => _LoginPageState();
  28. }
  29. class _LoginPageState extends State<LoginPage> {
  30. final JwtToken token = JwtToken();
  31. final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  32. final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  33. final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();
  34. String companyName = '';
  35. String serialNumber = '';
  36. String companyLogo = '';
  37. bool loading = false;
  38. String username = '';
  39. String password = '';
  40. String imageUrl = '';
  41. List lang = [];
  42. @override
  43. void initState() {
  44. try{
  45. imageUrl = '${apiAuthProvider.baseUrl}${U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))}/assets/background/tn';
  46. }catch(e){
  47. debugPrint(e.toString());
  48. }
  49. U.getServerVersion();
  50. getCompanyName();
  51. // TODO: implement initState
  52. super.initState();
  53. }
  54. getCompanyName() async {
  55. var lics = await U.reloadLicense();
  56. if (lics != null) {
  57. companyName = lics['companyName']??'';
  58. serialNumber = lics['serialNumber']??'';
  59. companyLogo = lics['logo']??'';
  60. if(await U.isCompatibleWith(VersionKey.multiBahasa)){
  61. lang = lics['_validLang'] ?? [];
  62. } else if(1698720817 <= lics['serverVersion']){
  63. lang = lics['languages'] != null ? lics['languages'].split(',') : [];
  64. }
  65. if(mounted) setState(() {});
  66. }
  67. }
  68. @override
  69. Widget build(BuildContext context) {
  70. return Scaffold(
  71. resizeToAvoidBottomInset: false,
  72. body: Stack(
  73. children: [
  74. SizedBox(
  75. width: double.infinity, height: double.infinity,
  76. child: Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, height: double.infinity, errorBuilder: (context, error, stackTrace) {
  77. return Image.asset('assets/image/background/background.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity);
  78. }),
  79. ),
  80. SingleChildScrollView(
  81. child: Container(
  82. padding: EdgeInsets.all(16),
  83. width: MediaQuery.of(context).size.width,
  84. height: kIsWeb && MediaQuery.of(context).size.height<820 ? 820 : MediaQuery.of(context).size.height,
  85. decoration: BoxDecoration(gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [primaryColor.withValues(alpha: 0.50), Colors.black.withValues(alpha: 0.91)])),
  86. child: SafeArea(
  87. child: Column(
  88. children: [
  89. Container(
  90. padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
  91. // height: 90,
  92. child: Row(
  93. crossAxisAlignment: CrossAxisAlignment.center,
  94. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  95. // padding: EdgeInsets.symmetric(horizontal: 16),
  96. children: [
  97. backButton(),
  98. langWidget()
  99. ],
  100. ),
  101. ),
  102. Image.asset('assets/image/logo/logo.png', height: companyLogo.isNotEmpty?25:40),
  103. companyLogo.isNotEmpty?Container(
  104. margin: EdgeInsets.only(top: 30, bottom: 40),
  105. width: 160, height: 160,
  106. decoration: BoxDecoration(
  107. borderRadius: BorderRadius.all(Radius.circular(80)),
  108. image: DecorationImage(image: CachedNetworkImageProvider('$companyLogo?bridge-cache=true', cacheManager: CacheManager(CacheMan.config(companyLogo))), fit: BoxFit.cover)
  109. ),
  110. ):SizedBox(height: 115),
  111. Expanded(
  112. child: Column(
  113. mainAxisAlignment: MainAxisAlignment.start,
  114. children: [
  115. Container(
  116. alignment: Alignment.topCenter,
  117. width: U.bodyWidth(context),
  118. child: Column(
  119. children: [
  120. loginFieldTemplate(placeholder: 'userId'.tr(), value: username, action: (val)=>username = val, submit: (val)=>loginAction()),
  121. SizedBox(height: 12),
  122. loginFieldTemplate(placeholder: 'password'.tr(), value: password, action: (val)=>password = val, isPassword: true, submit: (val)=>loginAction()),
  123. GestureDetector(
  124. child: Container(
  125. width: double.infinity,
  126. margin: EdgeInsets.only(top: 40, bottom: 20),
  127. padding: EdgeInsets.symmetric(vertical: 16),
  128. decoration: BoxDecoration(
  129. color: primaryColor.withValues(alpha: 0.50),
  130. border: Border.all(color: Colors.white),
  131. borderRadius: BorderRadius.all(Radius.circular(12))
  132. ),
  133. child: !loading ? Text('buttonLogin'.tr(), style: TextStyle(color: Colors.white, fontSize: 17), textAlign: TextAlign.center):Center(
  134. child: SizedBox(
  135. width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white),
  136. ),
  137. ),
  138. ),
  139. onTap: ()=>loginAction(),
  140. ),
  141. ],
  142. ),
  143. ),
  144. companyName.isNotEmpty?Text(companyName, style: TextStyle(fontSize: 16, color: Colors.white), textAlign: TextAlign.center):Container(),
  145. SizedBox(height: companyName.isNotEmpty?5:0),
  146. serialNumber.isNotEmpty?Text('${'serialNumber'.tr()} $serialNumber', style: TextStyle(color: Colors.white, fontSize: 14)):Container(),
  147. ],
  148. ),
  149. ),
  150. Container(
  151. margin: EdgeInsets.only(top: 20, bottom: 5),
  152. alignment: Alignment.bottomCenter,
  153. child: GestureDetector(
  154. child: Text('policy'.tr(), style: TextStyle(color: Colors.white, fontSize: 14, decoration: TextDecoration.underline)),
  155. onTap: () async {
  156. Uri url = Uri.parse('https://telmessenger.com/privacy-police/telnow.html');
  157. await canLaunchUrl(url) ? await launchUrl(url) : debugPrint('Could not launch $url');
  158. },
  159. ),
  160. ),
  161. Text('${'version'.tr()} ${ApiAuthProvider().displayVersion}', style: TextStyle(color: Colors.white, fontSize: 14)),
  162. SizedBox(height: 5),
  163. Text('Build ${ApiAuthProvider().buildNumber}', style: TextStyle(color: Colors.white, fontSize: 13)),
  164. ],
  165. ),
  166. ),
  167. ),
  168. ),
  169. ],
  170. ),
  171. );
  172. }
  173. Widget backButton(){
  174. return GestureDetector(
  175. child: Row(
  176. children: [
  177. U.iconsax('arrow-left', color: Colors.white),
  178. SizedBox(width: 15),
  179. Column(
  180. crossAxisAlignment: CrossAxisAlignment.start,
  181. children: [
  182. Text('buttonBack'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500)),
  183. Text('buttonScan'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500)),
  184. ],
  185. )
  186. ],
  187. ),
  188. onTap: (){
  189. context.router.removeLast();
  190. context.navigateToPath('/qr?new=true');
  191. },
  192. );
  193. }
  194. Widget langWidget(){
  195. return Center(
  196. child: Container(
  197. margin: EdgeInsets.only(right: 16),
  198. child: Align(
  199. alignment: Alignment.topRight,
  200. child: lang.isNotEmpty ? GestureDetector(
  201. child: Container(
  202. width: 65, height: 30, padding: EdgeInsets.symmetric(horizontal: 10),
  203. decoration: BoxDecoration(
  204. color: Colors.deepOrange,
  205. borderRadius: BorderRadius.all(Radius.circular(50))
  206. ),
  207. child: Row(
  208. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  209. children: [
  210. U.iconsax('bold/global', color: Colors.white),
  211. Text(context.locale.toString().toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold))
  212. ],
  213. ),
  214. ),
  215. onTap: () => changeLangLogin(context, lang),
  216. ) : ToggleSwitch(
  217. minWidth: 40,
  218. minHeight: 30,
  219. cornerRadius: 20,
  220. initialLabelIndex: context.locale.toString() == 'en' ? 0 : 1,
  221. activeBgColor: [Colors.deepOrange],
  222. activeFgColor: Colors.white,
  223. inactiveBgColor: Colors.white54,
  224. inactiveFgColor: Colors.white,
  225. labels: ['EN', 'ID'],
  226. onToggle: (index) {
  227. if (index == 0) {
  228. context.setLocale(Locale('en'));
  229. } else {
  230. context.setLocale(Locale('id'));
  231. }
  232. },
  233. ),
  234. ),
  235. ),
  236. );
  237. }
  238. loginAction() async{
  239. final languageTag = context.locale.toLanguageTag();
  240. if(!loading){
  241. setState(()=>loading = true);
  242. String errMsg = '';
  243. if (password.isEmpty) {
  244. errMsg = 'passwordEmpty'.tr();
  245. } else if (username.isEmpty) {
  246. errMsg = 'userEmpty'.tr();
  247. }
  248. if (errMsg.isNotEmpty) {
  249. UIService.showError(errMsg);
  250. // showError(context, errMsg);
  251. setState(()=>loading = false);
  252. return;
  253. }
  254. Token token = await apiAuthRepository.postLoginUser(LoginBody(username.trim(), password.trim(), "password"));
  255. if (token.error != null) {
  256. UIService.showError(token.error.toString());
  257. setState(()=>loading = false);
  258. return;
  259. }
  260. var pid = U.getPidFromUrl(UIService.getCurrentUrl());
  261. await sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessToken, token.accessToken!);
  262. await sharedPreferencesManager.putString(SharedPreferencesManager.keyRefreshToken, token.refreshToken!);
  263. var accTkn = JwtDecoder.decode(token.accessToken!);
  264. switchLang(languageTag, accTkn);
  265. if(await setUsername() && mounted){
  266. var data = {
  267. 'username': username.trim(),
  268. 'password': password.trim()
  269. };
  270. Navigator.push(
  271. context,
  272. MaterialPageRoute(builder: (_) => ForceChgPassPage(data: data)),
  273. ).then((_) async {
  274. if (!U.getChangedPassword()) {
  275. await U.clearPreferences();
  276. U.setHidePayload(true);
  277. UIService.navigateNamed("/app/$pid/menu");
  278. }
  279. });
  280. } else {
  281. await sharedPreferencesManager.putBool(SharedPreferencesManager.keyIsLogin, true);
  282. await sharedPreferencesManager.putString(SharedPreferencesManager.keyScoope, 'INSIDE');
  283. await sharedPreferencesManager.putInt(SharedPreferencesManager.keyCountRefreshToken, 0);
  284. await sharedPreferencesManager.putString(SharedPreferencesManager.keyPendingData, jsonEncode([]));
  285. U.setHidePayload(true);
  286. UIService.navigateNamed("/app/$pid/menu");
  287. // context.router.removeLast();
  288. // context.navigateToPath("/app/$pid/menu");
  289. }
  290. }
  291. }
  292. switchLang(code, tkn) async {
  293. // final ctx = UIService.context;
  294. // if(ctx == null) return;
  295. var lg = code.toUpperCase();
  296. if(lang.indexOf(code) > 1){
  297. lg = lang.indexOf(code) - 1;
  298. }
  299. Map<String, dynamic> p;
  300. if(U.newServerVersion(1754624839)){
  301. p = {
  302. 'userId': tkn['user_name'].toString().replaceFirst('inf-', ""),
  303. 'language': 'ID',
  304. '_language': lg
  305. };
  306. } else {
  307. p = {
  308. 'userId': tkn['user_name'].toString().replaceFirst('inf-', ""),
  309. 'language': lg
  310. };
  311. }
  312. try{
  313. var res = await apiAuthProvider.patchData('/api/informants/${tkn['userId']}', p);
  314. if (res != null) {
  315. // print("res $res");
  316. // context.setLocale(Locale(code));
  317. }
  318. }catch(e){
  319. debugPrint(e.toString());
  320. }
  321. }
  322. setUsername() async {
  323. try{
  324. String? accessToken = sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessToken);
  325. var jwt = token.parseJwtPayLoad(accessToken!);
  326. await sharedPreferencesManager.putString(SharedPreferencesManager.keyUsername, jwt['user_name'].substring(4));
  327. await U.setChangedPassword(false);
  328. return jwt['forceChgPass'];
  329. } catch(e) {
  330. debugPrint(e.toString());
  331. }
  332. }
  333. }
  334. var lg = {
  335. "ja": {
  336. "text": 'japanese'
  337. }, "zh": {
  338. "text": 'chinese'
  339. }, "ko": {
  340. "text": 'korean'
  341. }, "ar": {
  342. "text": 'arabic'
  343. }, "fr": {
  344. "text": 'france'
  345. }, "de": {
  346. "text": 'german'
  347. }, "nl": {
  348. "text": 'dutch'
  349. }, "hi": {
  350. "text": 'hindi'
  351. }
  352. };
  353. changeLangLogin(BuildContext context, List lang){
  354. showModalBottomSheet(
  355. context: context,
  356. backgroundColor: Colors.white,
  357. builder: (BuildContext context) {
  358. return SafeArea(
  359. child: Column(
  360. mainAxisSize: MainAxisSize.min,
  361. children: <Widget>[
  362. Padding(
  363. padding: EdgeInsets.symmetric(vertical: 16),
  364. child: Center(
  365. child: Text('chooseLanguage'.tr(), style: TextStyle(color: textColor)),
  366. ),
  367. ),
  368. divider(),
  369. SizedBox(height: 16),
  370. Column(
  371. crossAxisAlignment: CrossAxisAlignment.start,
  372. children: [
  373. ListTile(
  374. title: Text('bahasa'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
  375. trailing: Icon(context.locale.toString()=='id'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
  376. onTap: context.locale.toString() != 'id' ? () async {
  377. Navigator.of(context).pop();
  378. context.setLocale(Locale('id'));
  379. } : null,
  380. ),
  381. ListTile(
  382. title: Text('english'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
  383. trailing: Icon(context.locale.toString()=='en'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
  384. onTap: context.locale.toString() != 'en' ? () async {
  385. Navigator.of(context).pop();
  386. context.setLocale(Locale('en'));
  387. } : null,
  388. ),
  389. lang.length - 1 > 1 ? ListTile(
  390. title: Text(lg[lang[2]]!['text'].toString().tr(), style: TextStyle(color: textColor, fontSize: 14)),
  391. trailing: Icon(context.locale.toString()==lang[2] ? Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
  392. onTap: context.locale.toString() != lang[2] ? () async {
  393. Navigator.of(context).pop();
  394. context.setLocale(Locale(lang[2]));
  395. } : null,
  396. ) : SizedBox(),
  397. lang.length - 1 > 2 ? ListTile(
  398. title: Text(lg[lang[3]]!['text'].toString().tr(), style: TextStyle(color: textColor, fontSize: 14)),
  399. trailing: Icon(context.locale.toString()==lang[3] ? Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
  400. onTap: context.locale.toString() != lang[3] ? () async {
  401. Navigator.of(context).pop();
  402. context.setLocale(Locale(lang[3]));
  403. } : null,
  404. ) : SizedBox(),
  405. lang.length - 1 > 3 ? ListTile(
  406. title: Text(lg[lang[4]]!['text'].toString().tr(), style: TextStyle(color: textColor, fontSize: 14)),
  407. trailing: Icon(context.locale.toString()==lang[4] ? Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
  408. onTap: context.locale.toString() != lang[4] ? () async {
  409. Navigator.of(context).pop();
  410. context.setLocale(Locale(lang[4]));
  411. } : null,
  412. ) : SizedBox(),
  413. ],
  414. ),
  415. SizedBox(height: 16)
  416. ],
  417. ),
  418. );
  419. }
  420. );
  421. }
  422. //------------------------------------------------------------------------------
  423. class ForceChgPassPage extends StatefulWidget {
  424. final Map<String, String> data;
  425. const ForceChgPassPage({required this.data, super.key});
  426. @override
  427. State<ForceChgPassPage> createState() => _ForceChgPassPageState();
  428. }
  429. class _ForceChgPassPageState extends State<ForceChgPassPage> {
  430. final JwtToken token = JwtToken();
  431. final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  432. final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  433. final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();
  434. Map<String, dynamic> tokenData = {};
  435. String companyName = '';
  436. String serialNumber = '';
  437. String guestName = '';
  438. bool loading = false;
  439. String imageUrl = '';
  440. String newPassword = '';
  441. String confirmPassword = '';
  442. @override
  443. void initState() {
  444. try{
  445. imageUrl = '${apiAuthProvider.baseUrl}${U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))}/assets/background/tn';
  446. }catch(e){
  447. debugPrint(e.toString());
  448. }
  449. getTokenData();
  450. getCompanyName();
  451. // TODO: implement initState
  452. super.initState();
  453. }
  454. getTokenData() async {
  455. String accessToken = sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessToken)!;
  456. var jwt = token.parseJwtPayLoad(accessToken);
  457. var user = await apiAuthProvider.getData('/api/informants/${jwt['userId']}', null);
  458. if(user!=null){
  459. setState((){
  460. tokenData = jwt;
  461. context.setLocale(Locale(tokenData['language'].toLowerCase()));
  462. guestName = user['guestName'];
  463. });
  464. }
  465. }
  466. getCompanyName() async {
  467. var license = await U.reloadLicense();
  468. if (license != null && mounted) {
  469. setState(() {
  470. companyName = license['companyName']??'';
  471. serialNumber = license['serialNumber']??'';
  472. });
  473. }
  474. }
  475. @override
  476. Widget build(BuildContext context) {
  477. return WillPopScope(
  478. onWillPop: (){
  479. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyAccessToken);
  480. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyRefreshToken);
  481. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyUsername);
  482. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyIsLogin);
  483. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyScoope);
  484. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyMenuDisplay);
  485. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyAutoTranslate);
  486. sharedPreferencesManager.clearKey(SharedPreferencesManager.keyPendingData);
  487. navigateBack(context);
  488. return Future.value(true);
  489. },
  490. child: Scaffold(
  491. resizeToAvoidBottomInset: false,
  492. body: Stack(
  493. children: [
  494. SizedBox(
  495. width: double.infinity, height: double.infinity,
  496. child: Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, height: double.infinity, errorBuilder: (context, error, stackTrace) {
  497. return Image.asset('assets/image/background/background.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity);
  498. }),
  499. ),
  500. Container(
  501. width: MediaQuery.of(context).size.width,
  502. height: MediaQuery.of(context).size.height,
  503. decoration: BoxDecoration(
  504. gradient: LinearGradient(
  505. begin: Alignment.topCenter, end: Alignment.bottomCenter,
  506. colors: [
  507. primaryColor.withValues(alpha: 0.50), Colors.black.withValues(alpha: 0.91)
  508. ]
  509. )
  510. ),
  511. child: SingleChildScrollView(
  512. padding: EdgeInsets.fromLTRB(16, 50, 16, 16),
  513. child: Column(
  514. crossAxisAlignment: CrossAxisAlignment.center,
  515. children: [
  516. Container(
  517. margin: EdgeInsets.only(bottom: 100),
  518. child: Row(
  519. children: [
  520. GestureDetector(
  521. child: U.iconsax('arrow-left', color: Colors.white),
  522. onTap: (){
  523. context.router.removeLast();
  524. context.navigateToPath('/qr?new=true');
  525. },
  526. ),
  527. SizedBox(width: 15),
  528. Expanded(
  529. child: GestureDetector(
  530. child: Column(
  531. crossAxisAlignment: CrossAxisAlignment.start,
  532. children: [
  533. Text('buttonBack'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500)),
  534. Text('buttonScan'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500)),
  535. ],
  536. ),
  537. onTap: (){
  538. context.router.removeLast();
  539. context.navigateToPath('/qr?new=true');
  540. },
  541. ),
  542. ),
  543. Image.asset('assets/image/logo/logo.png', width: 120)
  544. ],
  545. )
  546. ),
  547. Column(
  548. children: [
  549. Text('${'welcome'.tr()} $guestName', style: TextStyle(color: Colors.white, fontSize: 16), textAlign: TextAlign.center),
  550. SizedBox(height: 16),
  551. Text('createNewPassText'.tr(), style: TextStyle(color: Colors.white, fontSize: 16), textAlign: TextAlign.center),
  552. ],
  553. ),
  554. SizedBox(height: 80),
  555. Container(
  556. alignment: Alignment.topCenter,
  557. width: U.bodyWidth(context),
  558. child: Column(
  559. children: [
  560. loginFieldTemplate(placeholder: 'newPassword'.tr(), value: newPassword, action: (val)=>newPassword = val, isPassword: true, submit: (val)=>loginAction()),
  561. SizedBox(height: 12),
  562. loginFieldTemplate(placeholder: 'confirmPassword'.tr(), value: confirmPassword, action: (val)=>confirmPassword = val, isPassword: true, submit: (val)=>loginAction()),
  563. GestureDetector(
  564. child: Container(
  565. width: double.infinity,
  566. margin: EdgeInsets.only(top: 40, bottom: 20),
  567. padding: EdgeInsets.symmetric(vertical: 16),
  568. decoration: BoxDecoration(
  569. color: primaryColor.withValues(alpha: 0.50),
  570. border: Border.all(color: Colors.white),
  571. borderRadius: BorderRadius.all(Radius.circular(12))
  572. ),
  573. child: !loading?Text('buttonLogin'.tr(), style: TextStyle(color: Colors.white, fontSize: 17), textAlign: TextAlign.center):Center(
  574. child: SizedBox(
  575. width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white),
  576. ),
  577. ),
  578. ),
  579. onTap: ()=>loginAction(),
  580. ),
  581. ],
  582. ),
  583. ),
  584. companyName.isNotEmpty?Text(companyName, style: TextStyle(fontSize: 16, color: Colors.white), textAlign: TextAlign.center):Container(),
  585. SizedBox(height: companyName.isNotEmpty?5:0),
  586. serialNumber.isNotEmpty?Text('${'serialNumber'.tr()} $serialNumber', style: TextStyle(color: Colors.white, fontSize: 14)):Container(),
  587. Container(
  588. margin: const EdgeInsets.only(top: 145),
  589. alignment: Alignment.bottomCenter,
  590. child: Text('${'version'.tr()} ${ApiAuthProvider().displayVersion}', style: TextStyle(color: Colors.white, fontSize: 14))
  591. ),
  592. ],
  593. ),
  594. ),
  595. ),
  596. ],
  597. ),
  598. ),
  599. );
  600. }
  601. loginAction() async{
  602. if(!loading){
  603. if(newPassword.isNotEmpty && confirmPassword.isNotEmpty){
  604. if(newPassword.trim() == confirmPassword.trim()){
  605. setState(()=>loading = true);
  606. var data = {'oldPassword': widget.data['password'], 'password': newPassword.trim()};
  607. try {
  608. var res = await apiAuthProvider.patchData('/api/informants/${tokenData['userId']}/changePassword', data);
  609. if (res != null) {
  610. String password = tokenData['related'] && tokenData['tenantCode'] != null && tokenData['tenantCode'] != '' ? tokenData['tenantCode'] + ' ${data['password']}' : data['password'];
  611. LoginBody loginBody = LoginBody(widget.data['username']!, password, 'password');
  612. Token token = await apiAuthRepository.postLoginUser(loginBody);
  613. if (token.error != null) {
  614. setState(()=>loading = false);
  615. UIService.showError(token.error.toString());
  616. // showError(context, token.error);
  617. } else {
  618. await U.setChangedPassword(true);
  619. var parsedToken = U.token.parseJwtPayLoad(token.accessToken!);
  620. await sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessToken, token.accessToken!);
  621. await sharedPreferencesManager.putString(SharedPreferencesManager.keyRefreshToken, token.refreshToken!);
  622. await sharedPreferencesManager.putString(SharedPreferencesManager.keyUsername, tokenData['related'] ? parsedToken['user_name'].split("-").last : widget.data['username']);
  623. await sharedPreferencesManager.putBool(SharedPreferencesManager.keyIsLogin, true);
  624. await sharedPreferencesManager.putString(SharedPreferencesManager.keyScoope, 'INSIDE');
  625. await sharedPreferencesManager.putInt(SharedPreferencesManager.keyCountRefreshToken, 0);
  626. await sharedPreferencesManager.putString(SharedPreferencesManager.keyPendingData, jsonEncode([]));
  627. U.setHidePayload(true);
  628. // var pid = U.getAccessCode();
  629. var pid = U.getPidFromUrl(UIService.getCurrentUrl());
  630. UIService.navigateNamed("/app/$pid/menu");
  631. // context.router.removeLast();
  632. // context.navigateToPath("/app/$pid/menu");
  633. }
  634. }
  635. } catch(e) {
  636. debugPrint(e.toString());
  637. setState(()=>loading = false);
  638. }
  639. }
  640. else{
  641. showError(context, 'checkNewPass'.tr());
  642. }
  643. }
  644. else{
  645. debugPrint("Mbuh");
  646. UIService.showError('cannotEmpty'.tr());
  647. // showError(context, 'cannotEmpty'.tr());
  648. }
  649. }
  650. }
  651. }