You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package com.yf.exam.modules.user ; // 包名:表示该类属于 user 包
import com.yf.exam.core.api.ApiError ; // 导入 ApiError 类,定义 API 错误码
import com.yf.exam.core.exception.ServiceException ; // 导入 ServiceException 类,定义自定义服务异常
import com.yf.exam.modules.sys.user.dto.response.SysUserLoginDTO ; // 导入用户登录响应 DTO 类
import org.apache.shiro.SecurityUtils ; // 导入 Shiro 的 SecurityUtils 类,用于获取当前登录用户的信息
/**
* 用户静态工具类
* 提供当前登录用户的相关工具方法
* @作者 bool
*/
public class UserUtils {
/**
* 获取当前登录用户的ID
* @param throwable 如果发生异常,是否抛出异常
* @return 当前登录用户的ID
*/
public static String getUserId ( boolean throwable ) { // 获取当前登录用户 ID 的方法
try {
// 使用 Shiro 获取当前用户的主体对象,然后从中提取用户 ID
return ( ( SysUserLoginDTO ) SecurityUtils . getSubject ( ) . getPrincipal ( ) ) . getId ( ) ;
} catch ( Exception e ) { // 捕获异常
if ( throwable ) { // 如果 throwable 为 true, 则抛出自定义服务异常
throw new ServiceException ( ApiError . ERROR_10010002 ) ; // 异常码: 10010002
}
return null ; // 如果发生异常且 throwable 为 false, 则返回 null
}
}
/**
* 获取当前登录用户的ID
* @param throwable 如果发生异常,是否抛出异常
* @return 当前登录用户的ID
*/
public static boolean isAdmin ( boolean throwable ) { // 判断当前用户是否为管理员的方法
try {
SysUserLoginDTO dto = ( ( SysUserLoginDTO ) SecurityUtils . getSubject ( ) . getPrincipal ( ) ) ; // 获取当前用户的登录信息
return dto . getRoles ( ) . contains ( "sa" ) ; // 判断用户角色中是否包含管理员角色 "sa"
} catch ( Exception e ) { // 捕获异常
if ( throwable ) { // 如果 throwable 为 true, 则抛出自定义服务异常
throw new ServiceException ( ApiError . ERROR_10010002 ) ; // 异常码: 10010002
}
}
return false ; // 如果发生异常且 throwable 为 false, 则返回 false
}
/**
* 获取当前登录用户的ID, 默认是会抛异常的
* @return 当前登录用户的ID
*/
public static String getUserId ( ) { // 默认抛出异常的获取用户 ID 方法
return getUserId ( true ) ; // 调用带有 throwable 参数的方法,默认抛出异常
}
}