/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.base.filter;

import com.codvision.base.entity.BackendUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 静态资源登录校验
 *
 * @author lingee
 * @date 2023/11/2
 */
@Slf4j
public class LoginFilter implements Filter {

    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    // 登录session key
    public static final String LOGIN_SESSION_KEY = "backendUser";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1.获取请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求{}", requestURI);

        String[] urls = new String[]{
                "/backend/page/login.html",
                "/backend/css/**",
                "/backend/images/**",
                "/backend/js/**",
                "/backend/lib/**",
                "/backend/api/user/login"
        };

        if (checkAndPass(urls, requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        HttpSession session = request.getSession();
        BackendUser baseUser = (BackendUser) session.getAttribute(LOGIN_SESSION_KEY);
        if (ObjectUtils.isEmpty(baseUser)) {
            response.sendRedirect("/backend/page/login.html");
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

    /**
     * 路径匹配，判断是否需要放行
     *
     * @param urls 匹配地址
     * @param url  请求地址
     * @return
     */
    public boolean checkAndPass(String[] urls, String url) {
        for (String item : urls) {
            if (PATH_MATCHER.match(item, url)) {
                return true;
            }
        }
        return false;
    }

}

