lrj
3 天以前 7ba080d35812e6db7bd5aa8f88161c02653eb6c1
backend/src/main/java/com/rongyichuang/common/util/UserContextUtil.java
@@ -1,5 +1,8 @@
package com.rongyichuang.common.util;
import com.rongyichuang.auth.util.JwtUtil;
import com.rongyichuang.employee.entity.Employee;
import com.rongyichuang.employee.repository.EmployeeRepository;
import com.rongyichuang.judge.entity.Judge;
import com.rongyichuang.judge.repository.JudgeRepository;
import org.slf4j.Logger;
@@ -8,7 +11,10 @@
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
/**
@@ -23,30 +29,89 @@
    @Autowired
    private JudgeRepository judgeRepository;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 获取当前登录用户ID
     * 注意:当前系统暂时使用固定用户ID,后续需要根据实际认证机制修改
     * 从JWT token中解析用户ID
     * 
     * @return 用户ID
     */
    public Long getCurrentUserId() {
        try {
            // 首先尝试从HTTP请求头中获取JWT token
            String token = getTokenFromRequest();
            if (token != null && jwtUtil.validateToken(token)) {
                Long userId = jwtUtil.getUserIdFromToken(token);
                logger.debug("从JWT token中获取到用户ID: {}", userId);
                return userId;
            }
            // 如果没有有效的JWT token,尝试从Spring Security上下文获取
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() && 
                !"anonymousUser".equals(authentication.getPrincipal())) {
                // TODO: 从认证信息中获取真实的用户ID
                // 这里需要根据实际的认证机制来实现
                // 例如:从JWT token中解析用户ID,或从UserDetails中获取
                logger.debug("获取到认证用户: {}", authentication.getName());
                return 1L; // 临时返回固定用户ID
                // 如果认证信息中包含用户ID,可以在这里解析
                // 暂时返回固定用户ID用于兼容性
                return 1L;
            }
        } catch (Exception e) {
            logger.warn("获取当前用户ID时发生异常: {}", e.getMessage());
        }
        
        // 如果没有认证信息,返回默认用户ID(开发阶段使用)
        logger.debug("未找到认证信息,使用默认用户ID");
        return 1L;
        // 如果没有认证信息,返回null表示未登录
        logger.debug("未找到有效的认证信息");
        return null;
    }
    /**
     * 从HTTP请求中获取JWT token
     */
    private String getTokenFromRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String authHeader = request.getHeader("Authorization");
                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    return authHeader.substring(7);
                }
            }
        } catch (Exception e) {
            logger.debug("获取JWT token时发生异常: {}", e.getMessage());
        }
        return null;
    }
    /**
     * 获取当前用户关联的员工信息
     *
     * @return 员工信息,如果当前用户不是员工则返回空
     */
    public Optional<Employee> getCurrentEmployee() {
        Long userId = getCurrentUserId();
        if (userId == null) {
            logger.warn("无法获取当前用户ID");
            return Optional.empty();
        }
        try {
            Optional<Employee> employee = employeeRepository.findByUserId(userId);
            if (employee.isPresent()) {
                logger.debug("找到当前用户关联的员工: {}", employee.get().getName());
            } else {
                logger.debug("当前用户(ID: {})不是员工", userId);
            }
            return employee;
        } catch (Exception e) {
            logger.error("查询员工信息时发生异常: {}", e.getMessage(), e);
            return Optional.empty();
        }
    }
    /**
@@ -76,6 +141,15 @@
    }
    /**
     * 获取当前用户关联的员工ID
     *
     * @return 员工ID,如果当前用户不是员工则返回null
     */
    public Long getCurrentEmployeeId() {
        return getCurrentEmployee().map(Employee::getId).orElse(null);
    }
    /**
     * 获取当前用户关联的评委ID
     * 
     * @return 评委ID,如果当前用户不是评委则返回null
@@ -85,6 +159,15 @@
    }
    /**
     * 检查当前用户是否为员工
     *
     * @return true如果当前用户是员工,否则false
     */
    public boolean isCurrentUserEmployee() {
        return getCurrentEmployee().isPresent();
    }
    /**
     * 检查当前用户是否为评委
     * 
     * @return true如果当前用户是评委,否则false