package com.skr.mdm.authentication.user;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.json.JSONUtil;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.dto.TokenDTO;
import com.skr.mdm.enums.MdmEncryptEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import com.skr.mdm.util.SmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * @author nfq
 * @date 2020/7/15 11:47
 */
@Component
public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${mdm.encrypt}")
    private String mdmEncrypt;

    @Autowired
    private UserTokenHandler userTokenHandler;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        LoginUserDTO loginUserDTO = (LoginUserDTO) authentication.getPrincipal();
        TokenDTO token = userTokenHandler.createToken(loginUserDTO);
        ResponseResult result = ResponseResult.success(token);
        if (MdmEncryptEnum.SM.getMdmEncrypt().equals(mdmEncrypt)) {
            SecureRandom secureRandom = new SecureRandom();
            byte[] secretKeyBytes = new byte[16];
            secureRandom.nextBytes(secretKeyBytes);

            SM4 sm4 = SmUtil.sm4(secretKeyBytes);
            result.setData(sm4.encryptHex(JSONUtil.toJsonStr(result.getData())));

            SM2 sm2 = SmUtils.sm2Crypt();
            result.setSecretKey(sm2.encryptHex(secretKeyBytes, KeyType.PublicKey));
            // 签名
            String sm3 = SmUtil.sm3(JSONUtil.toJsonStr(result.getData()));
            SM2 sm2Sign = SmUtils.sm2Sign();
            result.setSign(sm2Sign.signHex(sm3));
        }
        ResponseUtil.responseJson(response, HttpStatus.OK.value(), result);
    }
}
