login.dart 29 KB

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