package cn.reghao.autodop.dmaster.rbac.security;

import cn.reghao.jdkutil.result.WebBody;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;

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
 */
public class WebAuthSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
            throws IOException {
        sendResponse(response);
        //redirect(request, response);
    }

    private void sendResponse(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String result = WebBody.success("");
        PrintWriter pt = response.getWriter();
        pt.println(result);
    }

    /**
     * TODO 前端无法处理重定向
     *
     * @param
     * @return
     * @date 2021-07-27 下午3:54
     */
    private void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest =
                (SavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            // 跳转到登录前的地址
            response.sendRedirect(redirectUrl);
        } else {
            // 跳转到首页
            response.sendRedirect("/");
        }
    }
}
