package com.skr.mdm.authentication.user;

import com.skr.mdm.authentication.TokenExpireException;
import com.skr.mdm.constant.RequestHeaderConstants;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * @author nfq
 * @date 2020/7/20 16:01
 */
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private UserTokenHandler userTokenHandler;
    @Autowired
    private UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        try {
            String jwt = request.getHeader(RequestHeaderConstants.REQUEST_HEADER_TOKEN);
            userTokenHandler.signOut(jwt);
            ResponseResult result = ResponseResult.success();
            ResponseUtil.responseJson(response, HttpStatus.OK.value(), result);
        } catch (TokenExpireException e) {
            userAuthenticationEntryPoint.commence(request, response, e);
        }
    }
}
