package com.jiayue.ssi.handler;

import cn.hutool.json.JSONUtil;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.constant.Constants;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.factory.LoginFactory;
import com.jiayue.ssi.util.ResponseVO;
import com.jiayue.ssi.util.SM2CryptUtils;
import com.jiayue.ssi.util.SecurityContextUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author ruoyi
 */
@Configuration
public class CustomLogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {
    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        SysUser sysUser = (SysUser)authentication.getPrincipal();
        // 记录用户退出日志
        LoginFactory.recordLogininfor(sysUser.getUsername(), Constants.LOGIN_SUCCESS, "退出成功");
        // 将token存储内存中，便于重复登录比对
        CacheConstants.LOGIN_TOKEN_MAP.remove(sysUser.getUsername());

        String obj = JSONUtil.toJsonStr(ResponseVO.success("退出成功"));
        // token加密处理
        String encrypt = SM2CryptUtils.encrypt(obj, SecretKeyConstants.CLIENT_PUBLIC_KEY);
        // token签名
        String signStr = SM2CryptUtils.sign(SecretKeyConstants.SERVER_PRIVATE_KEY,obj);
        String secretResult = "encrypt="+encrypt+"&signStr="+signStr;
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(200);
        response.getWriter().write(secretResult);
    }
}
