package com.hz.pm.api.user.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hz.pm.api.user.security.errorcode.AuthErrorCodeEnum;
import com.ningdatech.basic.model.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

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

/**
 * @Author LiuXinXin
 * @Date 2020/8/20 11:15 上午
 * @Version 1.0
 **/
@Component
@RequiredArgsConstructor
public class DefaultExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    private final ObjectMapper objectMapper;
    private static final ApiResponse<Void> SESSION_EXPIRED = ApiResponse.of(AuthErrorCodeEnum.SESSION_EXPIRED.getCode(),
            AuthErrorCodeEnum.SESSION_EXPIRED.getMsg());


    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent)
            throws IOException {
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(SESSION_EXPIRED));
    }

}
