Parcourir la source

redis实现验证码功能

zhh il y a 6 ans
Parent
commit
50e8932645

+ 5 - 4
README.md

@@ -50,13 +50,14 @@ JWT登录、注册、获取token | ✔
 JTA事务处理 | ✔
 集成单元测试 | ✔
 OSS上传功能 | ✔
-SpringSecurity权限管理功能 |
 Elasticsearch搜索功能 | ✔
-Elasticsearch日志收集功能 |
+SpringSecurity权限管理功能 |
+HTTPS支持 | ✔
+日志收集功能 |
 数字型ID生成 |
-HTTPS支持 |
 定时任务支持 |
 RestTemplate服务间调用 |
+docker容器化部署 |
 
 ### 后台功能
 
@@ -283,7 +284,7 @@ RestTemplate服务间调用 |
 - 在线支付选择支付方式:支付宝、微信、银联、ApplePay
 - 支付完成后修改订单状态为已支付、扣除库存
 
-#### 会员模块(我的)
+#### 会员模块(我的)
 
 > **我的关注**
 

+ 10 - 0
mall-portal/pom.xml

@@ -64,6 +64,16 @@
             <artifactId>springfox-swagger-ui</artifactId>
             <version>2.6.1</version>
         </dependency>
+        <!--redis依赖配置-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-cache</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-redis</artifactId>
+            <version>1.3.8.RELEASE</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 6 - 6
mall-portal/src/main/java/com/macro/mall/portal/config/SecurityConfig.java

@@ -62,12 +62,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
                 .logoutSuccessHandler(new GoLogoutSuccessHandler())
                 .invalidateHttpSession(true)
                 .deleteCookies("JSESSIONID")
-                .and()
-                .requiresChannel()
-                .antMatchers("/sso/*")
-                .requiresSecure()
-                .anyRequest()
-                .requiresInsecure()
+//                .and()
+//                .requiresChannel()
+//                .antMatchers("/sso/*")
+//                .requiresSecure()
+//                .anyRequest()
+//                .requiresInsecure()
 //                .and()
 //                .rememberMe()
 //                .tokenValiditySeconds(1800)

+ 1 - 7
mall-portal/src/main/java/com/macro/mall/portal/controller/UmsMemberController.java

@@ -1,7 +1,5 @@
 package com.macro.mall.portal.controller;
 
-import com.macro.mall.model.UmsMember;
-import com.macro.mall.portal.domain.CommonResult;
 import com.macro.mall.portal.service.UmsMemberService;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -30,11 +28,7 @@ public class UmsMemberController {
                            @RequestParam String password,
                            @RequestParam String telephone,
                            @RequestParam String authCode) {
-        UmsMember member = memberService.register(username, password, telephone, authCode);
-        if (member != null) {
-            return new CommonResult().success(member);
-        }
-        return new CommonResult().failed();
+        return memberService.register(username, password, telephone, authCode);
     }
 
     @ApiOperation("获取验证码")

+ 28 - 0
mall-portal/src/main/java/com/macro/mall/portal/service/RedisService.java

@@ -0,0 +1,28 @@
+package com.macro.mall.portal.service;
+
+/**
+ * redis操作Service,
+ * 对象和数组都以json形式进行存储
+ * Created by macro on 2018/8/7.
+ */
+public interface RedisService {
+    /**
+     * 存储数据
+     */
+    void set(String key, String value);
+
+    /**
+     * 获取数据
+     */
+    String get(String key);
+
+    /**
+     * 设置超期时间
+     */
+    boolean expire(String key, long expire);
+
+    /**
+     * 删除数据
+     */
+    void remove(String key);
+}

+ 4 - 1
mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java

@@ -18,7 +18,7 @@ public interface UmsMemberService {
      * 用户注册
      */
     @Transactional
-    UmsMember register(String username, String password, String telephone, String authCode);
+    CommonResult register(String username, String password, String telephone, String authCode);
 
     /**
      * 生成验证码
@@ -31,5 +31,8 @@ public interface UmsMemberService {
     @Transactional
     CommonResult updatePassword(String telephone, String password, String authCode);
 
+    /**
+     * 获取当前登录会员
+     */
     UmsMember getCurrentMember();
 }

+ 38 - 0
mall-portal/src/main/java/com/macro/mall/portal/service/impl/RedisServiceImpl.java

@@ -0,0 +1,38 @@
+package com.macro.mall.portal.service.impl;
+
+import com.macro.mall.portal.service.RedisService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * redis操作Service的实现类
+ * Created by macro on 2018/8/7.
+ */
+@Service
+public class RedisServiceImpl implements RedisService {
+    @Autowired
+    private StringRedisTemplate stringRedisTemplate;
+
+    @Override
+    public void set(String key, String value) {
+        stringRedisTemplate.opsForValue().set(key, value);
+    }
+
+    @Override
+    public String get(String key) {
+        return stringRedisTemplate.opsForValue().get(key);
+    }
+
+    @Override
+    public boolean expire(String key, long expire) {
+        return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
+    }
+
+    @Override
+    public void remove(String key) {
+        stringRedisTemplate.delete(key);
+    }
+}

+ 32 - 6
mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java

@@ -8,14 +8,17 @@ import com.macro.mall.model.UmsMemberLevel;
 import com.macro.mall.model.UmsMemberLevelExample;
 import com.macro.mall.portal.domain.CommonResult;
 import com.macro.mall.portal.domain.MemberDetails;
+import com.macro.mall.portal.service.RedisService;
 import com.macro.mall.portal.service.UmsMemberService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.security.authentication.encoding.PasswordEncoder;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContext;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
 
 import java.util.Date;
 import java.util.List;
@@ -33,6 +36,12 @@ public class UmsMemberServiceImpl implements UmsMemberService {
     private UmsMemberLevelMapper memberLevelMapper;
     @Autowired
     private PasswordEncoder passwordEncoder;
+    @Autowired
+    private RedisService redisService;
+    @Value("${redis.key.prefix.authCode}")
+    private String REDIS_KEY_PREFIX_AUTH_CODE;
+    @Value("${authCode.expire.seconds}")
+    private Long AUTH_CODE_EXPIRE_SECONDS;
 
     @Override
     public UmsMember getByUsername(String username) {
@@ -46,19 +55,23 @@ public class UmsMemberServiceImpl implements UmsMemberService {
     }
 
     @Override
-    public UmsMember register(String username, String password, String telephone, String authCode) {
-        // TODO: 2018/8/3 对验证码进行验证
+    public CommonResult register(String username, String password, String telephone, String authCode) {
+        //验证验证码
+        if(!verifyAuthCode(authCode,telephone)){
+            return new CommonResult().failed("验证码错误");
+        }
         //查询是否已有该用户
         UmsMemberExample example = new UmsMemberExample();
         example.createCriteria().andUsernameEqualTo(username);
         example.or(example.createCriteria().andPhoneEqualTo(telephone));
         List<UmsMember> umsMembers = memberMapper.selectByExample(example);
         if (!CollectionUtils.isEmpty(umsMembers)) {
-            return null;
+            return new CommonResult().failed("该用户已经存在");
         }
         //没有该用户进行添加操作
         UmsMember umsMember = new UmsMember();
         umsMember.setUsername(username);
+        umsMember.setPhone(telephone);
         umsMember.setPassword(passwordEncoder.encodePassword(password, null));
         umsMember.setCreateTime(new Date());
         umsMember.setStatus(1);
@@ -71,7 +84,7 @@ public class UmsMemberServiceImpl implements UmsMemberService {
         }
         memberMapper.insert(umsMember);
         umsMember.setPassword(null);
-        return umsMember;
+        return new CommonResult().success("注册成功",null);
     }
 
     @Override
@@ -81,7 +94,9 @@ public class UmsMemberServiceImpl implements UmsMemberService {
         for(int i=0;i<6;i++){
             sb.append(random.nextInt(10));
         }
-        // TODO: 2018/8/6 验证码进行存储
+        //验证码绑定手机号并存储到redis
+        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE+telephone,sb.toString());
+        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
         return new CommonResult().success("获取验证码成功",sb.toString());
     }
 
@@ -93,7 +108,10 @@ public class UmsMemberServiceImpl implements UmsMemberService {
         if(CollectionUtils.isEmpty(memberList)){
             return new CommonResult().failed("该账号不存在");
         }
-        // TODO: 2018/8/6 验证验证码
+        //验证验证码
+        if(!verifyAuthCode(authCode,telephone)){
+            return new CommonResult().failed("验证码错误");
+        }
         UmsMember umsMember = memberList.get(0);
         umsMember.setPassword(passwordEncoder.encodePassword(password,null));
         memberMapper.updateByPrimaryKeySelective(umsMember);
@@ -107,5 +125,13 @@ public class UmsMemberServiceImpl implements UmsMemberService {
         MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
         return memberDetails.getUmsMember();
     }
+    //对输入的验证码进行校验
+    private boolean verifyAuthCode(String authCode, String telephone){
+        if(StringUtils.isEmpty(authCode)){
+            return false;
+        }
+        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
+        return authCode.equals(realAuthCode);
+    }
 
 }

+ 26 - 0
mall-portal/src/main/resources/application.properties

@@ -29,3 +29,29 @@ spring.data.mongodb.port=27017
 spring.data.mongodb.database=mall-port
 #===mongodb end===
 
+#===redis start===
+# Redis数据库索引(默认为0)
+spring.redis.database=0
+# Redis服务器地址
+spring.redis.host=localhost
+# Redis服务器连接端口
+spring.redis.port=6379
+# Redis服务器连接密码(默认为空)
+spring.redis.password=
+# 连接池最大连接数(使用负值表示没有限制)
+spring.redis.pool.max-active=8
+# 连接池最大阻塞等待时间(使用负值表示没有限制)
+spring.redis.pool.max-wait=-1
+# 连接池中的最大空闲连接
+spring.redis.pool.max-idle=8
+# 连接池中的最小空闲连接
+spring.redis.pool.min-idle=0
+# 连接超时时间(毫秒)
+spring.redis.timeout=0
+#===redis end===
+
+#===redis custom key start===
+redis.key.prefix.authCode=portal:authCode:
+authCode.expire.seconds=90
+#===redis custom key end===
+