refactor:
This commit is contained in:
@ -17,28 +17,28 @@ public class GlobalExceptionHandler {
|
|||||||
@ExceptionHandler(EntityNotFoundException.class)
|
@ExceptionHandler(EntityNotFoundException.class)
|
||||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||||
public ApiResponse<Void> handleEntityNotFoundException(EntityNotFoundException e) {
|
public ApiResponse<Void> handleEntityNotFoundException(EntityNotFoundException e) {
|
||||||
logger.error("Entity not found: {}", e.getMessage());
|
// logger.error("Entity not found: {}", e.getMessage());
|
||||||
return ApiResponse.error(10003, e.getMessage());
|
return ApiResponse.error(10003, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(IllegalArgumentException.class)
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||||
public ApiResponse<Void> handleIllegalArgumentException(IllegalArgumentException e) {
|
public ApiResponse<Void> handleIllegalArgumentException(IllegalArgumentException e) {
|
||||||
logger.error("Invalid argument: {}", e.getMessage());
|
// logger.error("Invalid argument: {}", e.getMessage());
|
||||||
return ApiResponse.error(10001, e.getMessage());
|
return ApiResponse.error(10001, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||||
public ApiResponse<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
|
public ApiResponse<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
|
||||||
logger.error("Invalid request body: {}", e.getMessage());
|
// logger.error("Invalid request body: {}", e.getMessage());
|
||||||
return ApiResponse.error(10001, "请求体格式不正确");
|
return ApiResponse.error(10001, "请求体格式不正确");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(Exception.class)
|
||||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
public ApiResponse<Void> handleException(Exception e) {
|
public ApiResponse<Void> handleException(Exception e) {
|
||||||
logger.error("Unexpected error: ", e);
|
// logger.error("Unexpected error: ", e);
|
||||||
return ApiResponse.error(10009, "系统错误");
|
return ApiResponse.error(10009, "系统错误");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -37,7 +37,7 @@ public class RedisConfig {
|
|||||||
if (redisPassword != null && !redisPassword.isEmpty()) {
|
if (redisPassword != null && !redisPassword.isEmpty()) {
|
||||||
config.setPassword(redisPassword);
|
config.setPassword(redisPassword);
|
||||||
}
|
}
|
||||||
logger.info("Configuring Redis connection to {}:{}", redisHost, redisPort);
|
// logger.info("Configuring Redis connection to {}:{}", redisHost, redisPort);
|
||||||
return new LettuceConnectionFactory(config);
|
return new LettuceConnectionFactory(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,9 +74,9 @@ public class RedisConfig {
|
|||||||
// 测试连接
|
// 测试连接
|
||||||
try {
|
try {
|
||||||
template.getConnectionFactory().getConnection().ping();
|
template.getConnectionFactory().getConnection().ping();
|
||||||
logger.info("Redis连接测试成功");
|
// logger.info("Redis连接测试成功");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Redis连接测试失败: {}", e.getMessage(), e);
|
// logger.error("Redis连接测试失败: {}", e.getMessage(), e);
|
||||||
}
|
}
|
||||||
|
|
||||||
return template;
|
return template;
|
||||||
|
@ -30,24 +30,24 @@ public class LessonTaskController {
|
|||||||
@RequestParam(defaultValue = "1") Integer page,
|
@RequestParam(defaultValue = "1") Integer page,
|
||||||
@RequestParam(defaultValue = "10") Integer size,
|
@RequestParam(defaultValue = "10") Integer size,
|
||||||
@RequestParam(required = false) Long userId) {
|
@RequestParam(required = false) Long userId) {
|
||||||
logger.info("收到课程任务列表查询请求,页码: {},每页数量: {},用户ID: {}", page, size, userId);
|
// logger.info("收到课程任务列表查询请求,页码: {},每页数量: {},用户ID: {}", page, size, userId);
|
||||||
try {
|
try {
|
||||||
Page<LessonTask> tasks = lessonTaskService.findAll(PageRequest.of(page - 1, size), userId);
|
Page<LessonTask> tasks = lessonTaskService.findAll(PageRequest.of(page - 1, size), userId);
|
||||||
return ApiResponse.success(tasks);
|
return ApiResponse.success(tasks);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("查询课程任务列表失败", e);
|
// logger.error("查询课程任务列表失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务列表失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务列表失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public ApiResponse<LessonTask> getTask(@PathVariable Long id) {
|
public ApiResponse<LessonTask> getTask(@PathVariable Long id) {
|
||||||
logger.info("收到课程任务查询请求,任务ID: {}", id);
|
// logger.info("收到课程任务查询请求,任务ID: {}", id);
|
||||||
try {
|
try {
|
||||||
LessonTask task = lessonTaskService.findById(id);
|
LessonTask task = lessonTaskService.findById(id);
|
||||||
return ApiResponse.success(task);
|
return ApiResponse.success(task);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("查询课程任务失败", e);
|
// logger.error("查询课程任务失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取课程任务失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -57,49 +57,49 @@ public class LessonTaskController {
|
|||||||
@PathVariable Long departmentId,
|
@PathVariable Long departmentId,
|
||||||
@RequestParam(defaultValue = "1") Integer page,
|
@RequestParam(defaultValue = "1") Integer page,
|
||||||
@RequestParam(defaultValue = "10") Integer size) {
|
@RequestParam(defaultValue = "10") Integer size) {
|
||||||
logger.info("收到部门课程任务查询请求,部门ID: {}", departmentId);
|
// logger.info("收到部门课程任务查询请求,部门ID: {}", departmentId);
|
||||||
try {
|
try {
|
||||||
PageRequest pageRequest = PageRequest.of(page - 1, size);
|
PageRequest pageRequest = PageRequest.of(page - 1, size);
|
||||||
Page<LessonTaskDTO> tasks = lessonTaskService.findByDepartmentIdAndNormalUser(departmentId, pageRequest);
|
Page<LessonTaskDTO> tasks = lessonTaskService.findByDepartmentIdAndNormalUser(departmentId, pageRequest);
|
||||||
return ApiResponse.success(tasks);
|
return ApiResponse.success(tasks);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("查询部门课程任务失败", e);
|
// logger.error("查询部门课程任务失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门课程任务失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门课程任务失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ApiResponse<LessonTask> createTask(@Valid @RequestBody LessonTaskRequest request) {
|
public ApiResponse<LessonTask> createTask(@Valid @RequestBody LessonTaskRequest request) {
|
||||||
logger.info("收到创建课程任务请求");
|
// logger.info("收到创建课程任务请求");
|
||||||
try {
|
try {
|
||||||
LessonTask task = lessonTaskService.create(request);
|
LessonTask task = lessonTaskService.create(request);
|
||||||
return ApiResponse.success(task);
|
return ApiResponse.success(task);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("创建课程任务失败", e);
|
// logger.error("创建课程任务失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "创建课程任务失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "创建课程任务失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
public ApiResponse<LessonTask> updateTask(@PathVariable Long id, @Valid @RequestBody LessonTaskRequest request) {
|
public ApiResponse<LessonTask> updateTask(@PathVariable Long id, @Valid @RequestBody LessonTaskRequest request) {
|
||||||
logger.info("收到更新课程任务请求,任务ID: {}", id);
|
// logger.info("收到更新课程任务请求,任务ID: {}", id);
|
||||||
try {
|
try {
|
||||||
LessonTask task = lessonTaskService.update(id, request);
|
LessonTask task = lessonTaskService.update(id, request);
|
||||||
return ApiResponse.success(task);
|
return ApiResponse.success(task);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("更新课程任务失败", e);
|
// logger.error("更新课程任务失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "更新课程任务失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "更新课程任务失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public ApiResponse<Void> deleteTask(@PathVariable Long id) {
|
public ApiResponse<Void> deleteTask(@PathVariable Long id) {
|
||||||
logger.info("收到删除课程任务请求,任务ID: {}", id);
|
// logger.info("收到删除课程任务请求,任务ID: {}", id);
|
||||||
try {
|
try {
|
||||||
lessonTaskService.delete(id);
|
lessonTaskService.delete(id);
|
||||||
return ApiResponse.success();
|
return ApiResponse.success();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("删除课程任务失败", e);
|
// logger.error("删除课程任务失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "删除课程任务失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "删除课程任务失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,9 +38,9 @@ public class UserController {
|
|||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public ApiResponse<LoginResponse> login(@Valid @RequestBody UserLoginRequest request) {
|
public ApiResponse<LoginResponse> login(@Valid @RequestBody UserLoginRequest request) {
|
||||||
logger.info("收到登录请求,邮箱: {}", request.getEmail());
|
// logger.info("收到登录请求,邮箱: {}", request.getEmail());
|
||||||
ApiResponse<LoginResponse> response = userService.login(request);
|
ApiResponse<LoginResponse> response = userService.login(request);
|
||||||
logger.info("登录响应: {}", response);
|
// logger.info("登录响应: {}", response);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,19 +59,19 @@ public class UserController {
|
|||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ApiResponse<Void> createUser(@Valid @RequestBody CreateUserRequest request) {
|
public ApiResponse<Void> createUser(@Valid @RequestBody CreateUserRequest request) {
|
||||||
logger.info("收到创建用户请求,用户名: {}", request.getUsername());
|
// logger.info("收到创建用户请求,用户名: {}", request.getUsername());
|
||||||
return userService.createUser(request);
|
return userService.createUser(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/current")
|
@GetMapping("/current")
|
||||||
public ApiResponse<User> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
|
public ApiResponse<User> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
|
||||||
logger.info("收到获取当前用户信息请求,Authorization: {}", authHeader);
|
// logger.info("收到获取当前用户信息请求,Authorization: {}", authHeader);
|
||||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
String token = authHeader.substring(7);
|
String token = authHeader.substring(7);
|
||||||
logger.info("解析出的token: {}", token);
|
// logger.info("解析出的token: {}", token);
|
||||||
return userService.getCurrentUser(token);
|
return userService.getCurrentUser(token);
|
||||||
}
|
}
|
||||||
logger.warn("未提供有效的认证令牌");
|
// logger.warn("未提供有效的认证令牌");
|
||||||
return ApiResponse.error(401, "未提供有效的认证令牌");
|
return ApiResponse.error(401, "未提供有效的认证令牌");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,37 +79,37 @@ public class UserController {
|
|||||||
public ApiResponse<?> listUsers(
|
public ApiResponse<?> listUsers(
|
||||||
@RequestParam(defaultValue = "1") Integer page,
|
@RequestParam(defaultValue = "1") Integer page,
|
||||||
@RequestParam(defaultValue = "10") Integer limit) {
|
@RequestParam(defaultValue = "10") Integer limit) {
|
||||||
logger.info("收到用户列表分页查询请求,页码: {},每页数量: {}", page, limit);
|
// logger.info("收到用户列表分页查询请求,页码: {},每页数量: {}", page, limit);
|
||||||
return userService.listUsers(page, limit);
|
return userService.listUsers(page, limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/disable/{userId}")
|
@PostMapping("/disable/{userId}")
|
||||||
public ApiResponse<String> disableUser(@PathVariable Long userId) {
|
public ApiResponse<String> disableUser(@PathVariable Long userId) {
|
||||||
logger.info("收到禁用用户请求,用户ID: {}", userId);
|
// logger.info("收到禁用用户请求,用户ID: {}", userId);
|
||||||
return userService.disableUser(userId);
|
return userService.disableUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/department/{departmentId}")
|
@GetMapping("/department/{departmentId}")
|
||||||
public ApiResponse<List<User>> getUsersByDepartment(@PathVariable Long departmentId) {
|
public ApiResponse<List<User>> getUsersByDepartment(@PathVariable Long departmentId) {
|
||||||
logger.info("收到查询部门用户请求,部门ID: {}", departmentId);
|
// logger.info("收到查询部门用户请求,部门ID: {}", departmentId);
|
||||||
try {
|
try {
|
||||||
List<User> users = userService.findByDepartmentId(departmentId);
|
List<User> users = userService.findByDepartmentId(departmentId);
|
||||||
// 清除密码信息
|
// 清除密码信息
|
||||||
users.forEach(user -> user.setPassword(null));
|
users.forEach(user -> user.setPassword(null));
|
||||||
return ApiResponse.success(users);
|
return ApiResponse.success(users);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("查询部门用户失败", e);
|
// logger.error("查询部门用户失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门用户列表失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "获取部门用户列表失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/teacher/search")
|
@GetMapping("/teacher/search")
|
||||||
public ApiResponse<User> searchTeacher(@RequestParam String email) {
|
public ApiResponse<User> searchTeacher(@RequestParam String email) {
|
||||||
logger.info("收到查询教师信息请求,邮箱: {}", email);
|
// logger.info("收到查询教师信息请求,邮箱: {}", email);
|
||||||
try {
|
try {
|
||||||
return userService.findTeacherByEmail(email);
|
return userService.findTeacherByEmail(email);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("查询教师信息失败", e);
|
// logger.error("查询教师信息失败", e);
|
||||||
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "查询教师信息失败", null);
|
return new ApiResponse<>(ErrorCode.SYSTEM_ERROR, "查询教师信息失败", null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -49,21 +49,21 @@ public class LessonTask implements Serializable {
|
|||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
logger.info("创建新课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
|
// logger.info("创建新课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
|
||||||
this.courseName, this.microLessonName, this.userId);
|
// this.courseName, this.microLessonName, this.userId);
|
||||||
progressStatus = 0;
|
progressStatus = 0;
|
||||||
long now = System.currentTimeMillis() / 1000;
|
long now = System.currentTimeMillis() / 1000;
|
||||||
createdAt = now;
|
createdAt = now;
|
||||||
updatedAt = now;
|
updatedAt = now;
|
||||||
logger.info("创建课程任务成功 - 进度状态: {}, 创建时间: {}, 更新时间: {}",
|
// logger.info("创建课程任务成功 - 进度状态: {}, 创建时间: {}, 更新时间: {}",
|
||||||
progressStatus, createdAt, updatedAt);
|
// progressStatus, createdAt, updatedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PreUpdate
|
@PreUpdate
|
||||||
protected void onUpdate() {
|
protected void onUpdate() {
|
||||||
logger.info("更新课程任务 - ID: {}, 课程名称: {}, 微课名称: {}",
|
// logger.info("更新课程任务 - ID: {}, 课程名称: {}, 微课名称: {}",
|
||||||
this.id, this.courseName, this.microLessonName);
|
// this.id, this.courseName, this.microLessonName);
|
||||||
updatedAt = System.currentTimeMillis() / 1000;
|
updatedAt = System.currentTimeMillis() / 1000;
|
||||||
logger.info("更新课程任务成功 - ID: {}, 更新时间: {}", id, updatedAt);
|
// logger.info("更新课程任务成功 - ID: {}, 更新时间: {}", id, updatedAt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,15 +25,15 @@ public class CustomUserDetailsService implements UserDetailsService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||||
logger.info("Loading user details for email: {}", email);
|
// logger.info("Loading user details for email: {}", email);
|
||||||
|
|
||||||
User user = userRepository.findByEmail(email)
|
User user = userRepository.findByEmail(email)
|
||||||
.orElseThrow(() -> {
|
.orElseThrow(() -> {
|
||||||
logger.error("User not found with email: {}", email);
|
// logger.error("User not found with email: {}", email);
|
||||||
return new UsernameNotFoundException("User not found with email: " + email);
|
return new UsernameNotFoundException("User not found with email: " + email);
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.info("User found with email: {}", email);
|
// logger.info("User found with email: {}", email);
|
||||||
|
|
||||||
return new org.springframework.security.core.userdetails.User(
|
return new org.springframework.security.core.userdetails.User(
|
||||||
user.getEmail(),
|
user.getEmail(),
|
||||||
|
@ -51,29 +51,29 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
try {
|
try {
|
||||||
// 允许OPTIONS请求通过
|
// 允许OPTIONS请求通过
|
||||||
if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
|
if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
|
||||||
logger.debug("OPTIONS请求,直接放行");
|
// logger.debug("OPTIONS请求,直接放行");
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final String authHeader = request.getHeader("Authorization");
|
final String authHeader = request.getHeader("Authorization");
|
||||||
logger.debug("处理请求认证 - 请求路径: {}", request.getRequestURI());
|
// logger.debug("处理请求认证 - 请求路径: {}", request.getRequestURI());
|
||||||
|
|
||||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
logger.debug("未提供认证令牌或格式不正确");
|
// logger.debug("未提供认证令牌或格式不正确");
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final String jwt = authHeader.substring(7);
|
final String jwt = authHeader.substring(7);
|
||||||
logger.debug("Received JWT token: {}", jwt);
|
// logger.debug("Received JWT token: {}", jwt);
|
||||||
final String username = jwtService.extractUsername(jwt);
|
final String username = jwtService.extractUsername(jwt);
|
||||||
|
|
||||||
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||||
logger.debug("开始验证用户令牌 - 用户邮箱: {}", username);
|
// logger.debug("开始验证用户令牌 - 用户邮箱: {}", username);
|
||||||
|
|
||||||
if (tokenBlacklistService.isBlacklisted(jwt)) {
|
if (tokenBlacklistService.isBlacklisted(jwt)) {
|
||||||
logger.warn("令牌已被加入黑名单");
|
// logger.warn("令牌已被加入黑名单");
|
||||||
handleJwtException(response, "令牌已被加入黑名单");
|
handleJwtException(response, "令牌已被加入黑名单");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -81,7 +81,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
|
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
|
||||||
|
|
||||||
if (jwtService.isTokenValid(jwt, userDetails)) {
|
if (jwtService.isTokenValid(jwt, userDetails)) {
|
||||||
logger.debug("令牌验证成功,设置安全上下文");
|
// logger.debug("令牌验证成功,设置安全上下文");
|
||||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||||
userDetails,
|
userDetails,
|
||||||
null,
|
null,
|
||||||
@ -89,7 +89,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||||
} else {
|
} else {
|
||||||
logger.warn("令牌验证失败");
|
// logger.warn("令牌验证失败");
|
||||||
handleJwtException(response, "令牌验证失败");
|
handleJwtException(response, "令牌验证失败");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -48,8 +48,8 @@ public class JwtService {
|
|||||||
public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {
|
public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {
|
||||||
Date issuedAt = new Date(System.currentTimeMillis() / 1000 * 1000);
|
Date issuedAt = new Date(System.currentTimeMillis() / 1000 * 1000);
|
||||||
Date expiration = new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000);
|
Date expiration = new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000);
|
||||||
logger.debug("Generating token for user: {}, expiration: {}, jwtExpiration: {}", userDetails.getUsername(),
|
// logger.debug("Generating token for user: {}, expiration: {}, jwtExpiration: {}", userDetails.getUsername(),
|
||||||
expiration, jwtExpiration);
|
// expiration, jwtExpiration);
|
||||||
|
|
||||||
return Jwts.builder()
|
return Jwts.builder()
|
||||||
.setClaims(extraClaims)
|
.setClaims(extraClaims)
|
||||||
|
@ -25,18 +25,18 @@ public class TokenBlacklistService {
|
|||||||
* @param expiration 过期时间(秒)
|
* @param expiration 过期时间(秒)
|
||||||
*/
|
*/
|
||||||
public void addToBlacklist(String token, long expiration) {
|
public void addToBlacklist(String token, long expiration) {
|
||||||
logger.info("将令牌加入黑名单 - 过期时间: {}", new Date(expiration * 1000));
|
// logger.info("将令牌加入黑名单 - 过期时间: {}", new Date(expiration * 1000));
|
||||||
try {
|
try {
|
||||||
String key = BLACKLIST_PREFIX + token;
|
String key = BLACKLIST_PREFIX + token;
|
||||||
long ttl = expiration - System.currentTimeMillis() / 1000;
|
long ttl = expiration - System.currentTimeMillis() / 1000;
|
||||||
if (ttl > 0) {
|
if (ttl > 0) {
|
||||||
redisTemplate.opsForValue().set(key, "blacklisted", ttl, TimeUnit.SECONDS);
|
redisTemplate.opsForValue().set(key, "blacklisted", ttl, TimeUnit.SECONDS);
|
||||||
logger.info("令牌已成功加入黑名单");
|
// logger.info("令牌已成功加入黑名单");
|
||||||
} else {
|
} else {
|
||||||
logger.warn("令牌已过期,无需加入黑名单");
|
// logger.warn("令牌已过期,无需加入黑名单");
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("将令牌加入黑名单时发生错误", e);
|
// logger.error("将令牌加入黑名单时发生错误", e);
|
||||||
throw new RuntimeException("无法将令牌加入黑名单", e);
|
throw new RuntimeException("无法将令牌加入黑名单", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -48,14 +48,14 @@ public class TokenBlacklistService {
|
|||||||
* @return 如果在黑名单中返回true
|
* @return 如果在黑名单中返回true
|
||||||
*/
|
*/
|
||||||
public boolean isBlacklisted(String token) {
|
public boolean isBlacklisted(String token) {
|
||||||
logger.debug("检查令牌是否在黑名单中");
|
// logger.debug("检查令牌是否在黑名单中");
|
||||||
try {
|
try {
|
||||||
String key = BLACKLIST_PREFIX + token;
|
String key = BLACKLIST_PREFIX + token;
|
||||||
Boolean exists = redisTemplate.hasKey(key);
|
Boolean exists = redisTemplate.hasKey(key);
|
||||||
logger.debug("令牌黑名单检查结果: {}", exists);
|
// logger.debug("令牌黑名单检查结果: {}", exists);
|
||||||
return Boolean.TRUE.equals(exists);
|
return Boolean.TRUE.equals(exists);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("检查令牌黑名单状态时发生错误", e);
|
// logger.error("检查令牌黑名单状态时发生错误", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,15 +19,15 @@ public class UserDetailsService implements org.springframework.security.core.use
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||||
logger.info("开始加载用户信息 - 邮箱: {}", email);
|
// logger.info("开始加载用户信息 - 邮箱: {}", email);
|
||||||
|
|
||||||
User user = userRepository.findByEmail(email)
|
User user = userRepository.findByEmail(email)
|
||||||
.orElseThrow(() -> {
|
.orElseThrow(() -> {
|
||||||
logger.error("未找到用户 - 邮箱: {}", email);
|
// logger.error("未找到用户 - 邮箱: {}", email);
|
||||||
return new UsernameNotFoundException("未找到用户");
|
return new UsernameNotFoundException("未找到用户");
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.info("成功加载用户信息 - 用户名: {}", user.getUsername());
|
// logger.info("成功加载用户信息 - 用户名: {}", user.getUsername());
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -56,7 +56,7 @@ public class DepartmentService {
|
|||||||
departmentRepository.save(department);
|
departmentRepository.save(department);
|
||||||
successCount++;
|
successCount++;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("导入第{}行数据失败", i + 2, e);
|
// logger.error("导入第{}行数据失败", i + 2, e);
|
||||||
errorMsg.append(String.format("第%d行导入失败;", i + 2));
|
errorMsg.append(String.format("第%d行导入失败;", i + 2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -36,8 +36,8 @@ public class LessonTaskService {
|
|||||||
|
|
||||||
@Cacheable(value = "lessonTasks", key = "#userId != null ? 'user:' + #userId + ':page:' + #pageable.pageNumber : 'all:page:' + #pageable.pageNumber")
|
@Cacheable(value = "lessonTasks", key = "#userId != null ? 'user:' + #userId + ':page:' + #pageable.pageNumber : 'all:page:' + #pageable.pageNumber")
|
||||||
public Page<LessonTask> findAll(Pageable pageable, Long userId) {
|
public Page<LessonTask> findAll(Pageable pageable, Long userId) {
|
||||||
logger.info("查询课程任务 - 页码: {}, 每页数量: {}, 用户ID: {}",
|
// logger.info("查询课程任务 - 页码: {}, 每页数量: {}, 用户ID: {}",
|
||||||
pageable.getPageNumber(), pageable.getPageSize(), userId);
|
// pageable.getPageNumber(), pageable.getPageSize(), userId);
|
||||||
|
|
||||||
Page<LessonTask> result;
|
Page<LessonTask> result;
|
||||||
if (userId != null) {
|
if (userId != null) {
|
||||||
@ -46,16 +46,16 @@ public class LessonTaskService {
|
|||||||
result = lessonTaskRepository.findAll(pageable);
|
result = lessonTaskRepository.findAll(pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("查询到 {} 条课程任务", result.getTotalElements());
|
// logger.info("查询到 {} 条课程任务", result.getTotalElements());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Cacheable(value = "lessonTask", key = "#id")
|
@Cacheable(value = "lessonTask", key = "#id")
|
||||||
public LessonTask findById(Long id) {
|
public LessonTask findById(Long id) {
|
||||||
logger.info("根据ID查询课程任务 - 任务ID: {}", id);
|
// logger.info("根据ID查询课程任务 - 任务ID: {}", id);
|
||||||
return lessonTaskRepository.findById(id)
|
return lessonTaskRepository.findById(id)
|
||||||
.orElseThrow(() -> {
|
.orElseThrow(() -> {
|
||||||
logger.error("未找到ID为 {} 的课程任务", id);
|
// logger.error("未找到ID为 {} 的课程任务", id);
|
||||||
return new EntityNotFoundException("未找到ID为 " + id + " 的任务");
|
return new EntityNotFoundException("未找到ID为 " + id + " 的任务");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -63,21 +63,21 @@ public class LessonTaskService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
||||||
public LessonTask create(LessonTaskRequest request) {
|
public LessonTask create(LessonTaskRequest request) {
|
||||||
logger.info("开始创建课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
|
// logger.info("开始创建课程任务 - 课程名称: {}, 微课名称: {}, 用户ID: {}",
|
||||||
request.getCourseName(), request.getMicroLessonName(), request.getUserId());
|
// request.getCourseName(), request.getMicroLessonName(), request.getUserId());
|
||||||
validateRequest(request);
|
validateRequest(request);
|
||||||
LessonTask task = new LessonTask();
|
LessonTask task = new LessonTask();
|
||||||
BeanUtils.copyProperties(request, task);
|
BeanUtils.copyProperties(request, task);
|
||||||
task.setProgressStatus(0); // 初始状态:未开始
|
task.setProgressStatus(0); // 初始状态:未开始
|
||||||
LessonTask savedTask = lessonTaskRepository.save(task);
|
LessonTask savedTask = lessonTaskRepository.save(task);
|
||||||
logger.info("创建课程任务成功 - 任务ID: {}", savedTask.getId());
|
// logger.info("创建课程任务成功 - 任务ID: {}", savedTask.getId());
|
||||||
return savedTask;
|
return savedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
||||||
public LessonTask update(Long id, LessonTaskRequest request) {
|
public LessonTask update(Long id, LessonTaskRequest request) {
|
||||||
logger.info("开始更新课程任务 - 任务ID: {}, 进度状态: {}", id, request.getProgressStatus());
|
// logger.info("开始更新课程任务 - 任务ID: {}, 进度状态: {}", id, request.getProgressStatus());
|
||||||
LessonTask task = findById(id);
|
LessonTask task = findById(id);
|
||||||
|
|
||||||
// 只更新非空字段
|
// 只更新非空字段
|
||||||
@ -141,20 +141,20 @@ public class LessonTaskService {
|
|||||||
|
|
||||||
task.setUpdatedAt(System.currentTimeMillis() / 1000);
|
task.setUpdatedAt(System.currentTimeMillis() / 1000);
|
||||||
LessonTask updatedTask = lessonTaskRepository.save(task);
|
LessonTask updatedTask = lessonTaskRepository.save(task);
|
||||||
logger.info("更新课程任务成功 - 任务ID: {}", updatedTask.getId());
|
// logger.info("更新课程任务成功 - 任务ID: {}", updatedTask.getId());
|
||||||
return updatedTask;
|
return updatedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
@CacheEvict(value = { "lessonTasks", "lessonTask" }, allEntries = true)
|
||||||
public void delete(Long id) {
|
public void delete(Long id) {
|
||||||
logger.info("开始删除课程任务 - 任务ID: {}", id);
|
// logger.info("开始删除课程任务 - 任务ID: {}", id);
|
||||||
if (!lessonTaskRepository.existsById(id)) {
|
if (!lessonTaskRepository.existsById(id)) {
|
||||||
logger.error("未找到ID为 {} 的课程任务", id);
|
// logger.error("未找到ID为 {} 的课程任务", id);
|
||||||
throw new EntityNotFoundException("未找到ID为 " + id + " 的任务");
|
throw new EntityNotFoundException("未找到ID为 " + id + " 的任务");
|
||||||
}
|
}
|
||||||
lessonTaskRepository.deleteById(id);
|
lessonTaskRepository.deleteById(id);
|
||||||
logger.info("删除课程任务成功 - 任务ID: {}", id);
|
// logger.info("删除课程任务成功 - 任务ID: {}", id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -165,7 +165,7 @@ public class LessonTaskService {
|
|||||||
* @return 课程任务分页数据
|
* @return 课程任务分页数据
|
||||||
*/
|
*/
|
||||||
public Page<LessonTaskDTO> findByDepartmentIdAndNormalUser(Long departmentId, Pageable pageable) {
|
public Page<LessonTaskDTO> findByDepartmentIdAndNormalUser(Long departmentId, Pageable pageable) {
|
||||||
logger.info("查询部门正常用户的课程任务,部门ID: {}", departmentId);
|
// logger.info("查询部门正常用户的课程任务,部门ID: {}", departmentId);
|
||||||
Page<java.util.Map<String, Object>> result = lessonTaskRepository
|
Page<java.util.Map<String, Object>> result = lessonTaskRepository
|
||||||
.findByDepartmentIdAndNormalUserWithUsername(departmentId, pageable);
|
.findByDepartmentIdAndNormalUserWithUsername(departmentId, pageable);
|
||||||
|
|
||||||
@ -185,7 +185,7 @@ public class LessonTaskService {
|
|||||||
* @return 课程任务分页数据
|
* @return 课程任务分页数据
|
||||||
*/
|
*/
|
||||||
public Page<LessonTask> findByDepartmentIdAndStatus(Long departmentId, Integer status, Pageable pageable) {
|
public Page<LessonTask> findByDepartmentIdAndStatus(Long departmentId, Integer status, Pageable pageable) {
|
||||||
logger.info("查询部门课程任务,部门ID: {}, 状态: {}", departmentId, status);
|
// logger.info("查询部门课程任务,部门ID: {}, 状态: {}", departmentId, status);
|
||||||
return lessonTaskRepository.findByDepartmentIdAndStatus(departmentId, status, pageable);
|
return lessonTaskRepository.findByDepartmentIdAndStatus(departmentId, status, pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,7 +198,7 @@ public class LessonTaskService {
|
|||||||
* @return 课程任务分页数据
|
* @return 课程任务分页数据
|
||||||
*/
|
*/
|
||||||
public Page<LessonTask> findByDepartmentIdAndUserStatus(Long departmentId, Integer userStatus, Pageable pageable) {
|
public Page<LessonTask> findByDepartmentIdAndUserStatus(Long departmentId, Integer userStatus, Pageable pageable) {
|
||||||
logger.info("查询部门课程任务,部门ID: {}, 用户状态: {}", departmentId, userStatus);
|
// logger.info("查询部门课程任务,部门ID: {}, 用户状态: {}", departmentId, userStatus);
|
||||||
return lessonTaskRepository.findByDepartmentIdAndUserStatus(departmentId, userStatus, pageable);
|
return lessonTaskRepository.findByDepartmentIdAndUserStatus(departmentId, userStatus, pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -88,15 +88,15 @@ public class UserService implements UserDetailsService {
|
|||||||
|
|
||||||
public ApiResponse<User> getCurrentUser(String token) {
|
public ApiResponse<User> getCurrentUser(String token) {
|
||||||
String email = jwtService.extractUsername(token);
|
String email = jwtService.extractUsername(token);
|
||||||
logger.info("从token中提取的邮箱: {}", email);
|
// logger.info("从token中提取的邮箱: {}", email);
|
||||||
Optional<User> userOpt = userRepository.findByEmail(email);
|
Optional<User> userOpt = userRepository.findByEmail(email);
|
||||||
if (userOpt.isEmpty()) {
|
if (userOpt.isEmpty()) {
|
||||||
logger.warn("用户不存在: {}", email);
|
// logger.warn("用户不存在: {}", email);
|
||||||
return new ApiResponse<>(ErrorCode.USER_NOT_FOUND, "用户不存在", null);
|
return new ApiResponse<>(ErrorCode.USER_NOT_FOUND, "用户不存在", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
User user = userOpt.get();
|
User user = userOpt.get();
|
||||||
logger.info("找到用户: {}", user.getUsername());
|
// logger.info("找到用户: {}", user.getUsername());
|
||||||
user.setPassword(null);
|
user.setPassword(null);
|
||||||
return ApiResponse.success(user);
|
return ApiResponse.success(user);
|
||||||
}
|
}
|
||||||
@ -172,7 +172,7 @@ public class UserService implements UserDetailsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<User> findByDepartmentId(Long departmentId) {
|
public List<User> findByDepartmentId(Long departmentId) {
|
||||||
logger.info("查询部门用户列表,部门ID: {}", departmentId);
|
// logger.info("查询部门用户列表,部门ID: {}", departmentId);
|
||||||
return userRepository.findByDepartmentIdAndNormalStatus(departmentId);
|
return userRepository.findByDepartmentIdAndNormalStatus(departmentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -222,7 +222,7 @@ public class UserService implements UserDetailsService {
|
|||||||
|
|
||||||
// 查找部门ID
|
// 查找部门ID
|
||||||
Department department = departmentRepository.findByName(dto.getDepartmentName());
|
Department department = departmentRepository.findByName(dto.getDepartmentName());
|
||||||
logger.info("查找部门:{},结果:{}", dto.getDepartmentName(), department);
|
// logger.info("查找部门:{},结果:{}", dto.getDepartmentName(), department);
|
||||||
if (department == null) {
|
if (department == null) {
|
||||||
errorMsg.append(String.format("第%d行部门不存在;", i + 2));
|
errorMsg.append(String.format("第%d行部门不存在;", i + 2));
|
||||||
continue;
|
continue;
|
||||||
@ -242,12 +242,12 @@ public class UserService implements UserDetailsService {
|
|||||||
user.setRoles(Integer.parseInt(roleAndJob));
|
user.setRoles(Integer.parseInt(roleAndJob));
|
||||||
user.setJobs(Integer.parseInt(roleAndJob));
|
user.setJobs(Integer.parseInt(roleAndJob));
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
logger.warn("角色/岗位不是有效的数字: {}", roleAndJob);
|
// logger.warn("角色/岗位不是有效的数字: {}", roleAndJob);
|
||||||
errorMsg.append(String.format("第%d行角色/岗位不是有效的数字;", i + 2));
|
errorMsg.append(String.format("第%d行角色/岗位不是有效的数字;", i + 2));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.warn("角色/岗位不能为空");
|
// logger.warn("角色/岗位不能为空");
|
||||||
errorMsg.append(String.format("第%d行角色/岗位不能为空;", i + 2));
|
errorMsg.append(String.format("第%d行角色/岗位不能为空;", i + 2));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -265,11 +265,11 @@ public class UserService implements UserDetailsService {
|
|||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
successCount++;
|
successCount++;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("保存用户失败", e);
|
// logger.error("保存用户失败", e);
|
||||||
errorMsg.append(String.format("第%d行保存失败: %s;", i + 2, e.getMessage()));
|
errorMsg.append(String.format("第%d行保存失败: %s;", i + 2, e.getMessage()));
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("导入第{}行数据失败", i + 2, e);
|
// logger.error("导入第{}行数据失败", i + 2, e);
|
||||||
errorMsg.append(String.format("第%d行导入失败;", i + 2));
|
errorMsg.append(String.format("第%d行导入失败;", i + 2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,16 +29,16 @@ public class JwtUtil {
|
|||||||
private long jwtExpiration;
|
private long jwtExpiration;
|
||||||
|
|
||||||
public String extractUsername(String token) {
|
public String extractUsername(String token) {
|
||||||
logger.debug("开始从token中提取用户名");
|
// logger.debug("开始从token中提取用户名");
|
||||||
try {
|
try {
|
||||||
String username = extractClaim(token, Claims::getSubject);
|
String username = extractClaim(token, Claims::getSubject);
|
||||||
logger.debug("提取的用户名: {}", username);
|
// logger.debug("提取的用户名: {}", username);
|
||||||
return username;
|
return username;
|
||||||
} catch (ExpiredJwtException e) {
|
} catch (ExpiredJwtException e) {
|
||||||
logger.error("token已过期", e);
|
// logger.error("token已过期", e);
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("从token中提取用户名时发生错误", e);
|
// logger.error("从token中提取用户名时发生错误", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -53,7 +53,7 @@ public class JwtUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Claims extractAllClaims(String token) {
|
private Claims extractAllClaims(String token) {
|
||||||
logger.debug("开始从token中提取所有声明");
|
// logger.debug("开始从token中提取所有声明");
|
||||||
try {
|
try {
|
||||||
Claims claims = Jwts
|
Claims claims = Jwts
|
||||||
.parserBuilder()
|
.parserBuilder()
|
||||||
@ -61,10 +61,10 @@ public class JwtUtil {
|
|||||||
.build()
|
.build()
|
||||||
.parseClaimsJws(token)
|
.parseClaimsJws(token)
|
||||||
.getBody();
|
.getBody();
|
||||||
logger.debug("声明提取成功");
|
// logger.debug("声明提取成功");
|
||||||
return claims;
|
return claims;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("从token中提取声明时发生错误", e);
|
// logger.error("从token中提取声明时发生错误", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -73,16 +73,16 @@ public class JwtUtil {
|
|||||||
try {
|
try {
|
||||||
Date expiration = extractExpiration(token);
|
Date expiration = extractExpiration(token);
|
||||||
boolean isExpired = expiration.before(new Date());
|
boolean isExpired = expiration.before(new Date());
|
||||||
logger.debug("token过期检查 - 过期时间: {}, 是否过期: {}", expiration, isExpired);
|
// logger.debug("token过期检查 - 过期时间: {}, 是否过期: {}", expiration, isExpired);
|
||||||
return isExpired;
|
return isExpired;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("检查token过期时发生错误", e);
|
// logger.error("检查token过期时发生错误", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String generateToken(String userName) {
|
public String generateToken(String userName) {
|
||||||
logger.debug("开始为用户创建token: {}", userName);
|
// logger.debug("开始为用户创建token: {}", userName);
|
||||||
try {
|
try {
|
||||||
Map<String, Object> claims = new HashMap<>();
|
Map<String, Object> claims = new HashMap<>();
|
||||||
String token = Jwts.builder()
|
String token = Jwts.builder()
|
||||||
@ -92,24 +92,24 @@ public class JwtUtil {
|
|||||||
.setExpiration(new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000))
|
.setExpiration(new Date((System.currentTimeMillis() / 1000 + jwtExpiration / 1000) * 1000))
|
||||||
.signWith(getSignKey(), SignatureAlgorithm.HS384)
|
.signWith(getSignKey(), SignatureAlgorithm.HS384)
|
||||||
.compact();
|
.compact();
|
||||||
logger.debug("token创建成功");
|
// logger.debug("token创建成功");
|
||||||
return token;
|
return token;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("创建token时发生错误", e);
|
// logger.error("创建token时发生错误", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Boolean validateToken(String token, User user) {
|
public Boolean validateToken(String token, User user) {
|
||||||
logger.debug("开始验证用户token: {}", user.getUsername());
|
// logger.debug("开始验证用户token: {}", user.getUsername());
|
||||||
try {
|
try {
|
||||||
final String username = extractUsername(token);
|
final String username = extractUsername(token);
|
||||||
boolean isValid = username.equals(user.getUsername()) && !isTokenExpired(token);
|
boolean isValid = username.equals(user.getUsername()) && !isTokenExpired(token);
|
||||||
logger.debug("token验证结果 - 用户名匹配: {}, 未过期: {}",
|
// logger.debug("token验证结果 - 用户名匹配: {}, 未过期: {}",
|
||||||
username.equals(user.getUsername()), !isTokenExpired(token));
|
// username.equals(user.getUsername()), !isTokenExpired(token));
|
||||||
return isValid;
|
return isValid;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("验证token时发生错误", e);
|
// logger.error("验证token时发生错误", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
# 数据库配置
|
# 数据库配置
|
||||||
spring.datasource.url=jdbc:mysql://172.16.215.132:3306/fenshenzhike?useSSL=false&serverTimezone=UTC
|
spring.datasource.url=jdbc:mysql://8.137.89.177:3306/jinduguanli?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
|
||||||
spring.datasource.username=root
|
spring.datasource.username=jinduguanli
|
||||||
spring.datasource.password=123
|
spring.datasource.password=root041218
|
||||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||||
|
|
||||||
server.port=1218
|
server.port=1218
|
||||||
|
@ -5,9 +5,9 @@ spring:
|
|||||||
main:
|
main:
|
||||||
banner-mode: console
|
banner-mode: console
|
||||||
datasource:
|
datasource:
|
||||||
url: jdbc:mysql://172.16.215.132:3306/fenshenzhike?useSSL=false&serverTimezone=UTC
|
url: jdbc:mysql://8.137.89.177:3306/jinduguanli?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
|
||||||
username: root
|
username: jinduguanli
|
||||||
password: 123
|
password: root041218
|
||||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
jpa:
|
jpa:
|
||||||
show-sql: true
|
show-sql: true
|
||||||
@ -18,7 +18,7 @@ spring:
|
|||||||
format_sql: true
|
format_sql: true
|
||||||
use_sql_comments: true
|
use_sql_comments: true
|
||||||
redis:
|
redis:
|
||||||
host: 172.16.215.132
|
host: 8.137.89.177
|
||||||
port: 6379
|
port: 6379
|
||||||
database: 0
|
database: 0
|
||||||
timeout: 10000
|
timeout: 10000
|
||||||
@ -37,7 +37,7 @@ spring:
|
|||||||
|
|
||||||
jwt:
|
jwt:
|
||||||
secret: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
|
secret: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
|
||||||
expiration: 86400000 # 24小时
|
expiration: 2592000000 # 24小时
|
||||||
|
|
||||||
logging:
|
logging:
|
||||||
level:
|
level:
|
||||||
|
Reference in New Issue
Block a user