Java Code Examples for org.springframework.data.redis.core.ValueOperations#get()

The following examples show how to use org.springframework.data.redis.core.ValueOperations#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Pub_RedisUtils.java    From SuperBoot with MIT License 6 votes vote down vote up
/**
 * 根据token清理TOKEN白名单
 *
 * @param pkUser 用户主键
 * @param token  TOKEN信息
 */
public void cleanTokenAllow(long pkUser, String token) {
    ValueOperations<String, HashMap> operations = redisTemplate.opsForValue();
    boolean exists = redisTemplate.hasKey(BaseConstants.USER_TOKEN + "-" + pkUser);
    if (exists) {
        HashMap<String, Object> tokenMap = operations.get(BaseConstants.USER_TOKEN + "-" + pkUser);
        HashMap<String, String> itemMap = (HashMap<String, String>) tokenMap.get(token);
        tokenMap.remove(token);
        //判断TOKEN的信息与平台版本存储的一致才进行删除,理论上会一致,但是不排除出现同平台的信息不一致的情况
        String tokenStr = "" + tokenMap.get(itemMap.get(BaseConstants.TOKEN_PLATFORM) + "-" + itemMap.get(BaseConstants.TOKEN_VERSION));
        if (token.equals(tokenStr)) {
            tokenMap.remove(itemMap.get(BaseConstants.TOKEN_PLATFORM) + "-" + itemMap.get(BaseConstants.TOKEN_VERSION));
        }
        //重新设置以便刷新最后失效时间
        operations.set(BaseConstants.USER_TOKEN + "-" + pkUser, tokenMap, TOKEN_EXPIRED_DAY, TimeUnit.DAYS);
    }
}
 
Example 2
Source File: ApproveController.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 重置资金密码
 *
 * @param newPassword
 * @param code
 * @param user
 * @return
 * @throws Exception
 */
@RequestMapping("/reset/transaction/password")
@Transactional(rollbackFor = Exception.class)
public MessageResult resetTransaction(String newPassword, String code, @SessionAttribute(SESSION_MEMBER) AuthMember user) throws Exception {
    hasText(newPassword, msService.getMessage("MISSING_NEW_JY_PASSWORD"));
    isTrue(newPassword.length() >= 6 && newPassword.length() <= 20, msService.getMessage("JY_PASSWORD_LENGTH_ILLEGAL"));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    Object cache = valueOperations.get(SysConstant.PHONE_RESET_TRANS_CODE_PREFIX + user.getMobilePhone());
    notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
    hasText(code, msService.getMessage("MISSING_VERIFICATION_CODE"));
    if (!code.equals(cache.toString())) {
        return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
    } else {
        valueOperations.getOperations().delete(SysConstant.PHONE_RESET_TRANS_CODE_PREFIX + user.getMobilePhone());
    }
    Member member = memberService.findOne(user.getId());
    member.setJyPassword(Md5.md5Digest(newPassword + member.getSalt()).toLowerCase());
    return MessageResult.success(msService.getMessage("SETTING_JY_PASSWORD"));
}
 
Example 3
Source File: ApproveController.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 *
 * 更改登录密码
 *
 * @param request
 * @param oldPassword
 * @param newPassword
 * @param code
 * @param user
 * @return
 * @throws Exception
 */
@RequestMapping("/update/password")
@Transactional(rollbackFor = Exception.class)
public MessageResult updateLoginPassword(HttpServletRequest request, String oldPassword, String newPassword, String code, @SessionAttribute(SESSION_MEMBER) AuthMember user) throws Exception {
    hasText(oldPassword, msService.getMessage("MISSING_OLD_PASSWORD"));
    hasText(newPassword, msService.getMessage("MISSING_NEW_PASSWORD"));
    isTrue(newPassword.length() >= 6 && newPassword.length() <= 20, msService.getMessage("PASSWORD_LENGTH_ILLEGAL"));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    Object cache = valueOperations.get(SysConstant.PHONE_UPDATE_PASSWORD_PREFIX + user.getMobilePhone());
    notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
    hasText(code, msService.getMessage("MISSING_VERIFICATION_CODE"));
    if (!code.equals(cache.toString())) {
        return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
    } else {
        valueOperations.getOperations().delete(SysConstant.PHONE_UPDATE_PASSWORD_PREFIX + user.getMobilePhone());
    }
    Member member = memberService.findOne(user.getId());
    request.removeAttribute(SysConstant.SESSION_MEMBER);
    isTrue(Md5.md5Digest(oldPassword + member.getSalt()).toLowerCase().equals(member.getPassword()), msService.getMessage("PASSWORD_ERROR"));
    member.setPassword(Md5.md5Digest(newPassword + member.getSalt()).toLowerCase());
    return MessageResult.success(msService.getMessage("SETTING_SUCCESS"));
}
 
Example 4
Source File: RegisterController.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 增加提币地址验证码
 *
 * @param user
 * @return
 */
@RequestMapping("/add/address/code")
@ResponseBody
@Transactional(rollbackFor = Exception.class)
public MessageResult sendAddAddress(@SessionAttribute(SESSION_MEMBER) AuthMember user) {
    String code = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    Member member = memberService.findOne(user.getId());
    String email = member.getEmail();
    if (email == null) {
        return error(localeMessageSourceService.getMessage("NOT_BIND_EMAIL"));
    }
    if (valueOperations.get(ADD_ADDRESS_CODE_PREFIX + email) != null) {
        return error(localeMessageSourceService.getMessage("EMAIL_ALREADY_SEND"));
    }
    try {
        sentEmailAddCode(valueOperations, email, code);
    } catch (Exception e) {
        e.printStackTrace();
        return error(localeMessageSourceService.getMessage("SEND_FAILED"));
    }
    return success(localeMessageSourceService.getMessage("SENT_SUCCESS_TEN"));
}
 
Example 5
Source File: RegisterController.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 发送绑定邮箱验证码
 *
 * @param email
 * @param user
 * @return
 */
@RequestMapping("/bind/email/code")
@ResponseBody
@Transactional(rollbackFor = Exception.class)
public MessageResult sendBindEmail(String email, @SessionAttribute(SESSION_MEMBER) AuthMember user) {
    Assert.isTrue(ValidateUtil.isEmail(email), localeMessageSourceService.getMessage("WRONG_EMAIL"));
    Member member = memberService.findOne(user.getId());
    Assert.isNull(member.getEmail(), localeMessageSourceService.getMessage("BIND_EMAIL_REPEAT"));
    Assert.isTrue(!memberService.emailIsExist(email), localeMessageSourceService.getMessage("EMAIL_ALREADY_BOUND"));
    String code = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    if (valueOperations.get(EMAIL_BIND_CODE_PREFIX + email) != null) {
        return error(localeMessageSourceService.getMessage("EMAIL_ALREADY_SEND"));
    }
    try {
        sentEmailCode(valueOperations, email, code);
    } catch (Exception e) {
        e.printStackTrace();
        return error(localeMessageSourceService.getMessage("SEND_FAILED"));
    }
    return success(localeMessageSourceService.getMessage("SENT_SUCCESS_TEN"));
}
 
Example 6
Source File: SmsController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 注册验证码发送
 *
 * @return
 */
@PostMapping("/code")
public MessageResult sendCheckCode(String phone, String country) throws Exception {
    Assert.isTrue(!memberService.phoneIsExist(phone), localeMessageSourceService.getMessage("PHONE_ALREADY_EXISTS"));
    Assert.notNull(country, localeMessageSourceService.getMessage("REQUEST_ILLEGAL"));
    Country country1 = countryService.findOne(country);
    Assert.notNull(country1, localeMessageSourceService.getMessage("REQUEST_ILLEGAL"));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    String key = SysConstant.PHONE_REG_CODE_PREFIX + phone;
    Object code = valueOperations.get(key);
    if (code != null) {
        //判断如果请求间隔小于一分钟则请求失败
        if (!BigDecimalUtils.compare(DateUtil.diffMinute((Date) (valueOperations.get(key + "Time"))), BigDecimal.ONE)) {
            return error(localeMessageSourceService.getMessage("FREQUENTLY_REQUEST"));
        }
    }
    String randomCode = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
    MessageResult result;
    if ("86".equals(country1.getAreaCode())) {
        Assert.isTrue(ValidateUtil.isMobilePhone(phone.trim()), localeMessageSourceService.getMessage("PHONE_EMPTY_OR_INCORRECT"));
        result = smsProvider.sendVerifyMessage(phone, randomCode);
    } else {
        result = smsProvider.sendInternationalMessage(randomCode, country1.getAreaCode() + phone);
    }
    if (result.getCode() == 0) {
        valueOperations.getOperations().delete(key);
        valueOperations.getOperations().delete(key + "Time");
        // 缓存验证码
        valueOperations.set(key, randomCode, 10, TimeUnit.MINUTES);
        valueOperations.set(key + "Time", new Date(), 10, TimeUnit.MINUTES);
        return success(localeMessageSourceService.getMessage("SEND_SMS_SUCCESS"));
    } else {
        return error(localeMessageSourceService.getMessage("SEND_SMS_FAILED"));
    }
}
 
Example 7
Source File: RedisUtilsTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
private  void  setinfo(String key){
    SerializerThreadlocal.set(key);
    ValueOperations<String, String> operations = (ValueOperations<String, String>) redisTemplate
            .opsForValue();
    operations.set("lisi", "999");
    String lisi = operations.get("lisi");
    log.info(lisi);
}
 
Example 8
Source File: AideController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 系统帮助详情
 *
 * @param id
 * @return
 */
@RequestMapping(value = "more/help/detail",method = RequestMethod.POST)
public MessageResult sysHelpDetail(@RequestParam(value = "id") long id) {
    ValueOperations valueOperations = redisTemplate.opsForValue();
    SysHelp result = (SysHelp) valueOperations.get(SysConstant.SYS_HELP_DETAIL+id);
    if (result != null){
        return success(result);
    }else {
        SysHelp sysHelp = sysHelpService.findOne(id);
        valueOperations.set(SysConstant.SYS_HELP_DETAIL+id,sysHelp,SysConstant.SYS_HELP_DETAIL_EXPIRE_TIME,TimeUnit.SECONDS);
        return success(sysHelp);
    }

}
 
Example 9
Source File: SmsController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 注册验证码发送
 *
 * @return
 */
@PostMapping("/code")
public MessageResult sendCheckCode(String phone, String country) throws Exception {
    Assert.isTrue(!memberService.phoneIsExist(phone), localeMessageSourceService.getMessage("PHONE_ALREADY_EXISTS"));
    Assert.notNull(country, localeMessageSourceService.getMessage("REQUEST_ILLEGAL"));
    Country country1 = countryService.findOne(country);
    Assert.notNull(country1, localeMessageSourceService.getMessage("REQUEST_ILLEGAL"));
    ValueOperations valueOperations = redisTemplate.opsForValue();
    String key = SysConstant.PHONE_REG_CODE_PREFIX + phone;
    Object code = valueOperations.get(key);
    if (code != null) {
        //判断如果请求间隔小于一分钟则请求失败
        if (!BigDecimalUtils.compare(DateUtil.diffMinute((Date) (valueOperations.get(key + "Time"))), BigDecimal.ONE)) {
            return error(localeMessageSourceService.getMessage("FREQUENTLY_REQUEST"));
        }
    }
    String randomCode = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
    MessageResult result;
    if ("86".equals(country1.getAreaCode())) {
        Assert.isTrue(ValidateUtil.isMobilePhone(phone.trim()), localeMessageSourceService.getMessage("PHONE_EMPTY_OR_INCORRECT"));
        result = smsProvider.sendVerifyMessage(phone, randomCode);
    } else {
        result = smsProvider.sendInternationalMessage(randomCode, country1.getAreaCode() + phone);
    }
    if (result.getCode() == 0) {
        valueOperations.getOperations().delete(key);
        valueOperations.getOperations().delete(key + "Time");
        // 缓存验证码
        valueOperations.set(key, randomCode, 10, TimeUnit.MINUTES);
        valueOperations.set(key + "Time", new Date(), 10, TimeUnit.MINUTES);
        return success(localeMessageSourceService.getMessage("SEND_SMS_SUCCESS"));
    } else {
        return error(localeMessageSourceService.getMessage("SEND_SMS_FAILED"));
    }
}
 
Example 10
Source File: BlogArticleServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public Integer getArticleClick(Long articleId) {
    ValueOperations<String, Object> operations = redisTemplate.opsForValue();
    Integer count = (Integer)operations.get("article_click_id_"+articleId);
    if(count == null){
        BlogArticle blogArticle = selectById(articleId);
        if(blogArticle.getClick() != null){
            count = blogArticle.getClick();
        }else{
            count = 0;
        }
    }
    return count == null? 0 : count;
}
 
Example 11
Source File: CoinController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@GetMapping("get-no-check-key")
public MessageResult getKey(String phone) {
    String key = SysConstant.ADMIN_COIN_TRANSFER_COLD_PREFIX + phone + "_PASS";
    ValueOperations valueOperations = redisTemplate.opsForValue();
    Object object = valueOperations.get(key);
    if (object == null) {
        return error(messageSource.getMessage("NEED_CODE"));
    }
    return success(messageSource.getMessage("NO_NEED_CODE"), object);
}
 
Example 12
Source File: RedisCache.java    From poseidon with Apache License 2.0 5 votes vote down vote up
/**
 * Get cached query result from redis
 * @param key
 * @return
 */
@Override
public Object getObject(Object key) {
	try {
		RedisTemplate redisTemplate = getRedisTemplate();
		ValueOperations opsForValue = redisTemplate.opsForValue();
		logger.debug("Get cached query result from redis");
		return opsForValue.get(key);
	}
	catch (Throwable t) {
		logger.error("Redis get failed, fail over to db", t);
		return null;
	}
}
 
Example 13
Source File: EmployeeController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 提交登录信息
 *
 * @param request
 * @return
 */


@RequestMapping(value = "sign/in")
@ResponseBody
@AccessLog(module = AdminModule.SYSTEM, operation = "提交登录信息Admin")
public MessageResult doLogin(@SessionAttribute("username")String username,
                             @SessionAttribute("password")String password,
                             @SessionAttribute("phone")String phone,String code,
                             @RequestParam(value="rememberMe",defaultValue = "true")boolean rememberMe,
                             HttpServletRequest request) {
    Assert.notNull(code,"请输入验证码");
    Assert.isTrue(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(password)&&StringUtils.isNotEmpty(phone),"会话已过期");
    ValueOperations valueOperations = redisTemplate.opsForValue() ;
    Object cacheCode = valueOperations.get(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
    Assert.notNull(cacheCode,"验证码已经被清除,请重新发送");
    if (!code.equals(cacheCode.toString())) {
        return error("手机验证码错误,请重新输入");
    }
    try {
        log.info("md5Key {}", md5Key);

        //password = Encrypt.MD5(password + md5Key);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,true);
        token.setHost(getRemoteIp(request));
        SecurityUtils.getSubject().login(token);
        valueOperations.getOperations().delete(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
        Admin admin = (Admin) request.getSession().getAttribute(SysConstant.SESSION_ADMIN);
        //token.setRememberMe(true);

        //获取当前用户的菜单权限
        List<Menu> list;
        if ("root".equalsIgnoreCase(admin.getUsername())) {
            list = sysRoleService.toMenus(sysPermissionService.findAll(), 0L);
        } else {
            list = sysRoleService.toMenus(sysRoleService.getPermissions(admin.getRoleId()), 0L);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("permissions", list);
        map.put("admin", admin);
        return success("登录成功", map);
    } catch (AuthenticationException e) {
        e.printStackTrace();
        return error(e.getMessage());
    }
}
 
Example 14
Source File: RedisServiceImpl.java    From DouBiNovel with Apache License 2.0 4 votes vote down vote up
@Override
public String get(String key) {
    ValueOperations<String, String> operations = this.template.opsForValue();
    return (String) operations.get(key);
}
 
Example 15
Source File: PubServiceImpl.java    From SuperBoot with MIT License 4 votes vote down vote up
@Override
public BaseResponse sso(ReqOtherLogin otherLogin) {

    if (isAes()) {
        //执行数据解密
        otherLogin.setPlatform(aesDecrypt(otherLogin.getPlatform()));
        otherLogin.setVersion(aesDecrypt(otherLogin.getVersion()));
        otherLogin.setUserKey(aesDecrypt(otherLogin.getUserKey()));
    }


    //调用用户中心服务获取登陆信息
    BaseResponse response = userRemote.sso(otherLogin);
    if (BaseStatus.OK.getCode() == response.getStatus()) {
        //判断数据状态
        if (StatusCode.OK.getCode() == response.getCode()) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            BaseToken bt = JSON.toJavaObject(data, BaseToken.class);

            //判断白名单,用户是否已经生成过TOKEN了,如果生成过则不再进行登陆操作
            String token = getRedisUtils().getTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion());
            if (null == token) {
                //生成新的TOKEN
                token = jwtUtils.generateToken(bt);
                //登陆后将TOKEN信息放入缓存
                getRedisUtils().setTokenInfo(token, bt);
                getRedisUtils().setTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion(), token);
            } else {
                //判断TOKEN是否已经锁定了,如果锁定了则需要重新生成新的TOKEN给客户端
                ValueOperations<String, HashMap> operations = getRedisUtils().getRedisTemplate().opsForValue();
                boolean exists = getRedisUtils().getRedisTemplate().hasKey(token);
                if (exists) {
                    HashMap tokenItem = operations.get(token);
                    //如果TOKEN已经锁定,则重新生成TOKEN信息
                    if (Pub_RedisUtils.TOKEN_STATUS_LOCKED.equals(tokenItem.get(Pub_RedisUtils.TOKEN_STATUS))) {
                        //生成新的TOKEN
                        token = jwtUtils.generateToken(bt);
                        //登陆后将TOKEN信息放入缓存
                        getRedisUtils().setTokenInfo(token, bt);
                        getRedisUtils().setTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion(), token);
                    }
                }
            }

            return new BaseResponse(genResToken(bt, token));
        }

    }
    return response;
}
 
Example 16
Source File: RegisterController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
     * 激活邮件  暂时注掉
     *
     * @param key
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/register/active")
    @Transactional(rollbackFor = Exception.class)
    public String activate(String key, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(key)) {
            request.setAttribute("result", localeMessageSourceService.getMessage("INVALID_LINK"));
            return "registeredResult";
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object info = valueOperations.get(key);
        LoginByEmail loginByEmail = null;
        if (info instanceof LoginByEmail) {
            loginByEmail = (LoginByEmail) info;
        }
        if (loginByEmail == null) {
            request.setAttribute("result", localeMessageSourceService.getMessage("INVALID_LINK"));
            return "registeredResult";
        }
        if (memberService.emailIsExist(loginByEmail.getEmail())) {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS_EMAIL"));
            return "registeredResult";
        } else if (memberService.usernameIsExist(loginByEmail.getUsername())) {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS_USERNAME"));
            return "registeredResult";
        }
        //删除redis里存的键值
        valueOperations.getOperations().delete(key);
        valueOperations.getOperations().delete(loginByEmail.getEmail());
        //不可重复随机数
        String loginNo = String.valueOf(idWorkByTwitter.nextId());
        //盐
        String credentialsSalt = ByteSource.Util.bytes(loginNo).toHex();
        //生成密码
        String password = Md5.md5Digest(loginByEmail.getPassword() + credentialsSalt).toLowerCase();
        Member member = new Member();
        //新增超级合伙人 判断0  普通 默认普通用户   1 超级合伙人 ....
        if(!StringUtils.isEmpty(loginByEmail.getSuperPartner())){
            member.setSuperPartner(loginByEmail.getSuperPartner());
            if (!"0".equals(loginByEmail.getSuperPartner())) {
                //需要后台审核解禁
                member.setStatus(CommonStatus.ILLEGAL);
            }

        }
        member.setMemberLevel(MemberLevelEnum.GENERAL);
        Location location = new Location();
        location.setCountry(loginByEmail.getCountry());
        member.setLocation(location);
        Country country = new Country();
        country.setZhName(loginByEmail.getCountry());
        member.setCountry(country);
        member.setUsername(loginByEmail.getUsername());
        member.setPassword(password);
        member.setEmail(loginByEmail.getEmail());
        member.setSalt(credentialsSalt);
        Member member1 = memberService.save(member);
        if (member1 != null) {
            member1.setPromotionCode(String.format(userNameFormat, member1.getId()) + GeneratorUtil.getNonceString(2));
            memberEvent.onRegisterSuccess(member1, loginByEmail.getPromotion());
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_SUCCESSFUL"));
        } else {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS"));
        }
        return "registeredResult";
    }
 
Example 17
Source File: LoginServiceController.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * 登录
 * @param param 用户名或手机号phone
 * @return 登录成功后返回用户基本信息
 * @since  1.0
 */
@PostMapping(path = "/login")
public BaseModel<UserEntity> login(@RequestBody LoginReq param) {

    BaseModel<UserEntity> userRes = new BaseModel<>();
    String key = RedisKeys.concat(RedisKeys.USER_LOGIN_FAILD, param.getName());
    ValueOperations<String, String> faildCountOps = redisTemplate.opsForValue();
    String faildCount = faildCountOps.get(key);
    int faild = 0;
    if (!StringUtils.isEmpty(faildCount)) {
        faild = Integer.parseInt(faildCount);
    }
    if (faild > 5) {
        return userRes.setResult(LoginCmdResult.LOGIN_PASSWORD_LOCK);
    }
    
    // 改为:用户名或手机号皆可登录
    SearchCriteria<IMUser> userSearchCriteria = new SearchCriteria<>();
    userSearchCriteria.add(JpaRestrictions.eq("name", param.getName(), false));
    userSearchCriteria.add(JpaRestrictions.ne("status", DBConstant.USER_STATUS_LEAVE, false));
    List<IMUser> users = userRepository.findAll(userSearchCriteria);
    
    if (users.isEmpty()) {
        logger.debug("用户{}登录失败", param.getName());
        return userRes.setResult(LoginCmdResult.LOGIN_NOUSER);
    }

    IMUser user = users.get(0);

    if (passwordEncoder.matches(param.getPassword(), user.getPassword())) {
        // 密码正确
        UserEntity userEntity = new UserEntity();
        userEntity.setId(user.getId());
        userEntity.setMainName(user.getNick());
        userEntity.setAvatar(user.getAvatar());
        userEntity.setCreated(user.getCreated());
        userEntity.setDepartmentId(user.getDepartId());
        userEntity.setPeerId(user.getId());
        userEntity.setPhone(user.getPhone());
        userEntity.setRealName(user.getName());
        userEntity.setStatus(user.getStatus());
        userEntity.setGender(user.getSex());
        userEntity.setUpdated(user.getUpdated());
        userEntity.setEmail(user.getEmail());
        userEntity.setPinyinName(user.getDomain());
        userEntity.setSignInfo(user.getSignInfo());
        userRes.setData(userEntity);

        // 如果登陆成功,则清除错误尝试限制
        if (faild > 0) {
            redisTemplate.delete(key);
        }
    } else {

        // 密码错误,记录一次登陆失败
        faildCountOps.set(key, String.valueOf(++faild), 30, TimeUnit.MINUTES);
        return userRes.setResult(LoginCmdResult.LOGIN_NOUSER);
    }
    return userRes;
}
 
Example 18
Source File: WithdrawController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
     * 申请提币(添加验证码校验)
     * @param user
     * @param unit
     * @param address
     * @param amount
     * @param fee
     * @param remark
     * @param jyPassword
     * @return
     * @throws Exception
     */
    @RequestMapping("apply/code")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult withdrawCode(@SessionAttribute(SESSION_MEMBER) AuthMember user, String unit, String address,
                                  BigDecimal amount, BigDecimal fee,String remark,String jyPassword,@RequestParam("code") String code) throws Exception {
        hasText(jyPassword, sourceService.getMessage("MISSING_JYPASSWORD"));
        hasText(unit, sourceService.getMessage("MISSING_COIN_TYPE"));
        Coin coin = coinService.findByUnit(unit);
        amount.setScale(coin.getWithdrawScale(),BigDecimal.ROUND_DOWN);
        notNull(coin, sourceService.getMessage("COIN_ILLEGAL"));

        isTrue(coin.getStatus().equals(CommonStatus.NORMAL) && coin.getCanWithdraw().equals(BooleanEnum.IS_TRUE), sourceService.getMessage("COIN_NOT_SUPPORT"));
        isTrue(compare(fee, new BigDecimal(String.valueOf(coin.getMinTxFee()))), sourceService.getMessage("CHARGE_MIN") + coin.getMinTxFee());
        isTrue(compare(new BigDecimal(String.valueOf(coin.getMaxTxFee())), fee), sourceService.getMessage("CHARGE_MAX") + coin.getMaxTxFee());
        isTrue(compare(coin.getMaxWithdrawAmount(), amount), sourceService.getMessage("WITHDRAW_MAX") + coin.getMaxWithdrawAmount());
        isTrue(compare(amount, coin.getMinWithdrawAmount()), sourceService.getMessage("WITHDRAW_MIN") + coin.getMinWithdrawAmount());
        MemberWallet memberWallet = memberWalletService.findByCoinAndMemberId(coin, user.getId());
        isTrue(compare(memberWallet.getBalance(), amount), sourceService.getMessage("INSUFFICIENT_BALANCE"));
//        isTrue(memberAddressService.findByMemberIdAndAddress(user.getId(), address).size() > 0, sourceService.getMessage("WRONG_ADDRESS"));
        isTrue(memberWallet.getIsLock()==BooleanEnum.IS_FALSE,"钱包已锁定");
        Member member = memberService.findOne(user.getId());
        String mbPassword = member.getJyPassword();
        Assert.hasText(mbPassword, sourceService.getMessage("NO_SET_JYPASSWORD"));
        Assert.isTrue(Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword), sourceService.getMessage("ERROR_JYPASSWORD"));
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String phone= member.getMobilePhone();
        Object codeRedis =valueOperations.get(SysConstant.PHONE_WITHDRAW_MONEY_CODE_PREFIX + phone);
        notNull(codeRedis, sourceService.getMessage("VERIFICATION_CODE_NOT_EXISTS"));
        if (!codeRedis.toString().equals(code)) {
            return error(sourceService.getMessage("VERIFICATION_CODE_INCORRECT"));
        } else {
            valueOperations.getOperations().delete(SysConstant.PHONE_WITHDRAW_MONEY_CODE_PREFIX + phone);
        }
        MessageResult result = memberWalletService.freezeBalance(memberWallet, amount);
        if (result.getCode() != 0) {
            throw new InformationExpiredException("Information Expired");
        }
        WithdrawRecord withdrawApply = new WithdrawRecord();
        withdrawApply.setCoin(coin);
        withdrawApply.setFee(fee);
        withdrawApply.setArrivedAmount(sub(amount, fee));
        withdrawApply.setMemberId(user.getId());
        withdrawApply.setTotalAmount(amount);
        withdrawApply.setAddress(address);
        withdrawApply.setRemark(remark);
        withdrawApply.setCanAutoWithdraw(coin.getCanAutoWithdraw());

        //提币数量低于或等于阈值并且该币种支持自动提币
        if (amount.compareTo(coin.getWithdrawThreshold()) <= 0 && coin.getCanAutoWithdraw().equals(BooleanEnum.IS_TRUE)) {
            withdrawApply.setStatus(WithdrawStatus.WAITING);
            withdrawApply.setIsAuto(BooleanEnum.IS_TRUE);
            withdrawApply.setDealTime(withdrawApply.getCreateTime());
            WithdrawRecord withdrawRecord = withdrawApplyService.save(withdrawApply);
            JSONObject json = new JSONObject();
            json.put("uid", user.getId());
            //提币总数量
            json.put("totalAmount", amount);
            //手续费
            json.put("fee", fee);
            //预计到账数量
            json.put("arriveAmount", sub(amount, fee));
            //币种
            json.put("coin", coin);
            //提币地址
            json.put("address", address);
            //提币记录id
            json.put("withdrawId", withdrawRecord.getId());
            kafkaTemplate.send("withdraw", coin.getUnit(), json.toJSONString());
            return MessageResult.success(sourceService.getMessage("APPLY_SUCCESS"));
        } else {
            withdrawApply.setStatus(WithdrawStatus.PROCESSING);
            withdrawApply.setIsAuto(BooleanEnum.IS_FALSE);
            if (withdrawApplyService.save(withdrawApply) != null) {
                return MessageResult.success(sourceService.getMessage("APPLY_AUDIT"));
            } else {
                throw new InformationExpiredException("Information Expired");
            }
        }
    }
 
Example 19
Source File: CacheServiceProvider.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
@Override
public String get(final String key) {
	final ValueOperations<String, String> operation = redisTemplate.opsForValue();
	return operation.get(getKey(key));
}
 
Example 20
Source File: RegisterController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
     * 激活邮件  暂时注掉
     *
     * @param key
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/register/active")
    @Transactional(rollbackFor = Exception.class)
    public String activate(String key, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(key)) {
            request.setAttribute("result", localeMessageSourceService.getMessage("INVALID_LINK"));
            return "registeredResult";
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object info = valueOperations.get(key);
        LoginByEmail loginByEmail = null;
        if (info instanceof LoginByEmail) {
            loginByEmail = (LoginByEmail) info;
        }
        if (loginByEmail == null) {
            request.setAttribute("result", localeMessageSourceService.getMessage("INVALID_LINK"));
            return "registeredResult";
        }
        if (memberService.emailIsExist(loginByEmail.getEmail())) {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS_EMAIL"));
            return "registeredResult";
        } else if (memberService.usernameIsExist(loginByEmail.getUsername())) {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS_USERNAME"));
            return "registeredResult";
        }
        //删除redis里存的键值
        valueOperations.getOperations().delete(key);
        valueOperations.getOperations().delete(loginByEmail.getEmail());
        //不可重复随机数
        String loginNo = String.valueOf(idWorkByTwitter.nextId());
        //盐
        String credentialsSalt = ByteSource.Util.bytes(loginNo).toHex();
        //生成密码
        String password = Md5.md5Digest(loginByEmail.getPassword() + credentialsSalt).toLowerCase();
        Member member = new Member();
        //新增超级合伙人 判断0  普通 默认普通用户   1 超级合伙人 ....
        if(!StringUtils.isEmpty(loginByEmail.getSuperPartner())){
            member.setSuperPartner(loginByEmail.getSuperPartner());
            if (!"0".equals(loginByEmail.getSuperPartner())) {
                //需要后台审核解禁
                member.setStatus(CommonStatus.ILLEGAL);
            }

        }
        member.setMemberLevel(MemberLevelEnum.GENERAL);
        Location location = new Location();
        location.setCountry(loginByEmail.getCountry());
        member.setLocation(location);
        Country country = new Country();
        country.setZhName(loginByEmail.getCountry());
        member.setCountry(country);
        member.setUsername(loginByEmail.getUsername());
        member.setPassword(password);
        member.setEmail(loginByEmail.getEmail());
        member.setSalt(credentialsSalt);
        Member member1 = memberService.save(member);
        if (member1 != null) {
            member1.setPromotionCode(String.format(userNameFormat, member1.getId()) + GeneratorUtil.getNonceString(2));
            memberEvent.onRegisterSuccess(member1, loginByEmail.getPromotion());
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_SUCCESSFUL"));
        } else {
            request.setAttribute("result", localeMessageSourceService.getMessage("ACTIVATION_FAILS"));
        }
        return "registeredResult";
    }