From be1cd9e5b30097ca427a9c2b7b054b28854e410a Mon Sep 17 00:00:00 2001
From: Junjie <fallin.jie@qq.com>
Date: 星期三, 11 三月 2026 13:21:36 +0800
Subject: [PATCH] #

---
 src/main/java/com/zy/common/web/AuthController.java |  203 ++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 187 insertions(+), 16 deletions(-)

diff --git a/src/main/java/com/zy/common/web/AuthController.java b/src/main/java/com/zy/common/web/AuthController.java
index cf7f800..89762e9 100644
--- a/src/main/java/com/zy/common/web/AuthController.java
+++ b/src/main/java/com/zy/common/web/AuthController.java
@@ -2,16 +2,18 @@
 
 import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.core.annotations.ManagerAuth;
 import com.core.common.Cools;
 import com.core.common.R;
 import com.core.exception.CoolException;
 import com.zy.common.CodeRes;
+import com.zy.common.auth.MfaLoginTicketManager;
 import com.zy.common.i18n.I18nMessageService;
 import com.zy.common.entity.Parameter;
 import com.zy.common.model.PowerDto;
 import com.zy.common.model.enums.HtmlNavIconType;
+import com.zy.common.utils.MfaTotpUtil;
+import com.zy.common.utils.QrCode;
 import com.zy.common.utils.RandomValidateCodeUtil;
 import com.zy.system.entity.*;
 import com.zy.system.service.*;
@@ -25,6 +27,10 @@
 import org.springframework.web.bind.annotation.RestController;
 
 import jakarta.servlet.http.HttpServletResponse;
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.util.Base64;
 import java.util.*;
 
 /**
@@ -53,6 +59,8 @@
     private LicenseTimer licenseTimer;
     @Autowired
     private I18nMessageService i18nMessageService;
+    @Autowired
+    private MfaLoginTicketManager mfaLoginTicketManager;
 
     @RequestMapping("/login.action")
     @ManagerAuth(value = ManagerAuth.Auth.NONE, memo = "鐧诲綍")
@@ -61,15 +69,16 @@
         if (!licenseTimer.getSystemSupport()){
             return new R(20001, i18nMessageService.getMessage("response.system.licenseExpired"));
         }
+        if (Cools.isEmpty(mobile, password)) {
+            return new R(10003, i18nMessageService.getMessage("response.user.passwordMismatch"));
+        }
         if (mobile.equals("super") && password.equals(Cools.md5(superPwd))) {
             Map<String, Object> res = new HashMap<>();
             res.put("username", mobile);
             res.put("token", Cools.enToken(System.currentTimeMillis() + mobile, superPwd));
             return R.ok(res);
         }
-        QueryWrapper<User> userWrapper = new QueryWrapper<>();
-        userWrapper.eq("mobile", mobile);
-        User user = userService.getOne(userWrapper);
+        User user = userService.getByMobileWithMfa(mobile);
         if (Cools.isEmpty(user)){
             return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
         }
@@ -79,17 +88,41 @@
         if (!user.getPassword().equals(password)){
             return new R(10003, i18nMessageService.getMessage("response.user.passwordMismatch"));
         }
-        String token = Cools.enToken(System.currentTimeMillis() + mobile, user.getPassword());
-        userLoginService.remove(new QueryWrapper<UserLogin>().eq("user_id", user.getId()).eq("system_type", "WCS"));
-        UserLogin userLogin = new UserLogin();
-        userLogin.setUserId(user.getId());
-        userLogin.setToken(token);
-        userLogin.setSystemType("WCS");
-        userLoginService.save(userLogin);
-        Map<String, Object> res = new HashMap<>();
-        res.put("username", user.getUsername());
-        res.put("token", token);
-        return R.ok(res);
+        if (requiresMfa(user)) {
+            Map<String, Object> res = new HashMap<>();
+            res.put("username", user.getUsername());
+            res.put("mfaRequired", true);
+            res.put("mfaTicket", mfaLoginTicketManager.create(user.getId()));
+            return R.ok(res);
+        }
+        return R.ok(buildLoginSuccess(user));
+    }
+
+    @RequestMapping("/login/mfa.action")
+    @ManagerAuth(value = ManagerAuth.Auth.NONE, memo = "MFA鐧诲綍")
+    public R loginMfaAction(String ticket, String code) {
+        Long userId = mfaLoginTicketManager.getUserId(ticket);
+        if (userId == null) {
+            return new R(10004, i18nMessageService.getMessage("response.user.mfaTicketExpired"));
+        }
+        User user = userService.getByIdWithMfa(userId);
+        if (Cools.isEmpty(user)) {
+            mfaLoginTicketManager.remove(ticket);
+            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
+        }
+        if (user.getStatus() != 1) {
+            mfaLoginTicketManager.remove(ticket);
+            return new R(10002, i18nMessageService.getMessage("response.user.disabled"));
+        }
+        if (!requiresMfa(user)) {
+            mfaLoginTicketManager.remove(ticket);
+            return new R(10005, i18nMessageService.getMessage("response.user.mfaNotEnabled"));
+        }
+        if (!MfaTotpUtil.verifyCode(user.getMfaSecret(), code, 1)) {
+            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
+        }
+        mfaLoginTicketManager.remove(ticket);
+        return R.ok(buildLoginSuccess(user));
     }
 
     @RequestMapping("/code/switch.action")
@@ -122,7 +155,85 @@
     @RequestMapping("/user/detail/auth")
     @ManagerAuth
     public R userDetail(){
-        return R.ok(userService.getById(getUserId()));
+        User user = userService.getByIdWithMfa(getUserId());
+        if (Cools.isEmpty(user)) {
+            return R.ok();
+        }
+        return R.ok(buildSafeUserDetail(user));
+    }
+
+    @RequestMapping("/user/mfa/setup/auth")
+    @ManagerAuth
+    public R userMfaSetup() {
+        User user = userService.getByIdWithMfa(getUserId());
+        if (Cools.isEmpty(user)) {
+            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
+        }
+        if (!Integer.valueOf(1).equals(user.getMfaAllow())) {
+            return new R(10007, i18nMessageService.getMessage("response.user.mfaNotAllowed"));
+        }
+        String secret = MfaTotpUtil.generateSecret();
+        String account = !Cools.isEmpty(user.getMobile())
+                ? user.getMobile()
+                : (!Cools.isEmpty(user.getUsername()) ? user.getUsername() : String.valueOf(user.getId()));
+        String otpAuth = MfaTotpUtil.buildOtpAuthUri("WCS", account, secret);
+        Map<String, Object> data = new HashMap<>();
+        data.put("secret", secret);
+        data.put("otpAuth", otpAuth);
+        data.put("qrCode", renderQrCodeDataUri(otpAuth));
+        return R.ok(data);
+    }
+
+    @RequestMapping("/user/mfa/enable/auth")
+    @ManagerAuth
+    @Transactional
+    public R userMfaEnable(String currentPassword, String secret, String code) {
+        User user = userService.getByIdWithMfa(getUserId());
+        if (Cools.isEmpty(user)) {
+            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
+        }
+        if (!Integer.valueOf(1).equals(user.getMfaAllow())) {
+            return new R(10007, i18nMessageService.getMessage("response.user.mfaNotAllowed"));
+        }
+        if (!Cools.eq(user.getPassword(), currentPassword)) {
+            return new R(10008, i18nMessageService.getMessage("response.user.oldPasswordMismatch"));
+        }
+        String normalizedSecret = normalizeSecret(secret);
+        if (Cools.isEmpty(normalizedSecret) || !MfaTotpUtil.verifyCode(normalizedSecret, code, 1)) {
+            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
+        }
+        userService.update(new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<User>()
+                .eq("id", user.getId())
+                .set("mfa_allow", 1)
+                .set("mfa_enabled", 1)
+                .set("mfa_secret", normalizedSecret)
+                .set("mfa_bound_time", new Date()));
+        return R.ok();
+    }
+
+    @RequestMapping("/user/mfa/disable/auth")
+    @ManagerAuth
+    @Transactional
+    public R userMfaDisable(String currentPassword, String code) {
+        User user = userService.getByIdWithMfa(getUserId());
+        if (Cools.isEmpty(user)) {
+            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
+        }
+        if (!requiresMfa(user)) {
+            return new R(10005, i18nMessageService.getMessage("response.user.mfaNotEnabled"));
+        }
+        if (!Cools.eq(user.getPassword(), currentPassword)) {
+            return new R(10008, i18nMessageService.getMessage("response.user.oldPasswordMismatch"));
+        }
+        if (!MfaTotpUtil.verifyCode(user.getMfaSecret(), code, 1)) {
+            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
+        }
+        userService.update(new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<User>()
+                .eq("id", user.getId())
+                .set("mfa_enabled", 0)
+                .set("mfa_secret", null)
+                .set("mfa_bound_time", null));
+        return R.ok();
     }
 
     @RequestMapping("/menu/auth")
@@ -246,6 +357,66 @@
         return R.ok(result);
     }
 
+    private Map<String, Object> buildLoginSuccess(User user) {
+        String token = Cools.enToken(System.currentTimeMillis() + user.getMobile(), user.getPassword());
+        userLoginService.remove(new QueryWrapper<UserLogin>().eq("user_id", user.getId()).eq("system_type", "WCS"));
+        UserLogin userLogin = new UserLogin();
+        userLogin.setUserId(user.getId());
+        userLogin.setToken(token);
+        userLogin.setSystemType("WCS");
+        userLoginService.save(userLogin);
+        Map<String, Object> result = new HashMap<>();
+        result.put("username", user.getUsername());
+        result.put("token", token);
+        result.put("mfaRequired", false);
+        return result;
+    }
+
+    private boolean requiresMfa(User user) {
+        return user != null
+                && Integer.valueOf(1).equals(user.getMfaAllow())
+                && Integer.valueOf(1).equals(user.getMfaEnabled())
+                && !Cools.isEmpty(user.getMfaSecret());
+    }
+
+    private Map<String, Object> buildSafeUserDetail(User user) {
+        Map<String, Object> result = new HashMap<>();
+        result.put("id", user.getId());
+        result.put("roleName", user.getRoleName());
+        result.put("username", user.getUsername());
+        result.put("mobile", user.getMobile());
+        result.put("createTime$", user.getCreateTime$());
+        result.put("mfaAllow", user.getMfaAllow());
+        result.put("mfaAllow$", user.getMfaAllow$());
+        result.put("mfaEnabled", user.getMfaEnabled());
+        result.put("mfaEnabled$", user.getMfaEnabled$());
+        result.put("mfaBoundTime$", user.getMfaBoundTime$());
+        result.put("mfaMaskedSecret", MfaTotpUtil.maskSecret(user.getMfaSecret()));
+        return result;
+    }
+
+    private String renderQrCodeDataUri(String content) {
+        try {
+            BufferedImage image = QrCode.createImg(content, 220);
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+            ImageIO.write(image, "jpg", outputStream);
+            return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
+        } catch (Exception e) {
+            return "";
+        }
+    }
+
+    private String normalizeSecret(String secret) {
+        if (Cools.isEmpty(secret)) {
+            return "";
+        }
+        return String.valueOf(secret)
+                .trim()
+                .replace(" ", "")
+                .replace("-", "")
+                .toUpperCase(Locale.ROOT);
+    }
+
     private String localizeResourceName(Resource resource) {
         return i18nMessageService.resolveResourceText(resource.getName(), resource.getCode(), resource.getId());
     }

--
Gitblit v1.9.1