package com.bcxin.ars.rest.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.bcxin.ars.model.User;
import com.bcxin.ars.service.util.ArsUtil;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.StringUtil;
import com.bcxin.ars.util.redis.RedisUtil;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author linqinglin
 * @date 2020/05/14 0014 13:34
 */
public class ThirdPartyAuthorizationFilter extends AccessControlFilter {

    private RedisUtil redisUtil;

    private ArsUtil arsUtil;

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public void setArsUtil(ArsUtil arsUtil) {
        this.arsUtil = arsUtil;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = servletRequest.getParameter("token");
        if(StringUtil.isNotEmpty(token)){
            token = token.replaceAll(" ", "+");
            String json = redisUtil.get(Constants.ARS_SHIRO_REDIS_TOKEN_KEY + token);
            if (StringUtil.isNotEmpty(json)) {
                if(arsUtil.getCurrentUser() == null) {
                    User user = JSON.parseObject(json, User.class);
                    arsUtil.setCurrentUser(user, 1000 * 30 * 60);
                }
                return true;
            }
        }
        saveRequestAndRedirectToLogin(servletRequest, servletResponse);
        return false;
    }

}
