package com.jd.lightapplication.security;

import cn.hutool.json.JSONUtil;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.utils.JwtUtils;
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 javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
    JwtUtils jwtUtils;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();

		// 生成jwt，并放置到请求头中
		AccountUser user = (AccountUser) authentication.getPrincipal();
		String jwt = jwtUtils.generateToken(user.getUserId().toString());
		response.setHeader(jwtUtils.getHeader(), jwt);
		//把认证信息封装到响应体里面
		Map<String,String> map = new HashMap<>();
		map.put(jwtUtils.getHeader(),jwt);
		R result = R.success(map);

		outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

		outputStream.flush();
		outputStream.close();
	}

}
