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

com.github.javaclub.base.service.impl.TokenStoreService Maven / Gradle / Ivy

package com.github.javaclub.base.service.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.javaclub.base.domain.LoginTokenModel;
import com.github.javaclub.base.utils.ConfigUtils;
import com.github.javaclub.sword.BizException;
import com.github.javaclub.sword.core.Collections;
import com.github.javaclub.sword.core.Strings;
import com.github.javaclub.sword.domain.enumtype.BasicMessage;
import com.github.javaclub.toolbox.cache.redis.RedisScanCallback;
import com.github.javaclub.toolbox.cache.redis.RedisStore;
import com.github.javaclub.toolbox.crypt.MiscCryptor;
import com.github.javaclub.toolbox.enumtype.SysAccountEnum;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TokenStoreService {
	
	public String generateAuthToken(int accountType, Serializable uid, Object user) {
		String sysId = SysAccountEnum.identity(accountType);
        try {
	        	// 生成最终token
	    		LoginTokenModel model = new LoginTokenModel(uid);
	    		String sign = model.generateSign();
	    		model.setMd5Sign(sign);
	    		// TODO 加入 用户salt 因子
	    		String token = MiscCryptor.encrypt(JSONObject.toJSONString(model));
	    		
	    		String redisKey = ConfigUtils.getAccountTokenKey(sysId, uid, token);
        	
            String userJSON = JSONObject.toJSONString(user);
            int hours = ConfigUtils.getLoginExpiredHours(sysId);
            getRedisStore().set(redisKey, userJSON, hours*60*60); // 有效期:hours小时
	    		
	    		log.info("生成用户token={}, sysId={}, uid={}, user={}", token, sysId, uid, userJSON);
	    		return token;
            
        } catch (Throwable e) {
            log.error("用户信息异常:", e);
            throw new BizException(BasicMessage.SYSTEM_ERROR.getCode(), "登录失败, 请稍后重试!");
        }
	}
	
	public boolean deleteAllToken(int accountType, Serializable uid, String token) {
		String sysId = SysAccountEnum.identity(accountType);
		String redisKey = ConfigUtils.getAccountTokenKey(sysId, uid, token);
		try {
			if (Strings.isNotBlank(token) && getRedisStore().hasKey(redisKey)) {
				getRedisStore().del(redisKey);
				return true;
			}
			// 没传特定的token,则表示要清理所有session会话
			String pattern = ConfigUtils.getAccountTokenKeyPattern(sysId, uid);
			boolean flag = getRedisStore().scan(pattern, 200, new RedisScanCallback() {
				@Override
				public void handle(List keys) {
					if (Collections.isNotEmpty(keys)) {
						getRedisStore().delMultiKeys(keys.toArray(new String[0]));
					}
				}
			});
			return flag;
		} catch (Throwable e) {
			throw new BizException(BasicMessage.REDIS_ERROR);
		}
	}
	
	RedisStore getRedisStore() {
		return RedisStore.defaultPublic();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy