Browse Source

用户登录错误次数验证 超过5次则禁用账户

andy 1 year ago
parent
commit
a909b89862

+ 50 - 38
src/main/java/com/beifan/foxlibc/modules/controller/AuthenticationController.java

@@ -30,7 +30,6 @@ import org.springframework.web.bind.annotation.RestController;
 
 import javax.validation.Valid;
 import java.util.Date;
-import java.util.List;
 import java.util.Objects;
 import java.util.regex.Pattern;
 
@@ -42,11 +41,13 @@ import java.util.regex.Pattern;
 @RestController
 public class AuthenticationController {
 
-    @Autowired private UserService userService;
+    @Autowired
+    private UserService userService;
 
 //    @Value("${foxlibc.debug}") private boolean __DEBUG__;
 
-    @Value("${foxlibc.mlogin}") private boolean __M_LOGIN__;
+    @Value("${foxlibc.mlogin}")
+    private boolean __M_LOGIN__;
 
     /**
      * 缓存
@@ -57,13 +58,13 @@ public class AuthenticationController {
     static String PWD_VALID_RGX =
             "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[`!@#$%^&*()_+{}\":?><,./';\\[\\]=-\\\\|])(?=\\S+$).{8,20}$";
 
+
     /**
      * 生成appToken
      */
     @NV_TOKEN
     @PostMapping("/application-token")
-    public R<AuthenticationOut> applicationToken(@Valid @RequestBody AuthenticationCodeIn authenticationCodeIn)
-    {
+    public R<AuthenticationOut> applicationToken(@Valid @RequestBody AuthenticationCodeIn authenticationCodeIn) {
         Assert.throwIfBool(userService.application(authenticationCodeIn.getAppid(), authenticationCodeIn.getAppSecret()),
                 "appid或app secret不正确");
 
@@ -71,12 +72,12 @@ public class AuthenticationController {
 //        String appToken = authenticationService.createToken(Maps.ofMap(JwtConst.APP, authenticationCodeIn.getAppid()));
 
         String appToken = UniqueUtils.uuid().toLowerCase();
-        Date expireTime = DateUtils.plus(new Date() , 1, TimeUnits.DAYS);
+        Date expireTime = DateUtils.plus(new Date(), 1, TimeUnits.DAYS);
 
         /* 记录登录信息 */
 //         Date expireTime = authenticationService.getExpireTime(appToken);
         String appid = authenticationCodeIn.getAppid();
-        UserLogininfo userLogininfo = new UserLogininfo(appid,null, expireTime, appToken, null,null,null);
+        UserLogininfo userLogininfo = new UserLogininfo(appid, null, expireTime, appToken, null, null, null);
         userService.saveUserLogininfo(userLogininfo);
 
         return R.ok(
@@ -90,8 +91,7 @@ public class AuthenticationController {
      */
     @NV_TOKEN
     @PostMapping("/valid/token")
-    public R<AuthenticationOut> validToken(@RequestHeader("Authorization") String token)
-    {
+    public R<AuthenticationOut> validToken(@RequestHeader("Authorization") String token) {
         /*   WRAN: 异常信息中的 -C401 是指定返回Code。
            如果删除了前端将不能通过 401 判断用户是否过期 */
         // Assert.throwIfBool(!jvmCache.contains(CacheConst.TOKEN_BLACKLIST(code)), "-C401 TOKEN已被禁用");
@@ -112,8 +112,7 @@ public class AuthenticationController {
      */
     @NV_TOKEN
     @PostMapping("/verification-code")
-    public R<String> verificationCode(@Valid @RequestBody MakeVerificationCodeIn makeVerificationCodeIn)
-    {
+    public R<String> verificationCode(@Valid @RequestBody MakeVerificationCodeIn makeVerificationCodeIn) {
         String code;
         SystemSet systemSet = userService.systemSetting();
 
@@ -125,7 +124,7 @@ public class AuthenticationController {
         } else {
             code = VerifyCodes.randomComplexVerifyCode(vlen);
         }
-        Date codeExpireTime = DateUtils.plus(new Date() , 60, TimeUnits.SECONDS);
+        Date codeExpireTime = DateUtils.plus(new Date(), 60, TimeUnits.SECONDS);
 
         // jvmCache.set(CacheConst.VERIFICATION_CODE(makeVerificationCodeIn.getAppToken()), code, (60 * 3));
         String appToken = makeVerificationCodeIn.getAppToken();
@@ -133,7 +132,7 @@ public class AuthenticationController {
         userLogininfo.setVerificationCode(code);
         userLogininfo.setCodeExpireTime(codeExpireTime);
 
-        userService.updateUserLogininfo(userLogininfo,appToken);
+        userService.updateUserLogininfo(userLogininfo, appToken);
 
         return R.ok(code);
     }
@@ -143,8 +142,7 @@ public class AuthenticationController {
      */
     @NV_TOKEN
     @PostMapping("/sign-in")
-    public R<AuthenticationOut> signin(@RequestHeader("Authorization") String appToken, @Valid @RequestBody AuthenticationUserIn authenticationUserIn)
-    {
+    public R<AuthenticationOut> signin(@RequestHeader("Authorization") String appToken, @Valid @RequestBody AuthenticationUserIn authenticationUserIn) {
         // String sessionid = getSessionId();
         String username = authenticationUserIn.getUsername();
         SystemSet systemSet = userService.systemSetting();
@@ -162,13 +160,30 @@ public class AuthenticationController {
                 Objects.equals(verificationCode, authenticationUserIn.getVerificationCode()) :
                 Objects.equals(verificationCode.toLowerCase(), authenticationUserIn.getVerificationCode().toLowerCase());
         Assert.throwIfBool(isCheckFull, "验证码不正确");
+//        查询用户
+        User u = userService.queryUserByUsername(username);
+
+        Assert.throwIfBool(!"0".equals(u.getUserStatus()), "当前用户状态已被禁用, 不允许登录");
+
+        String userid;
+        try {
+            /* 验证用户名密码是否可以登录 */
+            userid = userService.sign(username, authenticationUserIn.getPassword());
+//            验证成功则清零失败次数
+            userService.updateFailCount(username, 0);
+        } catch (Exception e) {
+//            验证失败 更新失败次数
+            if (u.getFailCount() < 4) {
+                userService.updateFailCount(username, u.getFailCount() + 1);
+            } else {
+//                超过次数则禁用用户,并且错误次数重置为0
+                userService.updateStatus(username, "0");
+                userService.updateFailCount(username, 0);
+            }
+//            并且抛出异常
+            throw e;
+        }
 
-        /* 验证用户名密码是否可以登录 */
-        String userid = userService.sign(username, authenticationUserIn.getPassword());
-
-        /* 获取用户信息 */
-        User user = userService.userQuery(userid);
-        Assert.throwIfBool(!"0".equals(user.getUserStatus()), "当前用户状态已被禁用, 不允许登录");
 
         /* 生成token */
 //        authenticationService.useEnv(JwtConst.USR);
@@ -176,7 +191,7 @@ public class AuthenticationController {
 //        Date tokenDate = authenticationService.getExpireTime(token);
 
         String token = UniqueUtils.uuid().toLowerCase();
-        Date tokenDate = DateUtils.plus(new Date() , 1, TimeUnits.DAYS);
+        Date tokenDate = DateUtils.plus(new Date(), 1, TimeUnits.DAYS);
 
         UserLogininfo appLoginInfo = userService.queryUserLogininfo(appToken);
         appLoginInfo.setVerificationCode(null);
@@ -186,11 +201,12 @@ public class AuthenticationController {
         appLoginInfo.setExpireTime(tokenDate);
 
         /* 如果不允许其他地方登陆的话,删除其他地方登录过的缓存 */
-        if (!__M_LOGIN__)
+        if (!__M_LOGIN__) {
             userService.deleteUserLogininfoByUserId(userid);
+        }
 
         /* 保存登录信息 */
-        userService.updateUserLogininfo(appLoginInfo,appToken);
+        userService.updateUserLogininfo(appLoginInfo, appToken);
 
         return R.ok(
                 "token", token,
@@ -203,15 +219,14 @@ public class AuthenticationController {
      * 刷新token
      */
     @PostMapping("/flush-token")
-    public R<Void> flushToken(@RequestHeader("Authorization") String token)
-    {
+    public R<Void> flushToken(@RequestHeader("Authorization") String token) {
         // String sessionid = getSessionId();
 //        String env = authenticationService.getEnv(token);
 
         UserLogininfo userLogininfo = userService.queryUserLogininfo(token);
-        Date expireTime = DateUtils.plus(new Date() , 1, TimeUnits.DAYS);
+        Date expireTime = DateUtils.plus(new Date(), 1, TimeUnits.DAYS);
         userLogininfo.setExpireTime(expireTime);
-        userService.updateUserLogininfo(userLogininfo,token);
+        userService.updateUserLogininfo(userLogininfo, token);
 
         return R.ok("expireTime", DateUtils.format(expireTime));
     }
@@ -220,8 +235,7 @@ public class AuthenticationController {
      * 退出登录
      */
     @PostMapping("/sign-out")
-    public R<Void> signout(@RequestHeader("Authorization") String token)
-    {
+    public R<Void> signout(@RequestHeader("Authorization") String token) {
         /* 添加到黑名单 */
 //        Date expireTime = authenticationService.getExpireTime(token);
 //        jvmCache.set(CacheConst.TOKEN_BLACKLIST(token), 0, expireTime);
@@ -236,8 +250,7 @@ public class AuthenticationController {
      * 获取系统设置
      */
     @PostMapping("/system/setting")
-    public R<SystemSet> systemSet()
-    {
+    public R<SystemSet> systemSet() {
         return R.ok(userService.systemSetting());
     }
 
@@ -247,8 +260,7 @@ public class AuthenticationController {
      */
     @NV_TOKEN
     @PostMapping("/sec-sign-in")
-    public R<AuthenticationOut> secsignin(@Valid @RequestBody AuthenticationSecUserIn authenticationUserIn)
-    {
+    public R<AuthenticationOut> secsignin(@Valid @RequestBody AuthenticationSecUserIn authenticationUserIn) {
         String userId = authenticationUserIn.getUserId();
         SystemSet systemSet = userService.systemSetting();
 
@@ -281,12 +293,12 @@ public class AuthenticationController {
 //        return R.ok(userService.authQuery(userid));
 //    }
 //
+
     /**
      * 修改用户密码
      */
     @PostMapping("/reset-passwd")
-    public R<Void> resetPasswd(@Valid @RequestBody ResetPasswdIn resetPasswdIn)
-    {
+    public R<Void> resetPasswd(@Valid @RequestBody ResetPasswdIn resetPasswdIn) {
         String userid = userService.idsign(resetPasswdIn.getUserId(), resetPasswdIn.getOriginPassword());
 
         /* 修改密码 */
@@ -300,12 +312,12 @@ public class AuthenticationController {
 
         return R.ok();
     }
+
     /**
      * 修改用户密码
      */
     @PostMapping("/reset-secpasswd")
-    public R<Void> resetSecPasswd(@Valid @RequestBody ResetSecPasswdIn resetPasswdIn)
-    {
+    public R<Void> resetSecPasswd(@Valid @RequestBody ResetSecPasswdIn resetPasswdIn) {
         String userid = resetPasswdIn.getUserId();
 
         /* 修改密码 */

+ 2 - 0
src/main/java/com/beifan/foxlibc/modules/pojo/model/User.java

@@ -25,4 +25,6 @@ public class User {
     private String userToken;
     @JSONField(name = "token_valid_time")
     private String tokenValidTime;
+    @JSONField(name = "fail_count")
+    private int failCount;
 }

+ 16 - 0
src/main/java/com/beifan/foxlibc/modules/service/UserService.java

@@ -88,4 +88,20 @@ public interface UserService {
     void updateUserPwd(String userid, String pwd);
 
     void updateUserSecPwd(String userid, String pwd);
+
+    /**
+     * 根据用户名查询用户
+     * @param username
+     * @return
+     */
+    User queryUserByUsername(String username);
+
+    /**
+     * 根据用户名更新失败次数
+     * @param username
+     * @param failCount
+     */
+    void updateFailCount(String username, int failCount);
+
+    void updateStatus(String username, String status);
 }

+ 41 - 20
src/main/java/com/beifan/foxlibc/modules/service/UserServiceImplements.java

@@ -11,8 +11,11 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Service;
 
+import java.util.ArrayList;
 import java.util.List;
 
+import static com.alibaba.fastjson.JSON.toJSONString;
+
 /**
  * @author lts
  * Create Time 2022/8/4
@@ -20,12 +23,13 @@ import java.util.List;
 @Service
 public class UserServiceImplements implements UserService {
 
-    @Autowired private JdbcTemplate jdbcTemplate;
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
 
     @Override
     public SystemSet systemSetting() {
         String sql = "SELECT * FROM t_system_set order by set_id desc limit 1";
-        return JSONObject.parseObject(JSON.toJSONString(jdbcTemplate.queryForMap(sql))).toJavaObject(SystemSet.class);
+        return JSONObject.parseObject(toJSONString(jdbcTemplate.queryForMap(sql))).toJavaObject(SystemSet.class);
     }
 
     @Override
@@ -62,9 +66,10 @@ public class UserServiceImplements implements UserService {
     @Override
     public User userQuery(String userId) {
         String sql = "SELECT * FROM t_user where user_id = ?";
-        return JSONObject.parseObject(JSON.toJSONString(jdbcTemplate.queryForMap(sql, userId))).toJavaObject(User.class);
+        return JSONObject.parseObject(toJSONString(jdbcTemplate.queryForMap(sql, userId))).toJavaObject(User.class);
     }
 
+
     @Override
     public List<UserAuth> authQuery(String userId) {
         return null;
@@ -79,39 +84,37 @@ public class UserServiceImplements implements UserService {
     @Override
     public void saveUserLogininfo(UserLogininfo userLogininfo) {
         String sql = "INSERT INTO `t_user_token_cache` (`appid`,`userId`, `expireTime`, `sessionId`, `token`,`verificationCode`) VALUES (?,?,?,?, ?, ?);";
-        jdbcTemplate.update(sql,userLogininfo.getAppid(), userLogininfo.getUserId(), userLogininfo.getExpireTime(), userLogininfo.getSessionId(), userLogininfo.getToken(),userLogininfo.getVerificationCode());
+        jdbcTemplate.update(sql, userLogininfo.getAppid(), userLogininfo.getUserId(), userLogininfo.getExpireTime(), userLogininfo.getSessionId(), userLogininfo.getToken(), userLogininfo.getVerificationCode());
     }
 
     @Override
-    public void updateUserLogininfo(UserLogininfo userLogininfo,String oldToken) {
+    public void updateUserLogininfo(UserLogininfo userLogininfo, String oldToken) {
         String sql = "UPDATE `t_user_token_cache` SET `token` = ?,`userId` = ?, `sessionId` = ?, `expireTime` = ?, `verificationCode` = ?,`codeExpireTime` = ? WHERE token = ?;";
-        jdbcTemplate.update(sql, userLogininfo.getToken(),userLogininfo.getUserId(), userLogininfo.getSessionId(), userLogininfo.getExpireTime(), userLogininfo.getVerificationCode(), userLogininfo.getCodeExpireTime(),oldToken);
+        jdbcTemplate.update(sql, userLogininfo.getToken(), userLogininfo.getUserId(), userLogininfo.getSessionId(), userLogininfo.getExpireTime(), userLogininfo.getVerificationCode(), userLogininfo.getCodeExpireTime(), oldToken);
     }
 
     @Override
     public void deleteUserLogininfoByToken(String token) {
-        String sql  = "DELETE FROM `t_user_token_cache` WHERE token = ?";
+        String sql = "DELETE FROM `t_user_token_cache` WHERE token = ?";
         jdbcTemplate.update(sql, token);
     }
 
     @Override
     public void deleteUserLogininfoByUserId(String userid) {
-        String sql  = "DELETE FROM `t_user_token_cache` WHERE userId = ?";
+        String sql = "DELETE FROM `t_user_token_cache` WHERE userId = ?";
         jdbcTemplate.update(sql, userid);
     }
 
     @Override
-    public UserLogininfo queryUserLogininfo(String token)
-    {
+    public UserLogininfo queryUserLogininfo(String token) {
         String sql = "SELECT * FROM t_user_token_cache  WHERE  token = ?";
         return Assert.throwIfError(() -> {
-            return JSONObject.parseObject(JSON.toJSONString(jdbcTemplate.queryForMap(sql, token))).toJavaObject(UserLogininfo.class);
+            return JSONObject.parseObject(toJSONString(jdbcTemplate.queryForMap(sql, token))).toJavaObject(UserLogininfo.class);
         }, "token已过期");
     }
 
     @Override
-    public List<UserLogininfo> queryUserLogininfosByUserId(String userId)
-    {
+    public List<UserLogininfo> queryUserLogininfosByUserId(String userId) {
         String sql = "SELECT * FROM t_user_token_cache  WHERE  userId = ?";
         return Assert.throwIfError(() -> {
             return jdbcTemplate.queryForList(sql, UserLogininfo.class, userId);
@@ -119,22 +122,40 @@ public class UserServiceImplements implements UserService {
     }
 
     @Override
-    public UserLogininfo queryUserLogininfosByUserIdPS(String userId)
-    {
+    public UserLogininfo queryUserLogininfosByUserIdPS(String userId) {
         String sql = "SELECT * FROM t_user_token_cache  WHERE  userId = ? and not isnull(token)";
         return Assert.throwIfError(() -> {
-            return JSONObject.parseObject(JSON.toJSONString(jdbcTemplate.queryForMap(sql, userId))).toJavaObject(UserLogininfo.class);
+            return JSONObject.parseObject(toJSONString(jdbcTemplate.queryForMap(sql, userId))).toJavaObject(UserLogininfo.class);
         }, "用户不存在");
     }
 
     @Override
     public void updateUserPwd(String userid, String pwd) {
-        String sql  = "UPDATE `t_user` SET user_pwd= ? WHERE user_id = ?";
-        jdbcTemplate.update(sql, pwd,userid);
+        String sql = "UPDATE `t_user` SET user_pwd= ? WHERE user_id = ?";
+        jdbcTemplate.update(sql, pwd, userid);
     }
+
     @Override
     public void updateUserSecPwd(String userid, String pwd) {
-        String sql  = "UPDATE `t_user` SET user_sec_pwd = ? WHERE user_id = ?";
-        jdbcTemplate.update(sql, pwd,userid);
+        String sql = "UPDATE `t_user` SET user_sec_pwd = ? WHERE user_id = ?";
+        jdbcTemplate.update(sql, pwd, userid);
+    }
+
+    @Override
+    public User queryUserByUsername(String username) {
+        ArrayList<Object> objects = new ArrayList<>();
+        objects.add(username);
+        Object[] args = objects.toArray();
+        return JSON.parseObject(toJSONString(jdbcTemplate.queryForMap("SELECT * FROM t_user WHERE user_name=? limit 1", args)), User.class);
+    }
+
+    @Override
+    public void updateFailCount(String username, int failCount) {
+        jdbcTemplate.update("UPDATE t_user SET fail_count = ? WHERE user_name = ?", failCount, username);
+    }
+
+    @Override
+    public void updateStatus(String username, String status) {
+        jdbcTemplate.update("UPDATE t_user SET user_status = ? WHERE user_name = ?", status, username);
     }
 }