/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-impl
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.auth.basic.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.common.util.Base64Exception;
import org.apache.cxf.common.util.Base64Utility;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.security.AuthenticationException;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.Headers;
import ru.entaxy.esb.system.auth.basic.jpa.api.BasicAuthService;
import ru.entaxy.esb.system.common.util.SystemHeadersConstants;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class AuthenticationInterceptor extends AbstractPhaseInterceptor<Message> {

    private static final Log LOG = LogFactory.getLog(AuthenticationInterceptor.class);

    private boolean enabled = false;
    private BasicAuthService basicAuthService;

    private static final String BASIC = "Basic";
    private static final String AUTHORIZATION = "Authorization";
    private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
    private static final String WWW_AUTHENTICATE_MESSAGE = "Basic realm=\"Access to Entaxy\"";


    public AuthenticationInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        LOG.debug("AuthenticationInterceptor enabled=" + enabled);
        if (!enabled) {
            return;
        }


        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);
        //reset passed value
        headers.put(SystemHeadersConstants.HEADER_USER_LOGIN, Collections.emptyList());

        Optional<String> auth = Optional.ofNullable(headers.get(AUTHORIZATION)).
                orElse(Collections.emptyList())
                .stream().findFirst();

        Optional<String> isDisplayServiceSchema = Optional.ofNullable(headers.get(SystemHeadersConstants.HEADER_IS_DISPLAY_SERVICE_SERVICE)).
                orElse(Collections.emptyList())
                .stream().findFirst();

        if (isDisplayServiceSchema.isPresent() && Boolean.parseBoolean(isDisplayServiceSchema.get()))
            return;

        if (auth.isPresent()) {
            String[] namePassword = prepareAuthData(message, auth);
            if (namePassword.length == 2 && isAuthenticated(namePassword[0], namePassword[1])) {
                // let request to continue
                LOG.trace(namePassword[0] + " authenticated");
                headers.put(SystemHeadersConstants.HEADER_USER_LOGIN, Collections.singletonList(namePassword[0]));
            } else {
                faultAction(message);
            }
        } else {
            faultAction(message);
        }
    }

    private String[] prepareAuthData(Message message, Optional<String> auth) {
        String[] parts = auth.get().split(" ");
        if (parts.length != 2 || !BASIC.equals(parts[0])) {
            faultAction(message);
        }
        String decodedValue = null;
        try {
            decodedValue = new String(Base64Utility.decode(parts[1]));
        } catch (Base64Exception ex) {
            faultAction(message);
        }
        String[] namePassword = decodedValue.split(":");
        return namePassword;
    }

    private void faultAction(Message message) {
        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);
        headers.put(WWW_AUTHENTICATE, Collections.singletonList(WWW_AUTHENTICATE_MESSAGE));
        Fault fault = new Fault(new AuthenticationException("Unauthorized Access"));
        fault.setFaultCode(Fault.FAULT_CODE_CLIENT);
        fault.setStatusCode(401);
        throw fault;
    }

    private boolean isAuthenticated(String name, String password) {
        return basicAuthService.check(name, password);
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public BasicAuthService getBasicAuthService() {
        return basicAuthService;
    }

    public void setBasicAuthService(BasicAuthService basicAuthService) {
        this.basicAuthService = basicAuthService;
    }

}
