package com.wgb.system.service.Filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class TokenFilter extends OncePerRequestFilter {

  @Override
  protected boolean shouldNotFilter(HttpServletRequest request) {
    return !request.getRequestURI().startsWith("/wechat");
  }

  @Override
  protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    final String authHeader = httpServletRequest.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("nuatesting")) {
        log.error("Invalid Authorization Header={}", httpServletRequest.getRequestURI());
        httpServletRequest.getSession().getServletContext().getRequestDispatcher("/error/session/expired").forward(httpServletRequest, httpServletResponse);
        return;
    } else {
        final String token = authHeader.replace("nuatesting", ""); // The part after "mjn "
        try {
//          httpServletRequest.setAttribute("memberInfo", "");
        } catch (Exception e) {
          log.warn("Error occured while parsing token {},msg{}", token, e.getMessage());
          httpServletRequest.getSession().getServletContext().getRequestDispatcher("/error/session/expired").forward(httpServletRequest, httpServletResponse);
          return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
  }
}
