package com.keyware.shandan.frame.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

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

/**
 * 注销处理
 */
@Component
public class LogoutHandlerConfig implements LogoutHandler {
    @Autowired
    private SecurityUtil securityUtil;

    @Value("${oauth.server.proxy}")
    private String oauthServer;

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //剔除退出用户
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal != null) {
                if (principal instanceof User) {
                    securityUtil.sessionRegistryRemoveUser((User) principal);
                } else if (principal instanceof String) {
                    securityUtil.sessionRegistryRemoveUserByLoginName((String) principal);
                }
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        cookie.setValue("");
                        response.addCookie(cookie);
                    }
                }
                try {
                    // 重定向到统一认证中心的登出URI
                    response.sendRedirect(oauthServer + "/logout?clientId=" + clientId);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
