com.yixan.base.web.utils.UserUtil Maven / Gradle / Ivy
package com.yixan.base.web.utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.subject.Subject;
import com.yixan.base.common.api.system.model.ICascadeResource;
import com.yixan.base.common.api.system.model.IUser;
import com.yixan.base.core.exception.ResultCode;
import com.yixan.base.core.exception.ServiceException;
import com.yixan.tools.common.util.RandomUtil;
/**
* 用户工具类
*
* @version C01 2015年6月12日
* @since v1.0
*/
public class UserUtil {
public static final String RESOURCES = "LoginUserResources";
/**
* 获取登录用户信息, 如果用户不存在则报错
*
* @author zhaohuihua
* @return 登录用户
*/
public static IUser getLoginUser() throws ServiceException {
IUser user = checkLoginUser();
if (user != null) {
return user;
} else {
throw new ServiceException(ResultCode.UNAUTHORIZED);
}
}
/**
* 获取登录用户信息
*
* @author zhaohuihua
* @return 登录用户
*/
public static IUser checkLoginUser() {
try {
Subject current = SecurityUtils.getSubject();
Object principal = current.getPrincipal();
if (principal instanceof IUser) {
return (IUser) principal;
} else {
return null;
}
} catch (UnknownSessionException e) {
return null;
}
}
/** Session已修改, 触发Shiro框架保存到缓存 **/
public static void sessionChanged() {
Session session = SecurityUtils.getSubject().getSession();
// 随机修改一个属性, 触发NativeSessionManager的onChange(session)
session.setAttribute("<>", RandomUtil.generateNumber(6));
}
public static void setUserResources(ICascadeResource> root) {
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute(RESOURCES, root);
}
public static ICascadeResource> getUserResources() {
Session session = SecurityUtils.getSubject().getSession();
return (ICascadeResource>) session.getAttribute(RESOURCES);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy