Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
4
Indexable
Never
package com.example.agricarbonuk.auth;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.agricarbonuk.LoginActivity;
import com.example.agricarbonuk.MyAmplifyApplication;
import com.example.agricarbonuk.utils.UserSession;

import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;


/**
 * This class is a custom authenticator class for an
 * authenticated API call. Whenever an Authenticated API call receives
 * 401 - Unauthorized response, the authenticate method is called by okhttp.
 * In this custom class, we override the authenticate method and have added
 * AuthService.refreshToken call which in turn makes a /user/login call to
 * get a fresh token.
 */
public class TokenAuthenticator implements Authenticator {

    private Context applicationContext;

    public TokenAuthenticator(Context applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Nullable
    @Override
    public Request authenticate(@Nullable Route route,
                                @NonNull Response response) {

        if(isLoginRequest(response.request()))
        {
            redirectToLoginActivity();
        }
        AuthService.refreshToken(UserSession.getInstance().getCredentials());
        return response.request().newBuilder()
                .header("Authorization", AuthService.getToken())
                .build();

    }
    private boolean isLoginRequest(Request request) {
        return request.url().encodedPath().endsWith("/login");
    }

    private void redirectToLoginActivity() {
        Intent loginIntent = new Intent(applicationContext, LoginActivity.class);
        applicationContext.startActivity(loginIntent);
    }
}