package com.skr.mdm.filter;

import com.skr.mdm.authentication.TokenExpireException;
import com.skr.mdm.authentication.user.UserAuthenticationEntryPoint;
import com.skr.mdm.authentication.user.UserTokenHandler;
import com.skr.mdm.constant.RequestHeaderConstants;
import com.skr.mdm.dto.LoginUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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;
import java.util.List;

/**
 * @author nfq
 * @date 2020/7/16 15:01
 */
@Component
@Slf4j
public class UserTokenFilter extends OncePerRequestFilter {

    public static final List<String> LOGIN_URL_LIST = new ArrayList<>();

    static {
        LOGIN_URL_LIST.add("login");
        LOGIN_URL_LIST.add("imei/login");
        LOGIN_URL_LIST.add("user/login");
        LOGIN_URL_LIST.add("oaid/login");
        LOGIN_URL_LIST.add("uuid/login");
    }

    @Autowired
    private UserTokenHandler userTokenHandler;
    @Autowired
    private UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        for (String uri : LOGIN_URL_LIST) {
            if (requestUri.contains(uri) && StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), method)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        String token = getTokenParameter(request);
        if (StringUtils.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        LoginUserDTO loginUser = null;
        try {
            loginUser = userTokenHandler.getLoginUserByJwt(token);
            if (loginUser == null) {
                filterChain.doFilter(request, response);
                return;
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (TokenExpireException e) {
            userAuthenticationEntryPoint.commence(request, response, e);
            return;
        }
        filterChain.doFilter(request, response);
    }


    private String getTokenParameter(HttpServletRequest request) {
        return request.getHeader(RequestHeaderConstants.REQUEST_HEADER_TOKEN);
    }
}
