package com.ruoyi.framework.filter;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.saas.vo.SysUserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 *@Description 平台登录路径匹配过滤器
 *@Author zhushuyong
 *@Date 2021/7/17 9:43
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
public class PlatformLoginPathMatchFilter extends PathMatchingFilter {

    @Override
    public boolean onPreHandle(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String servletPath = request.getServletPath();
        Object obj = SecurityUtils.getSubject().getPrincipal();
        if (Objects.isNull(obj)) {
            //如果是登录地址不拦截，否则跳转登录页
            if (Constants.PLATFORM_LOGIN_URL.equals(servletPath)) {
                return super.onPreHandle(request, response, mappedValue);
            }else {
                response.sendRedirect(request.getContextPath() + Constants.PLATFORM_LOGIN_URL);
                return false;
            }
        } else {
            if (obj instanceof SysUserVO) { //SaaS用户
                // 如果请求的路径与平台登录地址相同，则直接放行并跳回SaaS首页
                if (servletPath.contains(Constants.PLATFORM)) {
                    response.sendRedirect(request.getContextPath());
                    return false;
                }
                return super.onPreHandle(request, response, mappedValue);
            }
            return super.onPreHandle(request, response, mappedValue);
        }
    }
}
