package cn.axzo.msg.center.http;

import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @author yanglin
 */
@Component
@RequiredArgsConstructor
public class PrivateHandlerInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(PrivateHandlerInterceptor.class);
    private static final String PRIVATE_TOKEN = "ga1T5JXnGaiy4qaOnpHs";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean tokenValid = PRIVATE_TOKEN.equals(token);
        if (!tokenValid) {
            log.warn("Invalid private token:{}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid private token");
        }
        return tokenValid;
    }

}
