同用戶同系統異地登陸頂號,redis實現

 思路:
    第一次用戶登陸時生成UUID隨機數作爲token 查數據庫獲取用戶信息 保存redis中  key token value 用戶iduserId,
 同時保存 key userId ,value用戶基本信息實體其中包含token字段息, 返回用戶基本信息,每次請求時傳token去查redis中是否存在
當第二次登陸時 先查數據庫獲取userId 拿到userId去redis裏查詢用戶實體是否存在,存在說明之前登陸過,拿到其中token,根據key token刪除保存在redis中的信息,redis保存新的 key token  和 key userId 

登陸邏輯token處理

/**
 * 登陸處理
 * @param lmUserEntity
 * @return
 * @throws Exception
 */
public String handleLogin(LmUserEntity  lmUserEntity) throws Exception {
    LmUserEntity info = this.getUserByUserId(lmUserEntity.getUserId());
    if (info != null) {
        this.delToken(info.getToken());
        logger.info("清除原登陸token:"+info.getToken());
    }
    String token=this.setLoginToken(lmUserEntity.getUserId());
    logger.info("生成token:"+token);
    lmUserEntity.setToken(token);
    this.setUserByUserId(lmUserEntity);
    return token;
}
用戶實體
public class LmUserEntity implements Serializable {
   private static final long serialVersionUID = 1L;
   
   //
   private Integer id;
private String token;
//手機號
private String userMobile;
//姓名
private String userName;
//賬號登錄密碼
private String userPassword;

/**
攔截器
*/

@Configuration
public class AddInterceptorsConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
    @Bean
    public HandlerInterceptor getInterceptor() {
        return new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        registry.addInterceptor(getInterceptor())
                .addPathPatterns("/user/**"); 
    }

}

 

 

 

 

public class LoginInterceptor implements HandlerInterceptor{
    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Autowired
    private TokenRedisUtils tokenUtils;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("tokenStr");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (StringUtils.isBlank(token)){
            logger.info("未獲取到tokenStr");
            //用戶未登錄
            response.getWriter().print(JSONObject.toJSON(ResultDto.hasCodeFail("token失效","204")));
            return false;
        }else {
           Object o= tokenUtils.getLoginToken(token);
            if(null==o){
                logger.info("未查詢到token記錄:"+token);
                //登錄失效
                response.getWriter().print(JSONObject.toJSON(ResultDto.hasCodeFail("token失效","204")));
                return false;
            }
            LmUserEntity userEntity=tokenUtils.getUserByToken(o.toString());
            if (userEntity ==null ){
                logger.info("未查詢到用戶信息token:"+token+",userId:"+o.toString());
                response.getWriter().print(JSONObject.toJSON(ResultDto.hasCodeFail("token失效","204")));
                return false;
            } 
        }
        return true;
    }

 

public String setLoginToken(String userId) throws Exception {
    String uuid = UUId.getUUid();
    redisService.set(LM_R_LOGIN + uuid, userId, 60*60*24*7);
    return uuid;
}
public boolean setUserByUserId(LmUserEntity userEntity) throws Exception {
    return redisService.set(LM_R_LOGIN + userEntity.getUserId(), JSON.toJSONString(userEntity),60*60*24*7);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章