package cn.ibizlab.r7.runtime.runtimemgr.security.filter;

import cn.ibizlab.r7.runtime.runtimemgr.security.token.TokenManager;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    TokenManager tokenManager ;
    private String tokenHeader;

    public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,String tokenHeader) {
        super(authManager);
        this.tokenManager = tokenManager;
        this.tokenHeader = tokenHeader ;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        String headerToken = req.getHeader(tokenHeader);

        if (headerToken == null) {
            chain.doFilter(req, res);
            return;
        }
        if (headerToken.startsWith("Bearer ")) {
            String strToken = headerToken.substring(7);
            try {
                UsernamePasswordAuthenticationToken authentication = tokenManager.parseToken(strToken);
                if (authentication != null) {
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (ExpiredJwtException e) {

            }
        }
        chain.doFilter(req, res);
    }

}
