Skip to content

Instantly share code, notes, and snippets.

@akshay2211
Created July 23, 2018 10:00
Show Gist options
  • Save akshay2211/02c0319dcfceda517c013b16b0daab16 to your computer and use it in GitHub Desktop.
Save akshay2211/02c0319dcfceda517c013b16b0daab16 to your computer and use it in GitHub Desktop.
/**
* Created by akshay on 28/8/17.
*/
public class TokenAuthenticator implements Authenticator {
private final Context c;
public TokenAuthenticator(Context c) {
this.c = c;
}
private static int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (responseCount(response) >= 2) {
// If both the original call and the call with refreshed token failed,
// it will probably keep failing, so don't try again.
return null;
}
Log.e("authenticate", "refresh_token " + response.code());
// We need a new client, since we don't want to make another call using our client with access token
TokenService tokenClient = ServiceGenerator.createService(TokenService.class);
Call<TokenModel> call = tokenClient.refreshToken(
"refresh_token",
Constants.CLIENT_SECRET,
"1",
Utility.getDefaults(Constants.TAG_REFRESH_TOKEN, c)
);
try {
retrofit2.Response<TokenModel> tmr = call.execute();
Log.e("refresh_token", "" + tmr.isSuccessful() + " " + tmr.message().toString() + " " + call);
if (tmr.code() == 200) {
// Log.e("refresh_token", "" + tmr.isSuccessful() + " " + tmr.message().toString() + " " + call);
TokenModel tm = tmr.body();
Log.e("refresh_token", "isSuccessful " + tm.getToken_type() + " " + tm.getRefresh_token() + " -------- " + tm.getExpires_in());
Utility.setDefaults(Constants.TAG_REFRESH_TOKEN, tm.getRefresh_token(), c);
Utility.setDefaults(Constants.TAG_TOKEN, tm.getAccess_token(), c);
Utility.setDefaultsLong(Constants.TAG_REFRESH_TIME, Utility.getCalculatedRefreshTime(tm.getExpires_in()));
return response.request().newBuilder()
.header("Authorization", tm.getToken_type() + " " + tm.getAccess_token())
.build();
} else {
return null;
}
} catch (IOException e) {
Log.e("Exc", String.valueOf(e.getMessage()));
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment