package com.zcloud.config;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class StatelessAuthcFilter extends UserFilter {
    @Override

    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {

            httpResponse.setStatus(HttpStatus.OK.value());
            return false;

        }

        return super.preHandle(request, response);

    }

    @Override

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletResponse httpResp = WebUtils.toHttp(response);

        HttpServletRequest httpReq = WebUtils.toHttp(request);

        /*系统重定向会默认把请求头清空，这里通过拦截器重新设置请求头，解决跨域问题*/

        httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));

        httpResp.addHeader("Access-Control-Allow-Headers", "*");

        httpResp.addHeader("Access-Control-Allow-Methods", "*");

        httpResp.addHeader("Access-Control-Allow-Credentials", "true");

        this.saveRequestAndRedirectToLogin(request, response);

        return false;

    }

}
