package com.jiayue.ssi.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.util.JwtTokenUtil;
import com.jiayue.ssi.util.ResponseVO;

import cn.hutool.json.JSONUtil;

/**
* 成功认证处理
* @author xsl
* @date 2023/2/16
*/
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUser sysUser = (SysUser) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(sysUser);
//        SysUser sysUser = sysUserService.findByUserName(user.getUsername());
//        sysUser.setPwdErrNum(0);
//        sysUser.setStatus("0");
//        sysUserService.save(sysUser);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(ResponseVO.success(token)));
    }


}
