package com.its.op.security.interceptor;

import com.its.op.security.WebMvcConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Slf4j
public class ApiInterceptor implements HandlerInterceptor {

    /**
     * Executed before actual handler is executed
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // @CookieValue 를 컨트롤러에 추가해야함. (..., @CookieValue(value = "REMEMBER", required = false) Cookie rCookie)
//        log.info("START: Request URI: {}", request.getRequestURI());

        HttpSession session = request.getSession(false);
        if (session == null) {
            if (!StringUtils.equalsIgnoreCase("GET", request.getMethod())) {
                log.error("로그인 하지 않은 사용자가 API(POST/PUT/DELETE)에 접근함.");
                // GET Method 를 제외한 Request 제한할 경우.... ==> Web Security 에서 처리함.
                //return false;
            }
        }
        else {
            String encUserId = (String)session.getAttribute(WebMvcConfig.USER_UUID);
            String userId = "";
            if (!"".equals(encUserId)) {
                userId = WebMvcConfig.decUserId(encUserId);
            }
//            log.info("Session: {}", userId);
        }
        return true;
    }

}
