/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-audit
 * ==========
 * 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.audit.service.impl;

import org.slf4j.MDC;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.utils.AuditHelper;
import ru.entaxy.audit.utils.Constants;
import ru.entaxy.audit.data.Outcome;
import ru.entaxy.audit.data.Severity;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class WebLoginModule {
    public void onLogin(String username, HttpServletRequest request, Outcome outcome) {
        String remoteAddress = requestRemoteAddress(request);
        AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
                .suser(username)
                .outcome(outcome)
                .severity(outcome == Outcome.SUCCESS ? Severity.INFO : Severity.WARNING)
                .src(remoteAddress)
                .category(outcome == Outcome.SUCCESS ? "Login success" : "Login failed")
                .target("auth")
                .build();
        AuditHelper.log(event);
    }

    public void onLogout(String username, HttpServletRequest request) {
        String remoteAddress = requestRemoteAddress(request);
        AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
                .suser(username)
                .outcome(Outcome.SUCCESS)
                .severity(Severity.INFO)
                .src(remoteAddress)
                .category("Logout")
                .target("auth")
                .build();
        AuditHelper.log(event);
    }

    private static String requestRemoteAddress(HttpServletRequest request) {
        return Optional.ofNullable(request.getHeader(Constants.X_FORWARDER_FOR))
                .orElse(request.getRemoteHost());
    }

    public void setMDC(Subject subject, HttpServletRequest request) {
        String remoteUser = AuditHelper.findRemoteUser(subject);
        saveMDC(remoteUser, request);
    }

    public void setMDC(String username, HttpServletRequest request) {
        saveMDC(username, request);
    }

    private void saveMDC(String username, HttpServletRequest request) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        if (contextMap == null) {
            contextMap = new HashMap<>();
        }
        contextMap.put(Constants.HTTP_REQUEST_USER, username);
        contextMap.put(Constants.HTTP_REQUEST_REMOTE_IP, requestRemoteAddress(request));
        contextMap.put(Constants.HTTP_REQUEST_SERVER_IP, request.getServerName());
        MDC.setContextMap(contextMap);
    }

}
