lrj
3 天以前 7ba080d35812e6db7bd5aa8f88161c02653eb6c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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<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();
        }
    }
 
    /**
     * 获取当前用户关联的评委信息
     * 
     * @return 评委信息,如果当前用户不是评委则返回空
     */
    public Optional<Judge> getCurrentJudge() {
        Long userId = getCurrentUserId();
        if (userId == null) {
            logger.warn("无法获取当前用户ID");
            return Optional.empty();
        }
 
        try {
            Optional<Judge> 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> 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 "未知用户";
    }
}