package com.jsc.oscm.security.token;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;

public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private final TokenManager tokenManager;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager, TokenManager tokenManager) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        String headerString = request.getHeader("token");
        if (headerString == null) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken tokenAuthentication = getAuthenticationToken(request);
        if (tokenAuthentication != null) {
            SecurityContextHolder.getContext().setAuthentication(tokenAuthentication);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthenticationToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token != null && !"".equals(token.trim())) {
            // parse the token.
            String userName = tokenManager.getUserFromToken(token);

            if (!StringUtils.isEmpty(userName)) {
                return new UsernamePasswordAuthenticationToken(userName, token, new ArrayList<>());//todo：这里是不是应该把token替换为password
            }
            return null;
        }
        return null;
    }

}
