All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.base.utils.SecurityUtils Maven / Gradle / Ivy

package com.github.javaclub.base.utils;

import java.io.Serializable;
import java.time.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.github.javaclub.base.domain.AdminUser;
import com.github.javaclub.base.domain.LoginTokenModel;
import com.github.javaclub.base.domain.UserProfile;
import com.github.javaclub.base.service.UserAccountService;
import com.github.javaclub.sword.BizException;
import com.github.javaclub.sword.algorithm.crypt.MiscCryptor;
import com.github.javaclub.sword.core.BizObjects;
import com.github.javaclub.sword.core.Strings;
import com.github.javaclub.sword.domain.enumtype.BasicMessage;
import com.github.javaclub.sword.web.holder.AdminUserHolder;
import com.github.javaclub.sword.web.holder.AppUserHolder;
import com.github.javaclub.toolbox.ToolBox.Numbers;
import com.github.javaclub.toolbox.ToolBox.Objects;
import com.github.javaclub.toolbox.ToolBox.Web;
import com.github.javaclub.toolbox.cache.redis.RedisStore;
import com.github.javaclub.toolbox.enumtype.SysAccountEnum;
import com.github.javaclub.toolbox.spring.BeanFactory;

public class SecurityUtils {
	
	static Logger log = LoggerFactory.getLogger(SecurityUtils.class);

	public static AdminUser getAdminUser() {
		AdminUser user = AdminUserHolder.get();
		return user;
	}
	
	public static UserProfile getAppUser() {
		UserProfile user = AppUserHolder.get();
		return user;
	}
	
	public static UserProfile getAppUserFromToken() {
		return getAppUserFromToken(false);
	}
	
	public static UserProfile getAppUserFromToken(boolean throwsExIfNull) {
		try {
			String token = Web.getCurrentRequestHeader("token");
			if (Strings.isBlank(token)) {
				throw new BizException(BasicMessage.UN_LOGINED.getCode(), "请登录后再试!");
			}
			LoginTokenModel tkModel = checkUserLoginToken(token);
			Serializable id = Objects.requireNotNull(tkModel.getAccountId(), "用户信息异常,请重新登录!");
			Long userId = Numbers.parseLong(id.toString());

			String tokenUserKey = ConfigUtils.getAccountTokenKey(SysAccountEnum.BIZ.identity(), userId, token);
			String userJSON = RedisStore.defaultPublic().get(tokenUserKey);
			if (Strings.isBlank(userJSON)) {
				throw new BizException(BasicMessage.UN_LOGINED.getCode(), "登录已失效, 请登录后重试!");
			}
			UserProfile user = JSONObject.parseObject(userJSON, UserProfile.class);
			BizObjects.requireTrue(null != user && Numbers.isPositiveNumber(user.getId()), BasicMessage.UN_LOGINED, "登录状态异常, 请重新登录!");
			if (Numbers.isPositiveNumber(userId)) {
				long mills = System.currentTimeMillis() - tkModel.getTimestamp();
				if (0 > mills || mills > Duration.ofHours(ConfigUtils.getLoginExpiredHours(SysAccountEnum.BIZ.identity())).toMillis()) {
					throw new BizException(BasicMessage.LOGIN_INVALID.getCode(), "登录已过期, 请登录后重试!");
				}
			}

			boolean isLoginUserLoadFromDb = ConfigUtils.isLoginUserLoadFromDb();
			if (isLoginUserLoadFromDb) {
				UserProfile dbUser = BeanFactory.getInstance().getBean(UserAccountService.class).loadUserProfile(user.getId());
				BizObjects.requireTrue(null != dbUser, BasicMessage.UN_NORMAL_USER, "登录状态异常, 请重新登录!");
				return dbUser;
			}

			return user;

		} catch (BizException | com.github.javaclub.BizException e) {
			if (throwsExIfNull) {
				throw e;
			}
		} catch (Throwable e) {
			log.error("用户token解析异常:url=" + Web.getCurrentHttpRequest().getRequestURL(), e);
			if (throwsExIfNull) {
				throw new BizException(BasicMessage.LOGIN_INVALID.getCode(), "系统繁忙,请登录后重试!");
			}
		}
		
		return null;
	}
	
	static LoginTokenModel checkUserLoginToken(String token) throws Exception {
		
		String decrypt = MiscCryptor.decrypt(token);
		BizObjects.requireTrue(Strings.isNotBlank(decrypt), BasicMessage.LOGIN_INVALID, "登录已失效, 请登录后重试!");
        
        LoginTokenModel tkModel = JSONObject.parseObject(decrypt, LoginTokenModel.class);
        BizObjects.requireTrue(null != tkModel, BasicMessage.LOGIN_INVALID, "登录状态异常, 请重新登录!");
        
        Serializable userId = tkModel.getAccountId();
        BizObjects.requireTrue(null != userId, BasicMessage.LOGIN_INVALID, "登录状态异常, 请重新登录!!");
        
        boolean checkValid = tkModel.validate();
        BizObjects.requireTrue(checkValid, BasicMessage.LOGIN_INVALID, "登录校验失败, 请重新登录!");
        
        return tkModel;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy