/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-legacy-auth
 * ==========
 * 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.platform.runtime.security.jaas.modules.entaxylegacy;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;

import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.jaas.modules.AbstractKarafLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.system.auth.basic.jpa.api.entity.BasicAuthAccount;
import ru.entaxy.platform.base.support.CommonUtils;

public class EntaxyLegacyLoginModule extends AbstractKarafLoginModule {

    private static final Logger log = LoggerFactory.getLogger(EntaxyLegacyLoginModule.class);

    public static final String SYSTEM_ROLE_PREFIX = "PROFILE_";

    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
            Map<String, ?> options) {
        super.initialize(subject, callbackHandler, options);
    }

    @Override
    public boolean login() throws LoginException {

        if (ServiceHolder.getInstance() == null) {
            throw new LoginException("Entaxy legacy BasicAuthService not found");
        }

        Callback[] callbacks = new Callback[2];

        callbacks[0] = new NameCallback("Username: ");
        callbacks[1] = new PasswordCallback("Password: ", false);
        if (callbackHandler != null) {
            try {
                callbackHandler.handle(callbacks);
            } catch (IOException ioe) {
                throw new LoginException(ioe.getMessage());
            } catch (UnsupportedCallbackException uce) {
                throw new LoginException(uce.getMessage() + " not available to obtain information from user");
            }
        }
        // user callback get value
        if (((NameCallback) callbacks[0]).getName() == null) {
            throw new LoginException("Username can not be null");
        }
        user = ((NameCallback) callbacks[0]).getName();

        // password callback get value
        if (((PasswordCallback) callbacks[1]).getPassword() == null) {
            throw new LoginException("Password can not be null");
        }
        String password = new String(((PasswordCallback) callbacks[1]).getPassword());

        if (!isAuthenticated(user, password))
            throw new FailedLoginException("login failed");



        principals = new HashSet<>();
        principals.add(new UserPrincipal(user));
        Optional<BasicAuthAccount> acc = ServiceHolder.getInstance().getBasicAuthService().get(user);
        if (acc.isPresent()) {
            String systemUuid = acc.get().getSystemUUID();
            if (CommonUtils.isValid(systemUuid))
                principals.add(new RolePrincipal(SYSTEM_ROLE_PREFIX + systemUuid));
        }

        if (debug) {
            log.debug("Successfully logged in {}", user);
        }
        succeeded = true;
        return true;

    }

    private boolean isAuthenticated(String name, String password) {
        return ServiceHolder.getInstance().getBasicAuthService().check(name, password);
    }
}
