package com.ningdatech.carapi.user.security.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningdatech.basic.model.ApiResponse;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * @Author LiuXinXin
 * @Date 2020/8/3 8:32 下午
 * @Version 1.0
 **/
@Component("defaultLoginSuccessHandler")
@Primary
public class DefaultLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //设置cookie
        UserInfoDetails principal = (UserInfoDetails) authentication.getPrincipal();
        response.getWriter().write(objectMapper.writeValueAsString(ApiResponse.ofSuccess()));
    }

}
