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.
exam/user/UserUtils.java

76 lines
3.2 KiB

This file contains ambiguous Unicode characters!

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;
// 导入自定义的 API 错误信息类
import com.yf.exam.core.api.ApiError;
// 导入自定义的服务异常类
import com.yf.exam.core.exception.ServiceException;
// 导入系统用户登录信息响应数据传输对象
import com.yf.exam.modules.sys.user.dto.response.SysUserLoginDTO;
// 导入 Shiro 安全工具类
import org.apache.shiro.SecurityUtils;
/**
* 用户静态工具类,提供获取当前登录用户信息的静态方法。
* @author bool
*/
public class UserUtils {
/**
* 获取当前登录用户的ID。
*
* @param throwable 一个布尔值,指示在获取用户 ID 失败时是否抛出异常。
* 若为 true则在失败时抛出 ServiceException 异常;
* 若为 false则在失败时返回 null。
* @return 当前登录用户的 ID如果获取失败且 throwable 为 false则返回 null。
*/
public static String getUserId(boolean throwable){
try {
// 从 Shiro 的 Subject 中获取当前用户的主身份信息,并转换为 SysUserLoginDTO 对象,然后获取用户 ID
return ((SysUserLoginDTO) SecurityUtils.getSubject().getPrincipal()).getId();
}catch (Exception e){
if(throwable){
// 若 throwable 为 true获取用户 ID 失败时抛出服务异常
throw new ServiceException(ApiError.ERROR_10010002);
}
// 若 throwable 为 false获取用户 ID 失败时返回 null
return null;
}
}
/**
* 判断当前登录用户是否为管理员。
*
* @param throwable 一个布尔值,指示在获取用户信息失败时是否抛出异常。
* 若为 true则在失败时抛出 ServiceException 异常;
* 若为 false则在失败时返回 false。
* @return 若当前登录用户的角色列表包含 "sa",则返回 true否则返回 false。
* 若获取用户信息失败且 throwable 为 false也返回 false。
*/
public static boolean isAdmin(boolean throwable){
try {
// 从 Shiro 的 Subject 中获取当前用户的主身份信息,并转换为 SysUserLoginDTO 对象
SysUserLoginDTO dto = ((SysUserLoginDTO) SecurityUtils.getSubject().getPrincipal());
// 判断用户的角色列表是否包含 "sa"
return dto.getRoles().contains("sa");
}catch (Exception e){
if(throwable){
// 若 throwable 为 true获取用户信息失败时抛出服务异常
throw new ServiceException(ApiError.ERROR_10010002);
}
}
// 若获取用户信息失败且 throwable 为 false返回 false
return false;
}
/**
* 获取当前登录用户的 ID默认在获取失败时会抛出异常。
* 该方法调用了 getUserId(boolean throwable) 方法,并将 throwable 参数设置为 true。
*
* @return 当前登录用户的 ID如果获取失败则抛出 ServiceException 异常。
*/
public static String getUserId(){
return getUserId(true);
}
}