package com.keyware.shandan.config;

import com.keyware.shandan.component.ClientLogoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

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

/**
 * @author Administrator
 */
@Component
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    @Autowired
    private ClientLogoutHandler clientLogoutHandler;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String clientId = request.getParameter("clientId");
        String loginName = null;
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof String) {
                loginName = (String) principal;
            } else {
                User user = (User) principal;
                loginName = user.getUsername();
            }
        } else {
            loginName = request.getParameter("loginName");
        }
        clientLogoutHandler.callClientsLogout(loginName, clientId);
        response.sendRedirect("login?logout");
    }
}
