Java Code Examples for cn.hutool.core.util.RandomUtil#randomNumbers()

The following examples show how to use cn.hutool.core.util.RandomUtil#randomNumbers() . 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: ValidateCodeServiceImpl.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 发送验证码
 * <p>
 * 1. 先去redis 查询是否 60S内已经发送
 * 2. 未发送: 判断手机号是否存 ? false :产生4位数字  手机号-验证码
 * 3. 发往消息中心-》发送信息
 * 4. 保存redis
 *
 * @param mobile 手机号
 * @return true、false
 */
@Override
public Result sendSmsCode(String mobile) {
    Object tempCode = redisRepository.get(buildKey(mobile));
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return Result.failed("验证码未失效,请失效后再次申请");
    }

    SysUser user = userService.findByMobile(mobile);
    if (user == null) {
        log.error("根据用户手机号{}查询用户为空", mobile);
        return Result.failed("手机号不存在");
    }

    String code = RandomUtil.randomNumbers(4);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(buildKey(mobile), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
    return Result.succeed("true");
}
 
Example 2
Source File: MobileService.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 发送短信
 *
 * @param mobile     mobile
 * @return ResponseBean
 * @author tangyi
 * @date 2019/07/02 09:36:52
 */
public ResponseBean<Boolean> sendSms(String mobile) {
    String key = CommonConstant.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + mobile;
    // TODO 校验时间
    String code = RandomUtil.randomNumbers(Integer.parseInt(CommonConstant.CODE_SIZE));
    log.debug("Generate validate code success: {}, {}", mobile, code);
    redisTemplate.opsForValue().set(key, code, SecurityConstant.DEFAULT_SMS_EXPIRE, TimeUnit.SECONDS);
    // 调用消息中心服务,发送短信验证码
    SmsDto smsDto = new SmsDto();
    smsDto.setReceiver(mobile);
    smsDto.setContent(String.format(SmsConstant.SMS_TEMPLATE, code));
    ResponseBean<?> result = mscServiceClient.sendSms(smsDto);
    if (!ResponseUtil.isSuccess(result))
        throw new ServiceException("Send validate code error: " + result.getMsg());
    log.info("Send validate result: {}", result.getData());
    return new ResponseBean<>(Boolean.TRUE, code);
}
 
Example 3
Source File: VerificationCodeController.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 通用的发送验证码功能
 * <p>
 * 一个系统可能有很多地方需要发送验证码(注册、找回密码等),每增加一个场景,VerificationCodeType 就需要增加一个枚举值
 *
 * @param data
 * @return
 */
@ApiOperation(value = "发送验证码", notes = "发送验证码")
@PostMapping(value = "/send")
public R<Boolean> send(@Validated @RequestBody VerificationCodeDTO data) {
    String code = RandomUtil.randomNumbers(6);

    SmsTask smsTask = SmsTask.builder().build();
    smsTask.setSourceType(SourceType.SERVICE);
    JSONObject param = new JSONObject();
    param.put("1", code);
    smsTask.setTemplateParams(param.toString());
    smsTask.setReceiver(data.getMobile());
    smsTaskService.saveTask(smsTask, TemplateCodeType.ZUIHOU_COMMON);

    String key = CacheKey.buildTenantKey(CacheKey.REGISTER_USER, data.getType().name(), data.getMobile());
    cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
    return R.success();
}
 
Example 4
Source File: UserController.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 发送手机验证码
 *
 * @param mobile
 * @return
 */
@RequestMapping("/smsCode/{mobile}")
@ResponseBody
public ResponseEntity<Response> smsCode(@Pattern (regexp = MOBILE_REG, message = "请输入正确的手机号")
                                        @PathVariable String mobile) {
    Object tempCode = redisRepository.get(CacheConstants.DEFAULT_CODE_KEY + mobile);
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return ResponseEntity.ok(Response.failure("验证码: " + tempCode + " 未失效,请失效后再次申请"));
    }
    if (userTransferService.findUserByMobile(mobile) == null) {
        log.error("根据用户手机号:{}, 查询用户为空", mobile);
        return ResponseEntity.ok(Response.failure("手机号不存在"));
    }
    String code = RandomUtil.randomNumbers(6);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(CacheConstants.DEFAULT_CODE_KEY + mobile, code, CacheConstants.DEFAULT_EXPIRE_SECONDS);
    return ResponseEntity.ok(Response.success(code));
}
 
Example 5
Source File: SysUserServiceImpl.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 发送验证码
 * <p>
 * 1. 先去redis 查询是否 60S内已经发送
 * 2. 未发送: 判断手机号是否存 ? false :产生6位数字  手机号-验证码
 * 3. 发往消息中心-》发送信息
 * 4. 保存redis
 *
 * @param mobile 手机号
 * @return true、false
 */
@Override
public Response sendSmsCode(String mobile) {
    Object tempCode = redisRepository.get(CacheConstants.DEFAULT_CODE_KEY + mobile);
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return Response.failure("验证码: " + tempCode + "未失效,请失效后再次申请");
    }

    SysUser params = new SysUser();
    params.setPhone(mobile);
    List<SysUser> userList = this.list(new QueryWrapper<>(params));

    if (CollectionUtils.isEmpty(userList)) {
        log.error("根据用户手机号:{}, 查询用户为空", mobile);
        return Response.failure("手机号不存在");
    }

    String code = RandomUtil.randomNumbers(6);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
    return Response.success(code);
}
 
Example 6
Source File: VerifyServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
    EmailVo emailVo;
    String content;
    String redisKey = key + email;
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    Object oldCode =  redisUtils.get(redisKey);
    if(oldCode == null){
        String code = RandomUtil.randomNumbers (6);
        // 存入缓存
        if(!redisUtils.set(redisKey, code, expiration)){
            throw new BadRequestException("服务异常,请联系网站负责人");
        }
        content = template.render(Dict.create().set("code",code));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code",oldCode));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    }
    return emailVo;
}
 
Example 7
Source File: VerificationCodeController.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 通用的发送验证码功能
 * <p>
 * 一个系统可能有很多地方需要发送验证码(注册、找回密码等),每增加一个场景,VerificationCodeType 就需要增加一个枚举值
 *
 * @param data
 * @return
 */
@ApiOperation(value = "发送验证码", notes = "发送验证码")
@PostMapping(value = "/send")
public R<Boolean> send(@Validated @RequestBody VerificationCodeDTO data) {
    String code = RandomUtil.randomNumbers(6);

    SmsTask smsTask = SmsTask.builder().build();
    smsTask.setSourceType(SourceType.SERVICE);
    JSONObject param = new JSONObject();
    param.put("1", code);
    smsTask.setTemplateParams(param.toString());
    smsTask.setReceiver(data.getMobile());
    smsTaskService.saveTask(smsTask, TemplateCodeType.ZUIHOU_COMMON);

    String key = CacheKey.buildTenantKey(CacheKey.REGISTER_USER, data.getType().name(), data.getMobile());
    cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
    return R.success();
}
 
Example 8
Source File: EmailServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
	EmailVo emailVo;
	String content;
	String redisKey = key + email;
	// 如果不存在有效的验证码,就创建一个新的
	TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
	Template template = engine.getTemplate("email/email.ftl");
	Object oldCode = RedisUtil.getCacheString(redisKey);
	if (oldCode == null) {
		String code = RandomUtil.randomNumbers(6);

		// 存入缓存
		RedisUtil.setCacheString(redisKey, code, CommonConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);

		content = template.render(Dict.create().set("code", code));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
		// 存在就再次发送原来的验证码
	} else {
		content = template.render(Dict.create().set("code", oldCode));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
	}
	return emailVo;
}
 
Example 9
Source File: SmsLogServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void sendSms(SmsType smsType, String userId, String mobile, Map<String, String> params) {

    SmsLog smsLog = new SmsLog();
    if (smsType.equals(SmsType.VALID)) {
        int todaySendSmsNumber = smsLogMapper.selectCount(new LambdaQueryWrapper<SmsLog>()
                .gt(SmsLog::getRecDate, DateUtil.beginOfDay(new Date()))
                .lt(SmsLog::getRecDate, DateUtil.endOfDay(new Date()))
                .eq(SmsLog::getUserId, userId)
                .eq(SmsLog::getType, smsType.value()));
        if (todaySendSmsNumber >= TODAY_MAX_SEND_VALID_SMS_NUMBER) {
            throw new YamiShopBindException("今日发送短信验证码次数已达到上限");
        }

        // 将上一条验证码失效
        smsLogMapper.invalidSmsByMobileAndType(mobile, smsType.value());

        String code = RandomUtil.randomNumbers(6);
        params.put("code", code);
    }
    smsLog.setType(smsType.value());
    smsLog.setMobileCode(params.get("code"));
    smsLog.setRecDate(new Date());
    smsLog.setStatus(1);
    smsLog.setUserId(userId);
    smsLog.setUserPhone(mobile);
    smsLog.setContent(formatContent(smsType, params));
    smsLogMapper.insert(smsLog);
    try {
        this.sendSms(mobile, smsType.getTemplateCode(), params);
    } catch (ClientException e) {
        throw new YamiShopBindException("发送短信失败,请稍后再试");
    }


}