package com.jeeplus.common;

import cn.hutool.core.util.StrUtil;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is
 * found.
 */
public class JWTFilter extends GenericFilterBean {


    private final TokenProvider tokenProvider;

    public JWTFilter(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = TokenProvider.resolveToken ( request );
        String accessToken = null;
        if ( StrUtil.isNotEmpty ( token ) ) {
            String loginName = TokenProvider.getLoginName ( token );
            if ( StrUtil.isNotEmpty ( loginName ) ) {
                Object accessTokenObj = RedisUtils.getInstance ( ).get ( CacheNames.USER_CACHE_TOKEN, token );
                if ( accessTokenObj != null ) {
                    accessToken = accessTokenObj.toString ( );
                }
            }
        }

        boolean isLogin = StrUtil.isNotBlank ( accessToken ) && !accessToken.equals ( "kickOut" );

        if ( isLogin && this.tokenProvider.validateToken ( accessToken ) ) {
            if ( SecurityContextHolder.getContext ( ).getAuthentication ( ) == null ) { // 需要登录
                Authentication authentication = this.tokenProvider.getAuthentication ( accessToken );
//                authenticationManager.authenticate(authentication); 验证不需要
                SecurityContextHolder.getContext ( ).setAuthentication ( authentication );
            }
        }
        filterChain.doFilter ( servletRequest, servletResponse );
    }

}
