com.healthy.security.app.validate.code.impl.RedisValidateCodeRepository Maven / Gradle / Ivy
package com.healthy.security.app.validate.code.impl;
import cn.hutool.core.util.StrUtil;
import com.healthy.common.security.code.ValidateCode;
import com.healthy.common.security.code.ValidateCodeException;
import com.healthy.common.security.code.ValidateCodeRepository;
import com.healthy.common.security.code.ValidateCodeType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* A verification code accessor based on redis to avoid the problem of inaccessible
* verification codes due to no session
*
* @author xiaomingzhang
*/
@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {
@Resource
private RedisTemplate redisTemplate;
@Override
public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
redisTemplate.opsForValue().set(buildKey(request, type), code, 30, TimeUnit.MINUTES);
}
@Override
public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
Object value = redisTemplate.opsForValue().get(buildKey(request, type));
if (value == null) {
return null;
}
return (ValidateCode) value;
}
@Override
public void remove(ServletWebRequest request, ValidateCodeType type) {
redisTemplate.delete(buildKey(request, type));
}
private String buildKey(ServletWebRequest request, ValidateCodeType type) {
String deviceId = request.getHeader("deviceId");
if (StrUtil.isBlank(deviceId)) {
throw new ValidateCodeException("请在请求头中携带deviceId参数");
}
return "code:" + type.toString().toLowerCase() + ":" + deviceId;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy