Skip to content

Instantly share code, notes, and snippets.

@naimurhasan
Created June 24, 2021 06:52
Show Gist options
  • Save naimurhasan/bb496ffbec734ab8b80028d3df4be067 to your computer and use it in GitHub Desktop.
Save naimurhasan/bb496ffbec734ab8b80028d3df4be067 to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:jobsolution/src/logics/service/lecture_note/lecture_note_api_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
/****************
*
* MENU
* 01. Constants
* 02. sendGetReqWithAuth
* 03. MAuthorizedResponse Class
* 04. refreshToken
* 05. sendPostReqWithAuth
*/
// constants
final String successStr = 'success';
final String notLoggedInStr = 'You are not logged in';
final String noInternet = 'No Internet!';
// sendGetReqWithAuth
Future<MAuthorizedResponse> sendGetReqWithAuth(String url, {expectedStatusCode = 200}) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
String accessT = prefs.get("key");
// await prefs.setString("key", "oops");
// print(accessT);
// return null;
http.Response response;
if(accessT == null) return MAuthorizedResponse(false, notLoggedInStr, 401, null);
print("Sending request in : $url");
// first trial
try{
response = await http.get(Uri.parse(url), headers: {'Authorization': 'Bearer $accessT'});
}catch (e){
print('First Trial Error');
print(e);
return MAuthorizedResponse(false, noInternet, null, null);
}
print('First Trial Response');
print(response.statusCode);
print(response.body);
// if request success
if(response.statusCode == expectedStatusCode){
print('First Trial Success');
final data = json.decode(utf8.decode(response.bodyBytes));
return MAuthorizedResponse(true, null, response.statusCode, data);
}
// if still not success refresh token
bool isRefreshSuccess = await refreshToken();
if(isRefreshSuccess){
// start second trial
accessT = prefs.get("key");
print("access key $accessT");
try{
response = await http.get(Uri.parse(url), headers: {'Authorization': 'Bearer $accessT'});
}catch (e){
print('second Trial Error');
print(e);
return MAuthorizedResponse(false, noInternet, null, null);
}
print('Second Trial Response');
print(response.statusCode);
print(response.body);
// if second request success
if(response.statusCode == expectedStatusCode){
print('Second Trial Success');
final data = json.decode(utf8.decode(response.bodyBytes));
return MAuthorizedResponse(true, null, response.statusCode, data);
}
}else{
//token refresh failed probably not logged in
return MAuthorizedResponse(false, notLoggedInStr, 401, null);
}
print('http authorized request end');
return MAuthorizedResponse(false, notLoggedInStr, 401, null);
}
// MAuthorizedResponse
class MAuthorizedResponse{
bool success;
String message;
int httpResponseStatusCode;
dynamic httpResponseBody;
MAuthorizedResponse(this.success, this.message, this.httpResponseStatusCode, this.httpResponseBody);
}
// refreshToken
Future<bool> refreshToken() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
String refreshT = prefs.get("Rkey");
if (refreshT == null) return false;
http.Response response;
try{
print("refreshing");
response = await http.post(Uri.parse(ApiRefreshURL), body: {
"refresh" : "$refreshT"
});
}catch (e){
print('refresh token caught error');
print(e);
return false;
}
// returning refresh (true) success only when success
if(response.statusCode == 200){
print('refresh success');
final data = json.decode(response.body);
prefs.setString("key", data['access']);
prefs.setString("Rkey", data['refresh']);
return true;
}
return false;
}
// sendPostReqWithAuth
Future<MAuthorizedResponse> sendPostReqWithAuth(String url, {@required Map postBody, expectedStatusCode = 201}) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
String accessT = prefs.get("key");
// await prefs.setString("key", "oops");
// print(accessT);
// return null;
http.Response response;
if(accessT == null) return MAuthorizedResponse(false, notLoggedInStr, 401, null);
print("Sending request in : $url");
// first trial
try{
response = await http.post(Uri.parse(url), body: postBody, headers: {'Authorization': 'Bearer $accessT'});
}catch (e){
print('First Trial Error');
print(e);
return MAuthorizedResponse(false, noInternet, null, null);
}
print('First Trial Response');
print(response.statusCode);
print(response.body);
// if request success
if(response.statusCode == expectedStatusCode){
print('First Trial Success');
final data = json.decode(utf8.decode(response.bodyBytes));
return MAuthorizedResponse(true, null, response.statusCode, data);
}
// if still not success refresh token
bool isRefreshSuccess = await refreshToken();
if(isRefreshSuccess){
// start second trial
accessT = prefs.get("key");
print("access key $accessT");
try{
response = await http.post(Uri.parse(url), body: postBody, headers: {'Authorization': 'Bearer $accessT'});
}catch (e){
print('second Trial Error');
print(e);
return MAuthorizedResponse(false, noInternet, null, null);
}
print('Second Trial Response');
print(response.statusCode);
print(response.body);
// if second request success
if(response.statusCode == expectedStatusCode){
print('Second Trial Success');
final data = json.decode(utf8.decode(response.bodyBytes));
return MAuthorizedResponse(true, null, response.statusCode, data);
}
}else{
//token refresh failed probably not logged in
return MAuthorizedResponse(false, notLoggedInStr, 401, null);
}
print('http authorized request end');
return MAuthorizedResponse(false, notLoggedInStr, 401, null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment