package cz.muni.ics.oauth2.model.proxied_introspection.auth;

import cz.muni.ics.oidc.exceptions.ConfigurationException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * Authentication to remote introspection endpoint using Basic Authentication.
 *
 * Configuration of providers (replace [name] part with the name defined for the endpoint):
 * <ul>
 *     <li><b>proxied_introspection.provider.[name].username</b> - username (non-blank string)</li>
 *     <li><b>proxied_introspection.provider.[name].password</b> - password (can be blank)</li>
 * </ul>
 *
 * @see cz.muni.ics.oauth2.model.proxied_introspection.ProxiedIntrospectionEndpoint
 *
 * @author Dominik Frantisek Bucik <bucik@ics.muni.cz>
 */
public class BasicAuthProxiedIntrospectionAuthMethod implements ProxiedIntrospectionEndpointAuthMethod {

    public static final String USERNAME = ".username";

    public static final String PASSWORD = ".password";

    public final BasicAuthenticationInterceptor interceptor;

    public BasicAuthProxiedIntrospectionAuthMethod(String propertyBase, Properties properties) {
        String username = properties.getProperty(propertyBase + USERNAME, "");
        if (!StringUtils.hasText(username)) {
            throw new ConfigurationException("No username configured");
        }
        String password = properties.getProperty(propertyBase + PASSWORD, "");
        this.interceptor = new BasicAuthenticationInterceptor(username, password);
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        return interceptor.intercept(request, body, execution);
    }
}
