package cn.wisenergy.shiro.filter;

import cn.wisenergy.mapper.WorkUserMapper;
import cn.wisenergy.model.app.WorkUser;
import cn.wisenergy.shiro.util.CustomerRealm;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @description: 自定义退出
 * @author: nh
 * @create: 2021-04-10 16:31
 **/
public class CustomerLogoutFilter extends LogoutFilter {
    @Autowired
    private WorkUserMapper workUserMapper;

    @Autowired
    private CustomerRealm realm;

    public CustomerLogoutFilter() {
    }


    // 删除存入redis中的认证信息，小程序请求不带session，用shiro的subject.logout()方法不能够删除redis中的认证信息
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 请求的路径
        String requestURI = httpServletRequest.getRequestURI();
        // 不为微信登出则进行下一过滤器
        if (!requestURI.equals("/wxLogout")) {
            return true;
        }
        // shiro主体
        Subject subject = getSubject(request, response);

        // 获取请求的参数：userId
        String userIdString = httpServletRequest.getParameter("userId");
        Integer userId = Integer.valueOf(userIdString);
        // 获取用户信息
        WorkUser user = workUserMapper.getUserById(userId);
        //
        SimplePrincipalCollection simplePrincipalCollection = new SimplePrincipalCollection(user,realm.getName());
        // 删除主体认证信息
        realm.clearCachedAuthenticationInfo(simplePrincipalCollection);
        try {
            subject.logout();
        } catch (SessionException ise) {
            ise.printStackTrace();
        }
        // 重定向到指定地址
//        String redirectUrl = getRedirectUrl(request, response, subject);
//        issueRedirect(request, response, redirectUrl);
        // 为true，进入微信退出接口
        return true;
    }

}
