package com.jay.monitor.data.server.interceptors;

import com.jay.monitor.data.server.config.props.JayServerProperties;
import com.jay.monitor.data.server.costs.ServerConstants;
import com.jay.monitor.data.server.utils.CookiesUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
public class LoginHandler implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginHandler.class);

    @Autowired
    private JayServerProperties serverProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        logger.info(request.getRequestURI());

        if (!serverProperties.isEnableLogin()) {
            return true;
        }

        String token = request.getParameter("token");

        String defaultToken = serverProperties.getToken();

        if (defaultToken.equals(token)) {
            CookiesUtil.setCookie(response, ServerConstants.USER_SESSION_KEY, token, -1);
            return true;
        }

        Cookie cookieByName = CookiesUtil.getCookieByName(request, ServerConstants.USER_SESSION_KEY);

        if (cookieByName != null && defaultToken.equals(cookieByName.getValue())) {
            return true;
        }

        String user = (String)request.getSession().getAttribute(ServerConstants.USER_SESSION_KEY);

        if (StringUtils.isEmpty(user)) {
            response.sendRedirect(ServerConstants.LOGIN_HTML_PATH);
            logger.info("token 校验失败.");
            return false;
        }

        return true;
    }
}
