package cn.wisenergy.web.shiro.filter;

import cn.wisenergy.common.enums.RespCodeEnum;
import cn.wisenergy.common.utils.HttpContextUtils;
import cn.wisenergy.common.utils.exception.Result;
import cn.wisenergy.web.shiro.AuthToken;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
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;
import java.io.IOException;

/**
 * oauth2过滤器
 *
 * @author 86187
 */
@Slf4j
public class AuthFilter extends AuthenticatingFilter {

    /**
     * 这里重写了父类的方法，使用我们自己定义的Token类，提交给shiro。
     * 这个方法返回null的话会直接抛出异常，进入isAccessAllowed() 的异常处理逻辑。
     *
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return new AuthToken(token);
    }

    /**
     * 父类会在请求进入拦截器后调用该方法，返回true则继续，返回false则会调用onAccessDenied()。这里在不通过时，还调用了isPermissive()方法
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
//        boolean allowed = false;
//        try {
//            allowed = executeLogin(request, response);
//        } catch(IllegalStateException e){ //not found any token
//            log.error("Not found any token");
//        }catch (Exception e) {
//            log.error("Error occurs when login", e);
//        }

//        return allowed || super.isPermissive(mappedValue);
        return false;
    }

    /**
     * 如果这个Filter在之前isAccessAllowed（）方法中返回false,则会进入这个方法。这里直接返回错误的response
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response) || isEnabled(request, response)) {
            return true;
        } else {
            //获取请求token，如果token不存在，直接返回40101
            String token = getRequestToken((HttpServletRequest) request);
            if (StringUtils.isBlank(token)) {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
                httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
                httpResponse.setCharacterEncoding("UTF-8");

                Result result = new Result();
                result.setResult(Result.RESULT_FLG.FAIL.getValue());
                result.setErrorCode(RespCodeEnum.NO_AUTH_REQUEST.getCode());
                result.setErrorMsg(RespCodeEnum.NO_AUTH_REQUEST.getMsg());
                String json = JSON.toJSONString(result);
                httpResponse.getWriter().print(json);
                return false;
            }
        }

        return executeLogin(request, response);
    }

//    /**
//     *  如果Shiro Login认证成功，会进入该方法，等同于用户名密码登录成功，这里还判断了是否要刷新Token
//     */
//    @Override
//    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
//        HttpServletResponse httpResponse = WebUtils.toHttp(response);
//        if(token instanceof AuthToken){
//            AuthToken jwtToken = (AuthToken)token;
//            String newtoken  = jwtToken.getPrincipal();
//            if(StringUtils.isNotBlank(newtoken)){
//                httpResponse.setHeader("x-auth-token", newtoken);
//            }
//        }
//        return true;
//    }

    /**
     * 如果调用shiro的login认证失败，会回调这个方法
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Result result = new Result();
            result.setErrorCode(String.valueOf(HttpStatus.SC_UNAUTHORIZED));
            result.setResult(Result.RESULT_FLG.FAIL.getValue());
            result.setErrorMsg(throwable.getMessage());
            String json = JSON.toJSONString(result);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
        }
        return false;
    }

    /**
     * 获取请求头中的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("Authorization");
        return token;
    }

}
