package org.minager.core.security;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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

import org.minager.core.AbstractFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AuthenticationFilter extends AbstractFilter {

	private static final String HTTP_OPTIONS = "OPTIONS";

	private static final String HEADER_TOKEN = "token";
	
	@Autowired
	private TokenService tokenService;
	
	@Override
	protected List<Route> getRoutes() {
		return Arrays.asList(
				new Route("\\api\\/account\\/signin"),
				new Route("\\/api\\/server\\/start"),
				new Route("\\/api\\/server\\/stop"),
				new Route("\\/api\\/server\\/restart")
		);
	}

	@Override
	protected void filter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(HTTP_OPTIONS.equals(request.getMethod()) || tokenService.isUserConnected(request.getHeader(HEADER_TOKEN))) {
			chain.doFilter(request, response);
		} else {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		}
	}

}
