package com.app.framework.core.web.filter;

import com.app.framework.core.utils.request.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 前端接口身份认证拦截器
 * 用于非前后端分离的项目，前端用户通过Session存储登录信息
 * 默认所有资源都是开放的，只对受保护的资源进行登录认证，受保护的URL要求包含: /authc/
 * 根据Session中的会话信息，验证用户是否登录，以及是否有权限访问当前URL
 *
 */
public class WebHttpServletRequestFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(WebHttpServletRequestFilter.class);

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

    }

    @Override
    public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) srequest;
        HttpServletResponse response = (HttpServletResponse)sresponse;
        String uri = request.getRequestURI();
//        logger.info(String.format("前端身份认证[URI = %s]：", uri));
        if (uri.indexOf("/authc/") > -1) {//需要登录才能访问的资源，验证是否登录
            if (SessionUtil.getCurrentUser(request) == null) {//未登录，跳转到登录页面
                request.setAttribute("redirectUrl", uri);
                request.getRequestDispatcher("/web/login").forward(srequest, sresponse);
//                response.sendRedirect(request.getContextPath() + "/web/login");
            } else {
                chain.doFilter(srequest, sresponse);
            }
        } else if (uri.indexOf("/api/") > -1) {
            chain.doFilter(srequest, sresponse);
        } else if (uri.indexOf("/web/") > -1) {
            chain.doFilter(srequest, sresponse);
        } else {
            response.sendRedirect("/404");
        }
    }

    @Override
    public void destroy() {

    }
}
