api_auth_provider.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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.16'; //versi aplikasi untuk di tampilkan
  25. final int currentVersion = 40; //versi aplikasi yang digunakan untuk pengecekan versi
  26. final String buildNumber = '2525.02';
  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('$clientId:$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('$clientId:$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 if(error.response?.data['message'] == 'invalid parent ticket'){
  285. showError(context, 'invalidParentTicket'.tr());
  286. } else {
  287. showError(context, error.response?.data['message']);
  288. }
  289. } else {
  290. showError(context, 'errorServer'.tr());
  291. }
  292. return null;
  293. }
  294. }
  295. Future postDataNoAuth(String path) async {
  296. try {
  297. // print(path);
  298. Response response = await _dio.postUri(Uri(path: path));
  299. return response.data;
  300. } on DioException catch (error) {
  301. print(error.response);
  302. return null;
  303. }
  304. }
  305. Future patchData(String path, var data, context, {var params}) async {
  306. try {
  307. Response response = await _dio.patchUri(
  308. Uri(path: path, queryParameters: params),
  309. data: data,
  310. options: Options(
  311. headers: {
  312. 'Accept': 'application/json',
  313. 'requirestoken': true,
  314. },
  315. ),
  316. );
  317. return response.data;
  318. } on DioException catch (error) {
  319. if (error.response == null) {
  320. try {
  321. final result = await InternetAddress.lookup('google.com');
  322. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  323. showError(context, 'errorConnection'.tr());
  324. }
  325. } on SocketException catch (_) {
  326. showError(context, 'noInternet'.tr());
  327. }
  328. } else if (error.response!.statusCode! >= 500) {
  329. showError(context, 'errorConnection'.tr());
  330. } else if (error.response?.statusCode == 401) {
  331. handlingError(context, 3); //error auth
  332. } else if (error.response?.statusCode == 422) {
  333. if (error.response?.data['message'] == 'Old Password Not Match.') {
  334. showError(context, 'wrongOldPass'.tr());
  335. } else if (error.response?.data['message'] ==
  336. 'New password already in used.') {
  337. showError(context, 'alreadyUsePass'.tr());
  338. } else {
  339. showError(context, error.response?.data['message']);
  340. }
  341. } else {
  342. showError(context, 'errorServer'.tr());
  343. }
  344. return null;
  345. }
  346. }
  347. Future<dynamic> getJsonDataNoAuth(String path, {int n = 0}) async {
  348. // print('sini');
  349. var thisUrl = U.decodeBase64Url(U.getBaseUrl()!) + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!));
  350. // print("url : ${thisUrl + path}");
  351. try{
  352. var response = await http.get(Uri.parse(thisUrl + path)).timeout(Duration(seconds: 5));
  353. // print("data: ${response.body}");
  354. if(response.statusCode == 200){
  355. return Future.value(json.decode(response.body));
  356. }
  357. else{
  358. return Future.error(json.decode(response.body));
  359. }
  360. } on TimeoutException catch (error) {
  361. // print("err timeout men");
  362. // Fluttertoast.showToast(msg: 'invalid_bridge'.tr());
  363. return Future.error(error);
  364. } catch (error) {
  365. // print("err catch: $error");
  366. if (n < 3) {
  367. return getJsonDataNoAuth(path, n: n+1);
  368. } else {
  369. return Future.error(error);
  370. }
  371. }
  372. // try {
  373. // Response<String> response = await _dio.getUri(Uri(path: path));
  374. // return json.decode(response.data!);
  375. // } catch (error) {
  376. // if (n < 3) {
  377. // print("retry $n");
  378. // return getJsonDataNoAuth(path, n: n+1);
  379. // } else {
  380. // print("return error: after $n trial");
  381. // if (path.contains("/api/license")) {
  382. // U.clearAccessCode();
  383. // }
  384. // return Future.error(error);
  385. // }
  386. // }
  387. }
  388. Future getDataNoAuth(String path, {int n = 0}) async {
  389. try {
  390. Response<String> response = await _dio.getUri(Uri(path: path));
  391. return json.decode(response.data!);
  392. } catch (error) {
  393. // print('trien $n times!');
  394. if (n < 3) {
  395. getDataNoAuth(path, n: n+1);
  396. } else {
  397. // print("error after trial $n times: ${error.response}");
  398. return isDebug ? Future.error(error) : null;
  399. }
  400. }
  401. }
  402. Future downloadImage(String path, String savePath) async {
  403. try {
  404. var response = _dio.download(path, savePath);
  405. return response;
  406. } catch (e) {
  407. return e;
  408. }
  409. }
  410. String getServiceAsset(String key){
  411. return _dio.options.baseUrl+'/assets/lotties/$key';
  412. }
  413. }