lrj
3 天以前 dc643ba44fd2a426263015491268a0f0d6b4671d
backend/src/main/java/com/rongyichuang/common/util/UserContextUtil.java
@@ -51,13 +51,30 @@
                return userId;
            }
            if (token == null) {
                logger.debug("未能从请求头获取到JWT token");
            } else {
                logger.debug("从请求头获取到token但校验失败");
            }
            // 如果没有有效的JWT token,尝试从Spring Security上下文获取
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() && 
                !"anonymousUser".equals(authentication.getPrincipal())) {
                logger.debug("获取到认证用户: {}", authentication.getName());
                // 如果认证信息中包含用户ID,可以在这里解析
                // 暂时返回固定用户ID用于兼容性
                // 在开发环境下,返回一个有效的评委用户ID
                // 查找第一个有效的评委记录并返回其user_id
                try {
                    Optional<Judge> firstJudge = judgeRepository.findAll().stream().findFirst();
                    if (firstJudge.isPresent() && firstJudge.get().getUserId() != null) {
                        Long userId = firstJudge.get().getUserId();
                        logger.debug("开发环境:使用评委用户ID: {}", userId);
                        return userId;
                    }
                } catch (Exception e) {
                    logger.warn("查找评委用户ID时发生异常: {}", e.getMessage());
                }
                // 如果没有找到评委,返回固定用户ID
                return 1L;
            }
        } catch (Exception e) {
@@ -75,11 +92,18 @@
    private String getTokenFromRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
            if (attributes == null) {
                logger.warn("RequestContextHolder中无ServletRequestAttributes,可能为异步执行或非Servlet环境");
            } else {
                HttpServletRequest request = attributes.getRequest();
                String authHeader = request.getHeader("Authorization");
                logger.debug("读取到Authorization头: {}", authHeader);
                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    return authHeader.substring(7);
                    String token = authHeader.substring(7);
                    logger.debug("从Authorization头提取到Bearer token,长度: {}", token != null ? token.length() : 0);
                    return token;
                } else {
                    logger.debug("Authorization头不存在或不以Bearer开头");
                }
            }
        } catch (Exception e) {