package cn.reghao.oss.console.config.web;

import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.oss.console.app.service.UserKeyService;
import cn.reghao.oss.console.util.AuthKeyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * oss-console 认证拦截
 *
 * @author reghao
 * @date 2024-02-27 11:54:07
 */
@Slf4j
@Component
public class ConsoleAuthInterceptor implements HandlerInterceptor {
    private final UserKeyService userKeyService;

    public ConsoleAuthInterceptor(UserKeyService userKeyService) {
        this.userKeyService = userKeyService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        if (uri.startsWith("/api/oss/") && !method.equalsIgnoreCase("options")) {
            if (uri.startsWith("/api/oss/store") || uri.equals("/api/oss/key/auth")) {
                return true;
            }

            String token = ServletUtil.getBearerToken();
            if (token == null || token.isBlank()) {
                log.error("request {} start with /api/oss/, but not auth", uri);
                response.setStatus(403);
                return false;
            } else {
                int userId = userKeyService.getUserIdFromToken(token);
                log.info("{} access {}", userId, uri);
                AuthKeyContext authKeyContext = new AuthKeyContext(userId);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
    }
}
