package com.philisense.www.handler;

import com.alibaba.fastjson.JSON;
import com.philisense.www.constant.HttpStatus;
import com.philisense.www.pojos.entity.JwtUser;
import com.philisense.www.utils.JwtTokenUtils;
import com.philisense.www.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

/**
 *
 * 需要在 SecurityConfig 设置 （它只会走自己的方法，不再走自定义的 login 了）
 * 没有使用
 * httpSecurity.formLogin().loginProcessingUrl(CommonConst.WEB_REST_SERVICE_PREFICX + "auth" + loginPath).successHandler(jwtAuthenticationSuccessHandler);
 *
 * @Description:用于处理一个成功的身份验证实现执行是处理导航到后续的目标.
 * @author
 */
@Component("jwtAuthenticationSuccessHandler")
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        String jwtToken = jwtTokenUtils.generateToken(jwtUser);
        Map<String,Object> responsemap = new HashMap<>();
        responsemap.put("success", true);
        responsemap.put("message", "登录成功");
        responsemap.put("error", "no");
        responsemap.put("status", HttpStatus.SUCCESS);
        responsemap.put("token", jwtToken);
        responsemap.put("timestamp", new Date());
        responsemap.put("path", httpServletRequest.getRequestURI());
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(responsemap));
    }
}
