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; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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; /** * 用户上下文工具类 * 用于获取当前登录用户信息和关联的评委信息 */ @Component public class UserContextUtil { private static final Logger logger = LoggerFactory.getLogger(UserContextUtil.class); @Autowired private JudgeRepository judgeRepository; @Autowired private EmployeeRepository employeeRepository; @Autowired private JwtUtil jwtUtil; /** * 获取当前登录用户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())) { logger.debug("获取到认证用户: {}", authentication.getName()); // 如果认证信息中包含用户ID,可以在这里解析 // 暂时返回固定用户ID用于兼容性 return 1L; } } catch (Exception e) { logger.warn("获取当前用户ID时发生异常: {}", e.getMessage()); } // 如果没有认证信息,返回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 getCurrentEmployee() { Long userId = getCurrentUserId(); if (userId == null) { logger.warn("无法获取当前用户ID"); return Optional.empty(); } try { Optional 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(); } } /** * 获取当前用户关联的评委信息 * * @return 评委信息,如果当前用户不是评委则返回空 */ public Optional getCurrentJudge() { Long userId = getCurrentUserId(); if (userId == null) { logger.warn("无法获取当前用户ID"); return Optional.empty(); } try { Optional judge = judgeRepository.findByUserId(userId); if (judge.isPresent()) { logger.debug("找到当前用户关联的评委: {}", judge.get().getName()); } else { logger.debug("当前用户(ID: {})不是评委", userId); } return judge; } catch (Exception e) { logger.error("查询评委信息时发生异常: {}", e.getMessage(), e); return Optional.empty(); } } /** * 获取当前用户关联的员工ID * * @return 员工ID,如果当前用户不是员工则返回null */ public Long getCurrentEmployeeId() { return getCurrentEmployee().map(Employee::getId).orElse(null); } /** * 获取当前用户关联的评委ID * * @return 评委ID,如果当前用户不是评委则返回null */ public Long getCurrentJudgeId() { return getCurrentJudge().map(Judge::getId).orElse(null); } /** * 检查当前用户是否为员工 * * @return true如果当前用户是员工,否则false */ public boolean isCurrentUserEmployee() { return getCurrentEmployee().isPresent(); } /** * 检查当前用户是否为评委 * * @return true如果当前用户是评委,否则false */ public boolean isCurrentUserJudge() { return getCurrentJudge().isPresent(); } /** * 检查当前用户是否为指定活动的评委 * * @param activityId 活动ID * @return true如果当前用户是该活动的评委,否则false */ public boolean isCurrentUserJudgeForActivity(Long activityId) { Optional judge = getCurrentJudge(); if (judge.isEmpty()) { return false; } try { // 通过ActivityJudge表检查当前评委是否参与指定活动 return judgeRepository.existsByIdAndActivityId(judge.get().getId(), activityId); } catch (Exception e) { logger.error("检查评委活动权限时发生异常: {}", e.getMessage(), e); return false; } } /** * 获取当前用户名称(用于日志记录) * * @return 用户名称 */ public String getCurrentUserName() { try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { return authentication.getName(); } } catch (Exception e) { logger.warn("获取当前用户名称时发生异常: {}", e.getMessage()); } return "未知用户"; } }