package com.shr.filter;

import com.alibaba.fastjson.JSON;
import com.shr.common.response.RestResponse;
import com.shr.config.ThreadLocalConfig;
import org.eetrust.security.client.util.AssertionHolder;

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

/**
 * @author Inori
 */
//@WebFilter(urlPatterns = "/api/*")
public class SecurityFilter implements Filter {
    public static final String SUBJECT_USER = "_subject_user_";

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转换参数
        final HttpServletRequest request = (HttpServletRequest) servletRequest;

        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final HttpSession session = request.getSession(false);
        if (session == null) {
            this.writeResponse(response, "This Session Not Found");
            //response.sendRedirect(request.getContextPath() + "/accessDenied.jsp");
            return;
        }

        // 取得会话中登录用户
        String user = (String) session.getAttribute(SUBJECT_USER);
        if (user == null) {
            user = AssertionHolder.getAssertion().getPrincipal().getName();
            if (user == null) {
                this.writeResponse(response, "This User Not Found");
                //response.sendRedirect(request.getContextPath() + "/accessDenied.jsp");
                return;
            }

            ThreadLocalConfig.get().put("ssoUsername", user);

            request.getSession().setAttribute(SUBJECT_USER, user);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }

    private void writeResponse(HttpServletResponse httpServletResponse, String message) {
        httpServletResponse.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
        httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        RestResponse resp = RestResponse.fail(message).setCode(RestResponse.CODE_TOKEN_NOTFOUND);
        try (PrintWriter printWriter = httpServletResponse.getWriter()) {
            printWriter.write(JSON.toJSONString(resp));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
