api_auth_provider.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:dio/dio.dart';
  5. import 'package:flutter/cupertino.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:telnow_mobile_new/src/injector/injector.dart';
  8. import 'package:telnow_mobile_new/src/model/login/login_body.dart';
  9. import 'package:telnow_mobile_new/src/model/refreshtoken/refresh_token_body.dart';
  10. import 'package:telnow_mobile_new/src/model/token/token.dart';
  11. import 'package:telnow_mobile_new/src/layouts/components/template.dart';
  12. import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
  13. import 'package:telnow_mobile_new/src/utils/dio_logging_interceptors.dart';
  14. import 'package:telnow_mobile_new/src/utils/U.dart';
  15. import 'package:easy_localization/easy_localization.dart';
  16. import 'package:http/http.dart' as http;
  17. const String host = '';
  18. // const String host = 'bridge3.telmessenger.com';
  19. // const String host = '192.168.100.19:8080';
  20. // const String host = '192.168.100.18:8080';
  21. class ApiAuthProvider {
  22. final Dio _dio = new Dio();
  23. final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
  24. final String displayVersion = '4.0.15'; //versi aplikasi untuk di tampilkan
  25. final int currentVersion = 40; //versi aplikasi yang digunakan untuk pengecekan versi
  26. final String buildNumber = '2508.01';
  27. // final String companyName = '999';
  28. // final String _baseUrl = 'http://139.162.7.140:9090/';
  29. // final String _baseUrl = 'http://192.168.100.14:8080/'; //irma
  30. // final String _baseUrl = 'http://192.168.100.68:8080/'; //mita
  31. // final String _baseUrl = 'http://192.168.100.121:8080/'; //abi
  32. // String companyCode = '001';
  33. late String baseUrl = 'https://$host/';
  34. // final String baseUrl = 'http://$host/';
  35. final String clientId = 'inf-G52G4op8N8';
  36. final String clientSecret = '3JskYu5zxlXRDv6g';
  37. final String clientIdWeb = 'web-apHca0ncOX';
  38. final String clientSecretWeb = '1qeIwW8Wu9AF4DRF';
  39. var isDebug;
  40. ApiAuthProvider() {
  41. // print('ApiAuthProvider called');
  42. // print(U.getAccessCode());
  43. // isDebug = _sharedPreferencesManager.getBool(SharedPreferencesManager.keyIsDebug);
  44. // if (_sharedPreferencesManager
  45. // .isKeyExists(SharedPreferencesManager.keyAccessCode)) {
  46. // _dio.options.baseUrl = baseUrl + U.decryptAESCryptoJS(U.getAccessCode(), U.passphrase);
  47. // // _dio.options.baseUrl = baseUrl + U.getAccessCode();
  48. // _dio.interceptors.add(DioLoggingInterceptors(_dio));
  49. // }
  50. init();
  51. }
  52. init(){
  53. // print('ApiAuthProvider called');
  54. // print("U.getAccessCode() ==> ${U.getAccessCode()}");
  55. isDebug = _sharedPreferencesManager.getBool(SharedPreferencesManager.keyIsDebug);
  56. if (_sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyAccessCode)! && _sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyBaseUrl)!) {
  57. baseUrl = U.decodeBase64Url(U.getBaseUrl()!);
  58. _dio.options.baseUrl = baseUrl + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!));
  59. // _dio.options.baseUrl = baseUrl + U.getAccessCode();
  60. _dio.interceptors.add(DioLoggingInterceptors(_dio));
  61. }
  62. }
  63. Future<Token> loginUser(LoginBody loginBody) async {
  64. try {
  65. // print("======base url==========");
  66. // print(baseUrl + U.decryptAESCryptoJS(U.getAccessCode(), U.passphrase));
  67. var loginData = loginBody.toJson();
  68. var strData = "";
  69. var i = 0;
  70. loginData.forEach((key, value) {
  71. strData = strData +
  72. (i == 0 ? '' : '&') +
  73. key +
  74. '=' +
  75. Uri.encodeComponent(value);
  76. i++;
  77. });
  78. // print(strData);
  79. final response = await _dio.post('/oauth/token?' + strData,
  80. options: Options(
  81. headers: {
  82. 'Accept': 'application/json',
  83. 'Authorization': 'Basic ${base64Encode(
  84. utf8.encode('${kIsWeb?clientIdWeb:clientId}:${kIsWeb?clientSecretWeb:clientSecret}'),
  85. )}'
  86. },
  87. ));
  88. return Token.fromJson(response.data);
  89. } on DioException catch (error) {
  90. // print(error.response);
  91. if (error.response == null) {
  92. try {
  93. final result = await InternetAddress.lookup('google.com');
  94. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  95. return Token.withError('errorConnection'.tr());
  96. }
  97. } on SocketException catch (_) {
  98. return Token.withError('noInternet'.tr());
  99. }
  100. } else if (error.response?.statusCode == 400) {
  101. if (error.response?.data['error_description'] == 'User account has expired') return Token.withError('expAccount'.tr());
  102. return Token.withError('invalidLogin'.tr());
  103. } else if (error.response?.statusCode == 401) {
  104. if (error.response?.data['error_description'] ==
  105. 'Invalid phone number') {
  106. return Token.withError('invalidPhone'.tr());
  107. }
  108. return Token.withError('expAccount'.tr());
  109. } else if (error.response!.statusCode! >= 500) {
  110. return Token.withError('errorConnection'.tr());
  111. } else {
  112. return Token.withError('errorServer'.tr());
  113. }
  114. return Token.withError('$error');
  115. }
  116. }
  117. Future<Token> refreshAuth(RefreshTokenBody refreshTokenBody) async {
  118. try {
  119. // print(refreshTokenBody.toJson());
  120. var refreshData = refreshTokenBody.toJson();
  121. var strData = "";
  122. var i = 0;
  123. refreshData.forEach((key, value) {
  124. strData = strData +
  125. (i == 0 ? '' : '&') +
  126. key +
  127. '=' +
  128. Uri.encodeComponent(value);
  129. i++;
  130. });
  131. // print(strData);
  132. final response = await _dio.post(
  133. '/oauth/token?' + strData,
  134. options: Options(
  135. headers: {
  136. 'Accept': 'application/json',
  137. 'Authorization': 'Basic ${base64Encode(
  138. utf8.encode('${kIsWeb?clientIdWeb:clientId}:${kIsWeb?clientSecretWeb:clientSecret}'),
  139. )}',
  140. },
  141. ),
  142. );
  143. return Token.fromJson(response.data);
  144. } on DioException catch (error) {
  145. // print(error.response.statusCode);
  146. return Token.withError('$error');
  147. } catch(error){
  148. return Token.withError('$error');
  149. }
  150. }
  151. Future<dynamic> getJsonData(String path, var params, context,
  152. {bool secondCheck = false}) async {
  153. try {
  154. Response<String> response = await _dio.getUri(
  155. Uri(path: path, queryParameters: params),
  156. options: Options(
  157. headers: {
  158. 'Accept': 'application/json',
  159. 'requirestoken': true,
  160. },
  161. ),
  162. );
  163. return json.decode(response.data!);
  164. } on DioException catch (error) {
  165. print(error.response);
  166. if (error.response == null) {
  167. try {
  168. final result = await InternetAddress.lookup('google.com');
  169. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  170. handlingError(context, 1); //error server
  171. }
  172. } on SocketException catch (_) {
  173. // handlingError(context, ApiError.NO_INTERNET); //no internet
  174. }
  175. } else if (error.response!.statusCode! >= 500) {
  176. if (secondCheck) {
  177. print('secondCheck');
  178. handlingError(context, 2); //error connection
  179. } else {
  180. await Future.delayed(Duration(milliseconds: 200));
  181. return getData(path, params, context, secondCheck: true);
  182. }
  183. //error server
  184. } else if (error.response?.statusCode == 401) {
  185. handlingError(context, 3); //error auth
  186. } else {
  187. if (secondCheck) {
  188. print('secondCheck');
  189. handlingError(context, 2); //error connection
  190. } else {
  191. await Future.delayed(Duration(milliseconds: 200));
  192. return getData(path, params, context, secondCheck: true);
  193. }
  194. }
  195. return Future.error(error);
  196. } catch (error) {
  197. print(error.toString());
  198. handlingError(context, 1);
  199. return Future.error(error);
  200. }
  201. }
  202. Future getData(String path, var params, BuildContext context, {bool secondCheck = false}) async {
  203. try {
  204. Response<String> response = await _dio.getUri(
  205. Uri(path: path, queryParameters: params),
  206. options: Options(
  207. headers: {
  208. 'requirestoken': true,
  209. },
  210. ),
  211. );
  212. // print(response.data);
  213. return json.decode(response.data!);
  214. } on DioException catch (error) {
  215. // print(error.response!.statusCode);
  216. bool isOpen = ModalRoute.of(context)?.isCurrent != true;
  217. if (error.response == null) {
  218. try {
  219. final result = await InternetAddress.lookup('google.com');
  220. if (!isOpen && result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  221. handlingError(context, 1); //error server
  222. }
  223. } on SocketException catch (_) {
  224. // if(!isOpen) handlingError(context, 0); //no internet
  225. }
  226. } else if (!isOpen && error.response!.statusCode! >= 500) {
  227. handlingError(context, 1); //error server
  228. } else if (!isOpen && error.response?.statusCode == 401) {
  229. handlingError(context, 3); //error auth
  230. } else {
  231. if(!isOpen){
  232. if (secondCheck) {
  233. print('secondCheck');
  234. handlingError(context, 2); //error connection
  235. } else {
  236. return getData(path, params, context, secondCheck: true);
  237. }
  238. }
  239. }
  240. return null;
  241. }
  242. }
  243. Future postData(String path, var params, var data, context) async {
  244. try {
  245. Response response = await _dio.postUri(
  246. Uri(path: path, queryParameters: params),
  247. data: data,
  248. options: Options(
  249. headers: {
  250. 'Accept': 'application/json',
  251. 'requirestoken': true,
  252. },
  253. ),
  254. );
  255. return response.data;
  256. } on DioException catch (error) {
  257. print(error);
  258. if (error.response == null) {
  259. try {
  260. final result = await InternetAddress.lookup('google.com');
  261. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  262. showError(context, 'errorConnection'.tr());
  263. }
  264. } on SocketException catch (_) {
  265. showError(context, 'noInternet'.tr());
  266. }
  267. } else if (error.response!.statusCode! >= 500) {
  268. showError(context, 'errorConnection'.tr());
  269. } else if (error.response?.statusCode == 401) {
  270. handlingError(context, 3); //error auth
  271. } else if (error.response?.statusCode == 422) {
  272. if(error.response?.data['message'] == 'Worktime did not found'){
  273. showError(context, 'notFoundWorktime'.tr());
  274. } else if(error.response?.data['message'] == 'Cant send broadcast message, you have not permission.'){
  275. showError(context, 'broadcastPermission'.tr());
  276. } else if(error.response?.data['message'] == 'Cant send broadcast message, you have not permission.'){
  277. showError(context, 'broadcastPermission'.tr());
  278. } else if(error.response?.data['message'] == 'request did not match informant rights'){
  279. showError(context, 'idNotMatch'.tr().replaceAll("#ID", data['user_id']));
  280. } else if(error.response?.data['message'] == 'Informant user id not found.'){
  281. showError(context, 'idNotFound'.tr());
  282. } else if(error.response?.data['message'] == 'You are not registered as receptionist or room attendant.'){
  283. showError(context, 'informantNotRegistered'.tr());
  284. } else {
  285. showError(context, error.response?.data['message']);
  286. }
  287. } else {
  288. showError(context, 'errorServer'.tr());
  289. }
  290. return null;
  291. }
  292. }
  293. Future postDataNoAuth(String path) async {
  294. try {
  295. // print(path);
  296. Response response = await _dio.postUri(Uri(path: path));
  297. return response.data;
  298. } on DioException catch (error) {
  299. print(error.response);
  300. return null;
  301. }
  302. }
  303. Future patchData(String path, var data, context, {var params}) async {
  304. try {
  305. Response response = await _dio.patchUri(
  306. Uri(path: path, queryParameters: params),
  307. data: data,
  308. options: Options(
  309. headers: {
  310. 'Accept': 'application/json',
  311. 'requirestoken': true,
  312. },
  313. ),
  314. );
  315. return response.data;
  316. } on DioException catch (error) {
  317. if (error.response == null) {
  318. try {
  319. final result = await InternetAddress.lookup('google.com');
  320. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  321. showError(context, 'errorConnection'.tr());
  322. }
  323. } on SocketException catch (_) {
  324. showError(context, 'noInternet'.tr());
  325. }
  326. } else if (error.response!.statusCode! >= 500) {
  327. showError(context, 'errorConnection'.tr());
  328. } else if (error.response?.statusCode == 401) {
  329. handlingError(context, 3); //error auth
  330. } else if (error.response?.statusCode == 422) {
  331. if (error.response?.data['message'] == 'Old Password Not Match.') {
  332. showError(context, 'wrongOldPass'.tr());
  333. } else if (error.response?.data['message'] ==
  334. 'New password already in used.') {
  335. showError(context, 'alreadyUsePass'.tr());
  336. } else {
  337. showError(context, error.response?.data['message']);
  338. }
  339. } else {
  340. showError(context, 'errorServer'.tr());
  341. }
  342. return null;
  343. }
  344. }
  345. Future<dynamic> getJsonDataNoAuth(String path, {int n = 0}) async {
  346. // print('sini');
  347. var thisUrl = U.decodeBase64Url(U.getBaseUrl()!) + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!));
  348. // print("url : ${thisUrl + path}");
  349. try{
  350. var response = await http.get(Uri.parse(thisUrl + path)).timeout(Duration(seconds: 5));
  351. // print("data: ${response.body}");
  352. if(response.statusCode == 200){
  353. return Future.value(json.decode(response.body));
  354. }
  355. else{
  356. return Future.error(json.decode(response.body));
  357. }
  358. } on TimeoutException catch (error) {
  359. // print("err timeout men");
  360. // Fluttertoast.showToast(msg: 'invalid_bridge'.tr());
  361. return Future.error(error);
  362. } catch (error) {
  363. // print("err catch: $error");
  364. if (n < 3) {
  365. return getJsonDataNoAuth(path, n: n+1);
  366. } else {
  367. return Future.error(error);
  368. }
  369. }
  370. // try {
  371. // Response<String> response = await _dio.getUri(Uri(path: path));
  372. // return json.decode(response.data!);
  373. // } catch (error) {
  374. // if (n < 3) {
  375. // print("retry $n");
  376. // return getJsonDataNoAuth(path, n: n+1);
  377. // } else {
  378. // print("return error: after $n trial");
  379. // if (path.contains("/api/license")) {
  380. // U.clearAccessCode();
  381. // }
  382. // return Future.error(error);
  383. // }
  384. // }
  385. }
  386. Future getDataNoAuth(String path, {int n = 0}) async {
  387. try {
  388. Response<String> response = await _dio.getUri(Uri(path: path));
  389. return json.decode(response.data!);
  390. } catch (error) {
  391. // print('trien $n times!');
  392. if (n < 3) {
  393. getDataNoAuth(path, n: n+1);
  394. } else {
  395. // print("error after trial $n times: ${error.response}");
  396. return isDebug ? Future.error(error) : null;
  397. }
  398. }
  399. }
  400. Future downloadImage(String path, String savePath) async {
  401. try {
  402. var response = _dio.download(path, savePath);
  403. return response;
  404. } catch (e) {
  405. return e;
  406. }
  407. }
  408. String getServiceAsset(String key){
  409. return _dio.options.baseUrl+'/assets/lotties/$key';
  410. }
  411. }