Redis实战篇(一)短信登陆

Redis实战篇(一)短信登陆_第1张图片

一、短信登陆

Redis实战篇(一)短信登陆_第2张图片
Redis实战篇(一)短信登陆_第3张图片

1、发送短信验证码


	@Autowired
	private StringRedisTemplate stringRedisTemplate;

    public Result sendcode(String phone, HttpSession session){
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.如果不符合,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        //3.符合,生成验证码
        String code=Randomutil.randomNumbers(6);
        //4.保存验证码到redis//set key value ex120
        stringRedisTemplate.opsForValue().set("Login:code:"+phone,code,2, TimeUnit.MINUTES);
        //5,发送验证码
        log.debug("发送短信验证码成功,验证码:",code);
        //返回0k
        return Result.ok();
    }

2、登陆

@Override
public Result login(LoginFormDTO loginForm, HttpSession session) {
    //1.校验手机号
    final String phone = loginForm.getPhone();
    if (RegexUtils.isPhoneInvalid(phone)) {
        //2.如果不符合,返回错误信息
        return Result.fail("手机号格式错误!");

    }
    //2.校验验证码,从redis中获取
    final String cacheCode = stringRedisTemplate.opsForValue().get("Login:code:"+phone);
    final String code = loginForm.getCode();
    if(cacheCode==null||!cacheCode.equals(code)){
        //3.前端传入的和redis获取的不一致,报错
        return Result.fail("验证码错误");
    }
    //4.一致,根据手机号查询用户
    User user = query().eq("phone", phone).one();
    //5.判断用户是否存在
    if (user == null) {
        //6.不存在,创建新用户并保存
        user = createUserWithPhone(phone);
    }
    //7.保存用户信息到redis中
    	//7.1随机生成token,作为登陆令牌
    String token = UUID.randomUUID().toString(true);
    	//7.2将User对象转为HashMap存储
    UserDTO userDTO = BeanUtil.copyProperties(user,UserDTO.class);
    final Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
            CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->{
                return fieldValue.toString();
            })
    );
   		//7.3存储
    stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,map);
    	//7.4设置token有效期
    stringRedisTemplate.expire(LOGIN_USER_KEY+token,3000,TimeUnit.MINUTES);
    //8.返回token
    return Result.ok(token);
}

3、校验登陆

首先,对于每个请求,我们首先根据token判断用户是否已经登陆(是否已经保存到ThreadLocal中),如果没有登陆,放行交给登陆拦截器去做,如果已经登陆,刷新token的有效期,然后放行。
之后来到登陆拦截器,如果ThreadLocal没有用户,说明没有登陆,拦截,否则放行。
Redis实战篇(一)短信登陆_第4张图片
刷新token有效期拦截器

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response
    						, Object handler) throws Exception {
        //1.获取请求头中的token
        final String token = request.getHeader("authorization");
        if (token == null) {
            return true;
        }
        //2.获取redis中的用户
        final Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        //3.判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }
        //5.将查询到的Hash数据转换为UserDto对象
        final UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //6.存在,保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //7.刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,3000, TimeUnit.MINUTES);
        //8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
    				Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}

登录拦截器



public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
    							Object handler) throws Exception {
        //1.判断是否需要拦截(ThreadLocal中是否有用户)
        if(UserHolder.getUser()==null){
            response.setStatus(401);
            return false;
        }
        //8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
    			Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}



@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //登陆拦截器
        registry.addInterceptor(new LoginInterceptor()).excludePathPatterns(
                "/user/code","/user/login","/blog/hot","/shop/**","/shop-type/**","/upload/**"
                ,"/voucher/**"
        ).order(1);
        //token属性的拦截器
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);
    }
}

你可能感兴趣的:(Redis,redis,java,数据库)