package com.izouma.nineth.config;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.utils.SecurityUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
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;

@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class AddResponseHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        User user = SecurityUtils.getAuthenticatedUser();
        if (user != null) {
            httpServletResponse.addHeader("X-UID", user.getId() + "");
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
