org.springframework.util.DigestUtils Java Examples

The following examples show how to use org.springframework.util.DigestUtils. 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: LoginService.java    From xxl-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * login
 *
 * @param response
 * @param usernameParam
 * @param passwordParam
 * @param ifRemember
 * @return
 */
public ReturnT<String> login(HttpServletResponse response, String usernameParam, String passwordParam, boolean ifRemember){

    XxlApiUser xxlApiUser = xxlApiUserDao.findByUserName(usernameParam);
    if (xxlApiUser == null) {
        return new ReturnT<String>(500, "账号或密码错误");
    }

    String passwordParamMd5 = DigestUtils.md5DigestAsHex(passwordParam.getBytes());
    if (!xxlApiUser.getPassword().equals(passwordParamMd5)) {
        return new ReturnT<String>(500, "账号或密码错误");
    }

    String loginToken = makeToken(xxlApiUser);

    // do login
    CookieUtil.set(response, LOGIN_IDENTITY, loginToken, ifRemember);
    return ReturnT.SUCCESS;
}
 
Example #2
Source File: RegisterServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int register(String userName,String userPwd) {

	TbMember tbMember=new TbMember();
	tbMember.setUsername(userName);

	if(userName.isEmpty()||userPwd.isEmpty()){
		return -1; //用户名密码不能为空
	}
	boolean result = checkData(userName, 1);
	if (!result) {
		return 0; //该用户名已被注册
	}

	//MD5加密
	String md5Pass = DigestUtils.md5DigestAsHex(userPwd.getBytes());
	tbMember.setPassword(md5Pass);
	tbMember.setState(1);
	tbMember.setCreated(new Date());
	tbMember.setUpdated(new Date());

	if(tbMemberMapper.insert(tbMember)!=1){
		throw new XmallException("注册用户失败");
	}
	return 1;
}
 
Example #3
Source File: XxlApiUserController.java    From xxl-api with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping("/updatePwd")
@ResponseBody
public ReturnT<String> updatePwd(HttpServletRequest request, String password){

	// new password(md5)
	if (StringTool.isBlank(password)){
		return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空");
	}
	if (!(password.length()>=4 && password.length()<=100)) {
		return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码长度限制为4~50");
	}
	String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

	// update pwd
	XxlApiUser loginUser = (XxlApiUser) request.getAttribute(LoginService.LOGIN_IDENTITY);

	XxlApiUser existUser = xxlApiUserDao.findByUserName(loginUser.getUserName());
	existUser.setPassword(md5Password);
	xxlApiUserDao.update(existUser);

	return ReturnT.SUCCESS;
}
 
Example #4
Source File: MemberServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TbMember updateMember(Long id,MemberDto memberDto) {

    TbMember tbMember = DtoUtil.MemberDto2Member(memberDto);
    tbMember.setId(id);
    tbMember.setUpdated(new Date());
    TbMember oldMember=getMemberById(id);
    tbMember.setState(oldMember.getState());
    tbMember.setCreated(oldMember.getCreated());
    if(tbMember.getPassword()==null||tbMember.getPassword()==""){
        tbMember.setPassword(oldMember.getPassword());
    }else{
        String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
        tbMember.setPassword(md5Pass);
    }

    if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1){
        throw new XmallException("更新会员信息失败");
    }
    return getMemberById(id);
}
 
Example #5
Source File: MemberServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TbMember addMember(MemberDto memberDto) {

    TbMember tbMember= DtoUtil.MemberDto2Member(memberDto);

    if(getMemberByUsername(tbMember.getUsername())!=null){
        throw new XmallException("用户名已被注册");
    }
    if(getMemberByPhone(tbMember.getPhone())!=null){
        throw new XmallException("手机号已被注册");
    }
    if(getMemberByEmail(tbMember.getEmail())!=null){
        throw new XmallException("邮箱已被注册");
    }

    tbMember.setState(1);
    tbMember.setCreated(new Date());
    tbMember.setUpdated(new Date());
    String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
    tbMember.setPassword(md5Pass);

    if(tbMemberMapper.insert(tbMember)!=1){
        throw new XmallException("添加用户失败");
    }
    return getMemberByPhone(tbMember.getPhone());
}
 
Example #6
Source File: AppCacheManifestTransformer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Mono<? extends Resource> transform(String content, Resource resource,
		ResourceTransformerChain chain, ServerWebExchange exchange) {

	if (!content.startsWith(MANIFEST_HEADER)) {
		if (logger.isTraceEnabled()) {
			logger.trace(exchange.getLogPrefix() +
					"Skipping " + resource + ": Manifest does not start with 'CACHE MANIFEST'");
		}
		return Mono.just(resource);
	}
	return Flux.generate(new LineInfoGenerator(content))
			.concatMap(info -> processLine(info, exchange, resource, chain))
			.reduce(new ByteArrayOutputStream(), (out, line) -> {
				writeToByteArrayOutputStream(out, line + "\n");
				return out;
			})
			.map(out -> {
				String hash = DigestUtils.md5DigestAsHex(out.toByteArray());
				writeToByteArrayOutputStream(out, "\n" + "# Hash: " + hash);
				return new TransformedResource(resource, out.toByteArray());
			});
}
 
Example #7
Source File: LoginService.java    From xxl-conf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * login
 *
 * @param response
 * @param usernameParam
 * @param passwordParam
 * @param ifRemember
 * @return
 */
public ReturnT<String> login(HttpServletResponse response, String usernameParam, String passwordParam, boolean ifRemember){

    XxlConfUser xxlConfUser = xxlConfUserDao.load(usernameParam);
    if (xxlConfUser == null) {
        return new ReturnT<String>(500, "账号或密码错误");
    }

    String passwordParamMd5 = DigestUtils.md5DigestAsHex(passwordParam.getBytes());
    if (!xxlConfUser.getPassword().equals(passwordParamMd5)) {
        return new ReturnT<String>(500, "账号或密码错误");
    }

    String loginToken = makeToken(xxlConfUser);

    // do login
    CookieUtil.set(response, LOGIN_IDENTITY, loginToken, ifRemember);
    return ReturnT.SUCCESS;
}
 
Example #8
Source File: UserController.java    From SimpleBBS with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String register(User user, Invitecode invitecode, @RequestParam(value = "yzm", required = false) String yzm, HttpSession session) {
    if (user.getUname().length() > 16 || user.getUpwd().length() > 16 || user.getUpwd().length() < 6) {
        return "注册失败:用户名或密码长度必须小于16位";
    }

    if (session.getAttribute("yzm").equals(yzm.toLowerCase())) {
        user.setUpwd(DigestUtils.md5DigestAsHex(user.getUpwd().getBytes()));
        user.setLevel(1);
        user.setUcreatetime(new Date());
        user.setUstate(1);
        try {
            userService.register(user, invitecode);
            return "注册成功";
        } catch (MessageException e) {
            return e.getMessage();
        }
    } else
        return "验证码错误";

}
 
Example #9
Source File: ProfileController.java    From yyblog with MIT License 6 votes vote down vote up
@PostMapping("/edit")
@ResponseBody
public YYBlogResult edit(String username, String nickname, 
        String password1, String password2, String avatar) {
    if (password1.equals(password2)) {
        UserDO user = new UserDO();
        user.setUsername(username);
        if (!StringUtils.isEmpty(password1)) {
            user.setPassword(DigestUtils.md5DigestAsHex(password1.getBytes()));    
        }
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setUpdateTime(new Date());
        return userService.updateByUsername(user);
    }
    return YYBlogResult.build(500, "密码验证不一致,请检查!");
}
 
Example #10
Source File: UserController.java    From xxl-conf with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping("/updatePwd")
@ResponseBody
public ReturnT<String> updatePwd(HttpServletRequest request, String password){

    // new password(md5)
    if (StringUtils.isBlank(password)){
        return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空");
    }
    if (!(password.length()>=4 && password.length()<=100)) {
        return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码长度限制为4~50");
    }
    String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

    // update pwd
    XxlConfUser loginUser = (XxlConfUser) request.getAttribute(LoginService.LOGIN_IDENTITY);

    XxlConfUser existUser = xxlConfUserDao.load(loginUser.getUsername());
    existUser.setPassword(md5Password);
    xxlConfUserDao.update(existUser);

    return ReturnT.SUCCESS;
}
 
Example #11
Source File: Md5FingerprintProvider.java    From errors-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a fingerprint based on the exception and the current timestamp.
 *
 * @param httpError Error event for which fingerprint is generated.
 * @return The generated fingerprint.
 */
@Override
public String generate(@NonNull HttpError httpError) {
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        write(outputStream, exceptionName(httpError));
        write(outputStream, System.currentTimeMillis());

        // To ensure that the fingerprint is unique when the same exception is handled
        // at almost the same time in the same JVM instance.
        write(outputStream, System.nanoTime());

        return DigestUtils.md5DigestAsHex(outputStream.toByteArray());
    } catch (Exception e) {
        logger.warn("Failed to generate a fingerprint for {}", httpError);
        return null;
    }
}
 
Example #12
Source File: AdminServiceImpl.java    From notes with Apache License 2.0 6 votes vote down vote up
@Override
public AdminDto addAdmin(AdminDto dto) throws CommonException {

    String password = StringUtils.trimToEmpty(dto.getAdminPassword());
    if (EMPTY.equals(password)){
        throw new CommonException(ERROR_REGISTRYPASSWORD100011);
    }

    String name = StringUtils.trimToEmpty(dto.getAdminName());
    if (EMPTY.equals(name)){
        throw new CommonException(ERROR_REGISTRY_ADMIN_NAME100012);
    }

    String salt = RandomStringUtils.randomNumeric(6);
    dto.setAdminSalt(salt);
    String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
    dto.setAdminPassword(md5Password);
    int adminId = adminDtoMapper.insert(dto);
    dto.setAdminId(Long.parseLong(String.valueOf(adminId)));
    dto.setAdminSalt(null);
    return dto;
}
 
Example #13
Source File: UserServiceImpl.java    From lightconf with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ResultCode<User> addUser(User confUser) {

    ResultCode<User> resultCode = new ResultCode();

    // valid
    if (StringUtils.isBlank(confUser.getUserName()) || StringUtils.isBlank(confUser.getPassword())) {
        resultCode.setCode(Messages.INPUT_ERROR_CODE);
        resultCode.setMsg(Messages.INPUT_ERROR_MSG);
        return resultCode;
    }
    if (!(confUser.getPassword().length() >= 4 && confUser.getPassword().length() <= 100)) {
        resultCode.setCode(Messages.INPUT_ERROR_CODE);
        resultCode.setMsg(Messages.INPUT_ERROR_MSG);
        return resultCode;
    }

    // passowrd md5
    String md5Password = DigestUtils.md5DigestAsHex(confUser.getPassword().getBytes());
    confUser.setPassword(md5Password);
    userMapper.insert(confUser);
    resultCode.setData(confUser);
    return resultCode;
}
 
Example #14
Source File: LoginServiceImpl.java    From goods-seckill with Apache License 2.0 6 votes vote down vote up
@Override
public ResultCode<String> loginUser(String sessionID, SeckillUserEntity user) {
	ResultCode<String> result = new ResultCode<>();

	if (user.getId() == null)
		return result.ERROE("手机号不能为空");
	if (user.getPassword() == null)
		return result.ERROE("密码不能为空");
	
	SeckillUserEntity userEntity = seckillUserEntityMapper.selectByPrimaryKey(user.getId());
	if (userEntity == null)
		return result.ERROE("手机号未注册");
	
	if (!DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).equals(userEntity.getPassword())) {
		return result.ERROE("密码不正确");
	}
	
	RedisUtil.setValue("user_login_" + sessionID, user.getId().toString());

	return result.OK(null);
}
 
Example #15
Source File: UserController.java    From JavaQuarkBBS with Apache License 2.0 6 votes vote down vote up
@ApiOperation("登录接口")
@ApiImplicitParams({
        @ApiImplicitParam(name = "email", value = "用户邮箱",dataType = "String"),
        @ApiImplicitParam(name = "password", value = "用户密码",dataType = "String")
})
@PostMapping("/login")
public QuarkResult Login(String email,String password) {

    QuarkResult result = restProcessor(() -> {
        User loginUser = userService.findByEmail(email);
        if (loginUser == null)
            return QuarkResult.warn("用户邮箱不存在,请重新输入");
        if (!loginUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())))
            return QuarkResult.warn("用户密码错误,请重新输入");
        String token = userService.LoginUser(loginUser);
        return QuarkResult.ok(token);
    });
    return result;
}
 
Example #16
Source File: AbstractSockJsService.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
	if (request.getMethod() != HttpMethod.GET) {
		sendMethodNotAllowed(response, HttpMethod.GET);
		return;
	}

	String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl());
	byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
	StringBuilder builder = new StringBuilder("\"0");
	DigestUtils.appendMd5DigestAsHex(contentBytes, builder);
	builder.append('"');
	String etagValue = builder.toString();

	List<String> ifNoneMatch = request.getHeaders().getIfNoneMatch();
	if (!CollectionUtils.isEmpty(ifNoneMatch) && ifNoneMatch.get(0).equals(etagValue)) {
		response.setStatusCode(HttpStatus.NOT_MODIFIED);
		return;
	}

	response.getHeaders().setContentType(new MediaType("text", "html", StandardCharsets.UTF_8));
	response.getHeaders().setContentLength(contentBytes.length);

	// No cache in order to check every time if IFrame are authorized
	addNoCacheHeaders(response);
	response.getHeaders().setETag(etagValue);
	response.getBody().write(contentBytes);
}
 
Example #17
Source File: MyStringUtils.java    From EosProxyServer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取指定内容的md5值,暂时不加盐
 * @param source
 * @return
 */
public static String getMD5(String source) {
	if (source==null) {
		return null;
	}
	String MD5 = DigestUtils.md5DigestAsHex(source.getBytes());
	return MD5;
}
 
Example #18
Source File: ArcusCache.java    From arcus-spring with Apache License 2.0 5 votes vote down vote up
/**
 * serviceId, prefix, name 값을 사용하여 아커스 키를 생성합니다. serviceId는 필수값이며, prefix 또는
 * name 둘 중에 하나가 반드시 있어야 합니다. name과 prefix값이 모두 있다면 prefix 값을 사용합니다.
 * <p>
 * 키 생성 로직은 다음과 같습니다.
 * <p>
 * serviceId + (prefix | name) + ":" + key.toString();
 * <p>
 * 만약 전체 키의 길이가 250자를 넘을 경우에는 key.toString() 대신 그 값을 MD5로 압축한 값을 사용합니다.
 *
 * @param key
 * @return
 */
public String createArcusKey(final Object key) {
  Assert.notNull(key);
  String keyString, arcusKey;

  if (key instanceof ArcusStringKey) {
    keyString = ((ArcusStringKey) key).getStringKey().replace(' ', '_') +
            String.valueOf(((ArcusStringKey) key).getHash());
  } else if (key instanceof Integer) {
    keyString = key.toString();
  } else {
    keyString = key.toString();
    int hash = ArcusStringKey.light_hash(keyString);
    keyString = keyString.replace(' ', '_') + String.valueOf(hash);
  }

  arcusKey = serviceId + name + ":" + keyString;
  if (this.prefix != null) {
    arcusKey = serviceId + prefix + ":" + keyString;
  }
  if (arcusKey.length() > 250) {
    String digestedString = DigestUtils.md5DigestAsHex(keyString
            .getBytes());
    arcusKey = serviceId + name + ":" + digestedString;
    if (this.prefix != null) {
      arcusKey = serviceId + prefix + ":" + digestedString;
    }
  }
  return arcusKey;
}
 
Example #19
Source File: LoginService.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
private String makeToken(String username, String password) {
    // md5
    String tokenTmp = DigestUtils.md5DigestAsHex(String.valueOf(username + "_" + password).getBytes());
    // md5-hex
    tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);
    return tokenTmp;
}
 
Example #20
Source File: UserServiceImpl.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ResultCode<User> updateUser(User confUser) {


    ResultCode<User> resultCode = new ResultCode();

    // valid
    if (StringUtils.isBlank(confUser.getUserName()) || StringUtils.isBlank(confUser.getPassword())) {
        resultCode.setCode(Messages.INPUT_ERROR_CODE);
        resultCode.setMsg(Messages.INPUT_ERROR_MSG);
        return resultCode;
    }

    if (!(confUser.getPassword().length() >= 4 && confUser.getPassword().length() <= 100)) {
        resultCode.setCode(Messages.INPUT_ERROR_CODE);
        resultCode.setMsg(Messages.INPUT_ERROR_MSG);
        return resultCode;
    }

    // update password
    // passowrd md5
    if (StringUtils.isNotBlank(confUser.getPassword())) {
        String md5Password = DigestUtils.md5DigestAsHex(confUser.getPassword().getBytes());
        confUser.setPassword(md5Password);
    }
    userMapper.updateByPrimaryKey(confUser);
    resultCode.setData(confUser);
    return resultCode;
}
 
Example #21
Source File: StorageService.java    From fish-admin with MIT License 5 votes vote down vote up
/**
 * 如果图片的大小大于1M,那么进行等比压缩为1280x1280图片
 * @param file
 * @return
 * @throws Exception
 */
public Storage store(MultipartFile file) throws Exception {

    if (file.isEmpty()) {
        throw new Exception("Failed to store empty file " + file.getOriginalFilename());
    }

    String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    byte[] bytes;
    // 如果原图片大于1M, 那么压缩图片
    if (file.getSize() > M) {
        bytes = ImageUtil.compress(file.getInputStream(), fileType, 1920, 1920);
    } else {
        bytes = file.getBytes();
    }

    String contentHash = DigestUtils.md5DigestAsHex(bytes);
    Storage oldStorage = storageRepository.findByFileHash(contentHash);
    if (oldStorage != null) return oldStorage;

    try {
        Path destDir = Paths.get(storageDirectory, contentHash.substring(0, 2));
        if (!Files.exists(destDir)) Files.createDirectory(destDir);

        // String filePath = contentHash.substring(0, 2) + "/" + contentHash.substring(2) + "." + fileType;
        Storage storage = new Storage();
        storage.setFileHash(contentHash);
        storage.setFileName(file.getName());
        storage.setFileType(file.getContentType());
        storage.setFileSize(file.getSize());
        storage.setOriginalFileName(file.getOriginalFilename());

        return storageRepository.save(storage);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}
 
Example #22
Source File: MethodInterceptorHolder.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static MethodInterceptorHolder create(MethodInvocation invocation) {
    String id = DigestUtils.md5DigestAsHex(String.valueOf(invocation.getMethod().hashCode()).getBytes());
    String[] argNames = nameDiscoverer.getParameterNames(invocation.getMethod());
    Object[] args = invocation.getArguments();
    Map<String, Object> argMap = new LinkedHashMap<>();
    for (int i = 0, len = args.length; i < len; i++) {
        argMap.put((argNames == null || argNames[i] == null) ? "arg" + i : argNames[i], args[i]);
    }
    return new MethodInterceptorHolder(id,
            invocation.getMethod(),
            invocation.getThis(), argMap);
}
 
Example #23
Source File: ContentBasedVersionStrategyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getResourceVersion() throws IOException {
	Resource expected = new ClassPathResource("test/bar.css", getClass());
	String hash = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(expected.getInputStream()));

	assertEquals(hash, this.versionStrategy.getResourceVersion(expected));
}
 
Example #24
Source File: ContentVersionStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String getResourceVersion(Resource resource) {
	try {
		byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
		return DigestUtils.md5DigestAsHex(content);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to calculate hash for " + resource, ex);
	}
}
 
Example #25
Source File: PermissionInterceptor.java    From xxl-rpc with GNU General Public License v3.0 5 votes vote down vote up
public static boolean login(HttpServletResponse response, String username, String password, boolean ifRemember){

		// login token
		String tokenTmp = DigestUtils.md5DigestAsHex(String.valueOf(username + "_" + password).getBytes());
		tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);

		if (!getLoginIdentityToken().equals(tokenTmp)){
			return false;
		}

		// do login
		CookieUtil.set(response, LOGIN_IDENTITY_KEY, getLoginIdentityToken(), ifRemember);
		return true;
	}
 
Example #26
Source File: AppCacheManifestTransformer.java    From java-technology-stack with MIT License 5 votes vote down vote up
public void add(LineOutput lineOutput) throws IOException {
	this.writer.write(lineOutput.getLine() + "\n");
	byte[] bytes = (lineOutput.getResource() != null ?
			DigestUtils.md5Digest(getResourceBytes(lineOutput.getResource())) :
			lineOutput.getLine().getBytes(DEFAULT_CHARSET));
	this.baos.write(bytes);
}
 
Example #27
Source File: ContentVersionStrategy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getResourceVersion(Resource resource) {
	try {
		byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
		return DigestUtils.md5DigestAsHex(content);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to calculate hash for " + resource, ex);
	}
}
 
Example #28
Source File: UserServiceImpl.java    From dbys with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String regapp(User user, String yzm) {
    Map<String, String> map = new HashMap<>(3);
    if (yzm == null) {
        map.put("message", "验证码有误");
        return JSON.toJSONString(map);
    }
    if (user != null) {
        String str = registerValidateService.getVerificationCode(user.getEmail());
        if (str != null && str.equals(yzm)) {
            registerValidateService.deleteVerificationCode(user.getEmail());
            User user2 = new User();
            user2.setUsername(user.getUsername());
            User user1 = getUser(user2);
            User user3 = getUserByEmail(user.getEmail());
            if (user3 != null) {
                map.put("message", "邮箱已存在");
                return JSON.toJSONString(map);
            }
            if (user1 == null) {
                user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername()+user.getPassword()).getBytes()));
                user.setUserType(1);
                user.setHeadurl("http://gravatar.com/avatar/" + user.getUsername() + "?s=256&d=identicon");
                if (addUser(user)) {
                    map.put("message", "注册成功");
                    map.put("zt", "ok");
                    return JSON.toJSONString(map);
                }
            } else {
                map.put("message", "用户名已存在");
            }
        } else {
            map.put("message", "验证码有误");
        }
    }
    return JSON.toJSONString(map);
}
 
Example #29
Source File: UserServiceImpl.java    From dbys with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reg(User user, Model model, String yzm) {
    if (user != null) {
        if (yzm == null) {
            model.addAttribute("message", "验证码有误");
            return;
        }

        if(!Pattern.matches("^[\u4e00-\u9fa5_a-zA-Z0-9]+$",user.getUsername())){
            model.addAttribute("message", "用户名不能有符号");
            return;
        }
        String str = registerValidateService.getVerificationCode(user.getEmail());
        if (str != null && str.equals(yzm)) {
            registerValidateService.deleteVerificationCode(user.getEmail());
            User user2 = new User();
            user2.setUsername(user.getUsername());
            User user1 = getUser(user2);
            User user3 = getUserByEmail(user.getEmail());
            if (user3 != null) {
                model.addAttribute("message", "邮箱已存在");
                return;
            }
            if (user1 == null) {
                user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername()+user.getPassword()).getBytes()));
                user.setUserType(1);
                user.setHeadurl("http://gravatar.com/avatar/" + user.getUsername() + "?s=256&d=identicon");
                if (addUser(user)) {
                    model.addAttribute("message", "注册成功");
                    return;
                }
            } else {
                model.addAttribute("message", "用户名已存在");
            }
        } else {
            model.addAttribute("message", "验证码有误");
        }
    }
    return;
}
 
Example #30
Source File: PatchService.java    From tinker-manager with Apache License 2.0 5 votes vote down vote up
public PatchInfo savePatch(AppInfo appInfo, VersionInfo versionInfo, String description, MultipartFile multipartFile) {
    List<PatchInfo> patchInfoList = patchInfoMapper.findByUidAndVersionName(appInfo.getUid(),versionInfo.getVersionName());
    int maxPatchVersion = getMaxPatchVersion(patchInfoList) + 1;
    String childPath = appInfo.getUid() + "/" + versionInfo.getVersionName() + "/" + maxPatchVersion + "/";
    PatchInfo patchInfo = new PatchInfo();
    try {
        String fileHash = DigestUtils.md5DigestAsHex(multipartFile.getBytes());
        File path = new File(new File(fileStoragePath), childPath);
        File patchFile = new File(path,fileHash + "_patch.zip");

        if (!path.exists() && !path.mkdirs()) {
            throw new BizException("文件目录创建失败");
        }
        multipartFile.transferTo(patchFile);

        patchInfo.setUserId(appInfo.getUserId());
        patchInfo.setAppUid(appInfo.getUid());
        patchInfo.setUid(UUID.randomUUID().toString().replaceAll("-", ""));
        patchInfo.setVersionName(versionInfo.getVersionName());
        patchInfo.setPatchVersion(maxPatchVersion);
        patchInfo.setPatchSize(patchFile.length());
        patchInfo.setFileHash(fileHash);
        patchInfo.setDescription(description);
        patchInfo.setStoragePath(patchFile.getAbsolutePath());
        patchInfo.setDownloadUrl(getDownloadUrl(patchStaticUrl,childPath + patchFile.getName()));
        patchInfo.setCreatedAt(new Date());
        patchInfo.setUpdatedAt(new Date());

        Integer id = patchInfoMapper.insert(patchInfo);
        patchInfo.setId(id);
    } catch (IOException e) {
        e.printStackTrace();
        throw new BizException("文件保存失败");
    }

    facadeService.clearCache();
    return patchInfo;
}