package com.gitee.sop.admin.interceptor;

import com.gitee.sop.admin.common.annotation.NoToken;
import com.gitee.sop.admin.common.enums.StatusEnum;
import com.gitee.sop.admin.common.user.User;
import com.gitee.sop.admin.common.context.UserContext;
import com.gitee.sop.admin.common.exception.LoginFailureException;
import com.gitee.sop.admin.common.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @author tanghc
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NoToken noLogin = handlerMethod.getMethodAnnotation(NoToken.class);
        if (noLogin != null) {
            return true;
        }
        noLogin = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), NoToken.class);
        if (noLogin != null) {
            return true;
        }
        User user = UserContext.getUser(request);
        if (user == null || StatusEnum.of(user.getStatus()) == StatusEnum.DISABLED) {
            log.error("登录失败, 客户端ip:{}, uri:{}", RequestUtil.getIP(request), request.getRequestURI());
            throw new LoginFailureException("登录失败");
        }
        return true;
    }

}
