package runtime;
import java.util.function.Supplier;
import okhttp3.Request;
public class ApiKeyAuth implements Authenticator {
private final String key;
private final Supplier<String> keyProvider;
private final String name;
private final ApiKeyLocation location;
public ApiKeyAuth(String key, String name, ApiKeyLocation location) {
this.key = key;
this.keyProvider = null;
this.name = name;
this.location = location;
}
public ApiKeyAuth(Supplier<String> keyProvider, String name, ApiKeyLocation location) {
this.key = null;
this.keyProvider = keyProvider;
this.name = name;
this.location = location;
}
@Override
public void authenticate(Request.Builder builder) {
String k = keyProvider != null ? keyProvider.get() : key;
if (location == ApiKeyLocation.HEADER) {
builder.header(name, k);
} else if (location == ApiKeyLocation.QUERY) {
builder.url(builder.build().url().newBuilder()
.addQueryParameter(name, k)
.build());
}
}
}