package cn.reghao.oss.console.account.security.handler;

import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.web.ServletUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

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

/**
 * 认证成功后跳转到登录前的地址
 *
 * @author reghao
 * @date 2019-04-08 23:50:51
 */
@Component
public class AuthSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
            throws IOException {
        String redirectPath = getRedirectPath();
        String body = WebResult.success(redirectPath);
        writeResponse(response, body);
    }

    /**
     * 认证成功后, 重定向到登录前的地址, 需要 session 的支持
     *
     * @param
     * @return
     * @date 2023-08-16 10:58:41
     */
    private String getRedirectPath() {
        String redirectPath = "/";
        // 获取 spring security 在 session 中存放的变量
        SavedRequest savedRequest =
                (SavedRequest) ServletUtil.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if (savedRequest != null) {
            redirectPath = savedRequest.getRedirectUrl();
        }

        return redirectPath;
    }

    private void writeResponse(HttpServletResponse response, String body) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(body);
    }
}
