package nckd.jimin.jyyy.bd.common.oauth;

import kd.bos.dc.api.model.Account;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.thirdauth.app.AppAuthResult;
import kd.bos.login.thirdauth.app.ThirdAppAuthtication;
import kd.bos.login.thirdauth.app.UserType;
import nckd.base.helper.CommonHelperUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author wanghaiwu_kd
 * @date 2025/05/06
 * @description 单点登录拦截，加固单点校验方式
 */
public class SSOAuthtication extends ThirdAppAuthtication {
    private static Log logger = LogFactory.getLog(SSOAuthtication.class);
    /**
     * 判断该接口请求是否需要通过此插件认证
     */
    @Override
    public boolean isNeedHandle(HttpServletRequest request, Account account) {
        //加密的数据信息
        String code = request.getParameter("kd_code");
        if(StringUtils.isNotBlank(code)){
            return true;
        }
        return false;
    }

    /**
     *用户身份解析
     */
    @Override
    public AppAuthResult appAuthtication(HttpServletRequest request, Account account) {
        AppAuthResult result = new AppAuthResult();
        result.setSucceed(false);
        try{
            //加密的数据信息
            String code = request.getParameter("kd_code");
            if(StringUtils.isBlank(code)){
                logger.info("SSOAuthtication：kd_code is null");

                result.setErrorMessage("sso：kd_code is null");
                return result;
            }

            Map<String, String> mapentity = CommonHelperUtils.getCommonParams("SSO");
            if(mapentity == null ){
                logger.info("SSOAuthtication：nckd_entryentity is null");

                result.setErrorMessage("SSOAuthtication：未配置单点相关参数");
                return result;
            }

            //私钥
            String privateKey = mapentity.get("privatekey");
            if(StringUtils.isEmpty(privateKey)){
                logger.info("SSOAuthtication：privateKey is null");

                result.setErrorMessage("SSOAuthtication：未配置单点相关参数privatekey");
                return result;
            }

            //和第三方约定加签
            String secret = mapentity.get("secret");
            if(StringUtils.isEmpty(secret)){
                logger.info("SSOAuthtication：secret is null");

                result.setErrorMessage("SSOAuthtication：未配置单点相关参数secret");
                return result;
            }

            //可以先使用SHAUtils.getSHA256Hex实现签名验证再数据解密
            String timeStamp = request.getParameter("timeStamp");
            String signture = request.getParameter("signture");
            if(!SHAUtils.checkDateTime(timeStamp)) {
                logger.info("SSOAuthtication：timeStamp check fail");

                result.setErrorMessage("sso：timeStamp check fail");
                return result;
            }

            String sign = SHAUtils.getSHA256Hex(code + timeStamp + secret);

            //签名认证
            if(StringUtils.isBlank(signture) || !signture.equals(sign)) {
                logger.info("SSOAuthtication：sign check fail");

                result.setErrorMessage("sso：sign check fail");
                return result;
            }

            String user = new String(SSORSAUtils.decryptByKey(SSORSAUtils.getPrivateKey(Base64.decodeBase64(privateKey))
                                        , Base64.decodeBase64(code.getBytes("UTF-8"))));
            if(StringUtils.isBlank(user)){
                logger.info("SSOAuthtication：user is null");

                result.setErrorMessage("sso：user is null");
                return result;
            }

            result.setUserFlag(user);
            result.setUserType(UserType.USER_NAME);
            result.setSucceed(true);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}