package com.cms.interceptor;

import com.cms.entity.transform.AuthMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    public static final String SESSION_MEMBER = "MEMBER";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        log.info("sessionId={}", request.getSession().getId());
        AuthMember authMember = (AuthMember) request.getSession().getAttribute(SESSION_MEMBER);
        if (authMember == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":4001,\"message\":\"未登录，请先登录\"}");
            return false;
        }
        return true;
    }
}
