88 lines
2.2 KiB
Java
88 lines
2.2 KiB
Java
package com.emotion.util;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
/**
|
|
* 当前用户工具类
|
|
* 提供便捷的方法获取当前登录用户信息
|
|
*
|
|
* @author emotion-museum
|
|
* @date 2025-07-25
|
|
*/
|
|
@Slf4j
|
|
public class CurrentUserUtil {
|
|
|
|
/**
|
|
* 获取当前用户ID
|
|
*
|
|
* @return 当前用户ID,如果未登录则返回null
|
|
*/
|
|
public static String getCurrentUserId() {
|
|
return UserContextHolder.getCurrentUserId();
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户名
|
|
*
|
|
* @return 当前用户名,如果未登录则返回null
|
|
*/
|
|
public static String getCurrentUsername() {
|
|
return UserContextHolder.getCurrentUsername();
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户Token
|
|
*
|
|
* @return 当前用户Token,如果未登录则返回null
|
|
*/
|
|
public static String getCurrentToken() {
|
|
return UserContextHolder.getCurrentToken();
|
|
}
|
|
|
|
/**
|
|
* 检查当前是否有用户登录
|
|
*
|
|
* @return 是否有用户登录
|
|
*/
|
|
public static boolean isUserLoggedIn() {
|
|
return UserContextHolder.hasUserContext();
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户ID,如果未登录则抛出异常
|
|
*
|
|
* @return 当前用户ID
|
|
* @throws IllegalStateException 如果用户未登录
|
|
*/
|
|
public static String requireCurrentUserId() {
|
|
String userId = getCurrentUserId();
|
|
if (userId == null || userId.trim().isEmpty()) {
|
|
throw new IllegalStateException("用户未登录或认证失败");
|
|
}
|
|
return userId;
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户名,如果未登录则抛出异常
|
|
*
|
|
* @return 当前用户名
|
|
* @throws IllegalStateException 如果用户未登录
|
|
*/
|
|
public static String requireCurrentUsername() {
|
|
String username = getCurrentUsername();
|
|
if (username == null || username.trim().isEmpty()) {
|
|
throw new IllegalStateException("用户未登录或认证失败");
|
|
}
|
|
return username;
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户上下文摘要信息
|
|
*
|
|
* @return 用户上下文摘要
|
|
*/
|
|
public static String getContextSummary() {
|
|
return UserContextHolder.getContextSummary();
|
|
}
|
|
}
|