Compare commits

...

14 Commits

Author SHA1 Message Date
7c84e7fb66 feat: 滑动验证码修改为数字字母验证码 2026-04-19 16:00:13 +08:00
24374d72fe fix(sso): 修复验证码每次返回相同图片的问题
每次调用createCode()重新生成验证码

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:33:30 +08:00
48d5f46c17 refactor(mhzc): 注释components-login.vue滑块验证代码(原代码注释保留)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:19:33 +08:00
1cbffca35b fix(sso): 修复StringUtils.isBlank编译错误
改用cn.hutool.core.util.StrUtil.isBlank()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:07:14 +08:00
5028ec4b8f fix(sso): 修复Bean方法名与字段名冲突
Bean方法名从lineCaptcha改为captchaGenerator,避免与@Resource字段名冲突

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:04:09 +08:00
0d6c3e353a fix(sso): 修复ICaptcha强制转换为CircleCaptcha调用getImage()
ICaptcha接口没有getImage()方法,需要强制转换为CircleCaptcha

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:01:00 +08:00
8a91713bab refactor(mhzc): 短信登录页滑块验证改为图形验证码(原代码注释保留)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:55:37 +08:00
eef27d2aeb refactor(mhzc): 登录页滑块验证改为图形验证码(原代码注释保留)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:53:38 +08:00
0f2efb0b66 feat(mhzc): 新增getCaptcha API
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:51:27 +08:00
57337d9e73 feat(sso): 登录接口改为校验图形验证码
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:50:57 +08:00
460ba0d969 feat(sso): 登录请求新增captchaCode字段
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:50:02 +08:00
122692bc8b feat(sso): 新增获取图形验证码接口
在 VerifyController 中添加 /captcha 接口,用于获取图形验证码。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:36:08 +08:00
1b8168ba10 fix(sso): rename lineCaptchaBean to lineCaptcha
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:30:14 +08:00
3fa6747c10 feat(sso): add captcha methods to VerifyService interface
Add getCaptcha and checkCaptcha methods for graphic captcha support
in login verification flow.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 15:26:01 +08:00
12 changed files with 1102 additions and 336 deletions

View File

@ -0,0 +1,688 @@
# 登录图形验证码重构实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan.
**Goal:** 将登录页滑块验证改为数字+字母图形验证码,前端注释保留原滑块代码不删除。
**Architecture:**
- 后端新增 `/verify/captcha` 接口生成验证码图片(base64)和uuid存入Redis
- 登录接口新增 `captchaCode` 参数与uuid联合校验
- 前端新增验证码图片展示和输入框,注释掉滑块相关代码
**Tech Stack:** Hutool CaptchaUtil (已有 hutool 依赖), Redis, Vue.js
---
## 文件改动总览
| 文件 | 操作 |
|------|------|
| `VerifyService.java` | 修改:新增 `getCaptcha()``checkCaptcha()` 接口 |
| `VerifyServiceImpl.java` | 修改:实现图形验证码生成和校验逻辑 |
| `VerifyController.java` | 修改:新增 `/verify/captcha` 接口 |
| `AuthLoginReqVO.java` | 修改:新增 `captchaCode` 字段 |
| `AuthServiceImpl.java` | 修改:`login()` 方法新增验证码校验 |
| `login.js` | 修改:新增 `getCaptcha()` API |
| `passwordlogin.vue` | 修改:注释滑块,新增验证码组件 |
| `phonelogin.vue` | 修改:注释滑块,新增验证码组件 |
---
## Task 1: 后端 - VerifyService 接口定义
**Files:**
- Modify: `txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/service/verify/VerifyService.java`
**Steps:**
- [ ] Step 1: 在 `VerifyService.java` 中新增两个接口方法定义
```java
package com.css.txw.sso.service.verify;
import com.css.ggzc.framework.common.pojo.CommonResult;
public interface VerifyService {
// === 原有方法保留 ===
CommonResult<String> getVerifyToken(String remoteId);
Boolean checkVerifyToken(String verifyToken);
// === 新增图形验证码方法 ===
/**
* 生成图形验证码返回验证码图片base64和uuid
* @param remoteId IP+UserAgent
* @return { uuid, imageBase64 }
*/
CommonResult<Map<String, String>> getCaptcha(String remoteId);
/**
* 校验图形验证码
* @param uuid 验证码唯一标识
* @param code 用户输入的验证码
* @return true=校验通过
*/
Boolean checkCaptcha(String uuid, String code);
}
```
---
## Task 2: 后端 - VerifyServiceImpl 实现
**Files:**
- Modify: `txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/service/verify/VerifyServiceImpl.java`
**Steps:**
- [ ] Step 1: 添加必要的 import
```java
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.img.Img;
import cn.hutool.core.img QRCodeUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
```
- [ ] Step 2: 新增 Captcha 生成器 Bean (在类上添加)
```java
@Bean
public ICaptcha lineCaptcha() {
// 自定义验证码内容为4位数字+字母
RandomGenerator randomGenerator = new RandomGenerator("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 4);
// 使用 hutool 的 CircleCaptcha验证码图片 120x40带干扰线
cn.hutool.captcha.CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 40, 4, 20);
captcha.setGenerator(randomGenerator);
return captcha;
}
```
- [ ] Step 3: 实现 `getCaptcha` 方法(在类中添加)
```java
@Resource
private ICaptcha lineCaptcha;
@Override
public CommonResult<Map<String, String>> getCaptcha(String remoteId) {
// 生成验证码内容
String code = lineCaptcha.getCode();
String uuid = IdUtil.fastSimpleUUID();
// 生成图片 base64
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(lineCaptcha.getImage(), "png", baos);
} catch (IOException e) {
throw new RuntimeException("生成验证码图片失败", e);
}
String imageBase64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
// 存入 Rediskey = captcha:{uuid}, value = 验证码内容, TTL = 5分钟
stringRedisTemplate.opsForValue().set(
formatCaptchaKey(uuid),
code.toLowerCase(), // 忽略大小写
5,
TimeUnit.MINUTES
);
Map<String, String> result = new HashMap<>();
result.put("uuid", uuid);
result.put("imageBase64", imageBase64);
return CommonResult.success(result);
}
```
- [ ] Step 4: 实现 `checkCaptcha` 方法
```java
@Override
public Boolean checkCaptcha(String uuid, String code) {
if (!this.ssoProperties.isLoginCaptcha()) {
return true;
}
if (StringUtils.isBlank(uuid) || StringUtils.isBlank(code)) {
return false;
}
String key = formatCaptchaKey(uuid);
String cachedCode = stringRedisTemplate.opsForValue().get(key);
if (cachedCode == null) {
return false;
}
// 校验成功后删除验证码(一次性)
stringRedisTemplate.delete(key);
return cachedCode.equalsIgnoreCase(code);
}
```
- [ ] Step 5: 添加 format 方法
```java
private static String formatCaptchaKey(String uuid) {
return "captcha:" + uuid;
}
```
- [ ] Step 6: 提交
```bash
git add txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/service/verify/VerifyServiceImpl.java
git commit -m "feat(sso): 实现图形验证码生成和校验逻辑"
```
---
## Task 3: 后端 - VerifyController 新增接口
**Files:**
- Modify: `txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/controller/verify/VerifyController.java`
**Steps:**
- [ ] Step 1: 新增 `/verify/captcha` 接口方法(在类中添加)
```java
@Operation(summary = "获取图形验证码")
@PermitAll
@PostMapping("/captcha")
public CommonResult<Map<String, String>> getCaptcha(HttpServletRequest request) {
final String remoteId = getRemoteId(request);
return verifyService.getCaptcha(remoteId);
}
```
- [ ] Step 2: 添加 import
```java
import java.util.Map;
```
- [ ] Step 3: 提交
```bash
git add txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/controller/verify/VerifyController.java
git commit -m "feat(sso): 新增图形验证码获取接口 /verify/captcha"
```
---
## Task 4: 后端 - AuthLoginReqVO 新增字段
**Files:**
- Modify: `txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/pojo/vo/AuthLoginReqVO.java`
**Steps:**
- [ ] Step 1: 在 `captchaVerification` 字段后新增 `captchaCode` 字段
```java
@Schema(description = "图形验证码uuid原有字段复用为验证码标识")
private String captchaVerification;
@Schema(description = "用户输入的图形验证码", requiredMode = Schema.RequiredMode.REQUIRED,
example = "Kp7m")
@JsonProperty("CaptchaCode")
private String captchaCode;
```
- [ ] Step 2: 提交
```bash
git add txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/pojo/vo/AuthLoginReqVO.java
git commit -m "feat(sso): 登录请求新增captchaCode字段"
```
---
## Task 5: 后端 - AuthServiceImpl 登录校验改动
**Files:**
- Modify: `txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/service/auth/impl/AuthServiceImpl.java`
**Steps:**
- [ ] Step 1: 修改 `login()` 方法,将原来的 `checkVerifyToken` 替换为新的 `checkCaptcha` 校验
找到原始代码约在114-118行
```java
@Override
public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
final Boolean checked = verifyService.checkVerifyToken(reqVO.getCaptchaVerification());
if (!checked) {
throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR);
}
// 使用账号密码,进行登录
YhxxbDTO user = authenticate(reqVO.getUsername(), reqVO.getPassword());
return createTokenAfterLoginSuccess(user.getYhUuid());
}
```
替换为:
```java
@Override
public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
// 校验图形验证码
final Boolean checked = verifyService.checkCaptcha(
reqVO.getCaptchaVerification(),
reqVO.getCaptchaCode()
);
if (!checked) {
throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR);
}
// 使用账号密码,进行登录
YhxxbDTO user = authenticate(reqVO.getUsername(), reqVO.getPassword());
return createTokenAfterLoginSuccess(user.getYhUuid());
}
```
- [ ] Step 2: 提交
```bash
git add txw-sso/txw-sso-service-biz/src/main/java/com/css/txw/sso/service/auth/impl/AuthServiceImpl.java
git commit -m "feat(sso): 登录接口改为校验图形验证码"
```
---
## Task 6: 前端 - login.js 新增 API
**Files:**
- Modify: `txw-mhzc-web/src/pages/index/api/login.js`
**Steps:**
- [ ] Step 1: 在文件末尾约195行之后新增 `getCaptcha` 方法
```javascript
// 获取图形验证码
export function getCaptcha() {
return fetchSso({
url: `${basurl}/sso/verify/captcha`,
method: 'post',
});
}
```
- [ ] Step 2: 提交
```bash
git add txw-mhzc-web/src/pages/index/api/login.js
git commit -m "feat(mhzc): 新增getCaptcha API"
```
---
## Task 7: 前端 - passwordlogin.vue 重构
**Files:**
- Modify: `txw-mhzc-web/src/pages/index/views/login/components/login/passwordlogin.vue`
**Steps:**
- [ ] Step 1: 注释掉 `import { getVerify }` 并改为 `import { getCaptcha }`约68行
原始:
```javascript
import { getVerify } from '@/pages/index/api/login';
```
改为:
```javascript
// import { getVerify } from '@/pages/index/api/login'; // 滑块验证已注释
import { getCaptcha } from '@/pages/index/api/login';
```
- [ ] Step 2: 在 `data()``loginForm` 中新增 `captchaCode``captchaUuid` 字段并注释掉滑块相关数据约83-100行
原始 `data()` 返回:
```javascript
return {
beginClientX: 0,
mouseMoveState: false,
maxWidth: '',
confirmWords: '请按住滑块,拖动到最右边',
confirmSuccess: false,
width: 350,
height: 42,
textSize: '18px',
FORM_RULES,
loginForm: {
loginType: 'password',
username: '',
password: '',
captchaVerification: '',
mobile: '',
mobileCode: '',
rememberMe: false,
},
countDown: 0,
intervalTimer: null,
};
```
注释后:
```javascript
// === 滑块验证相关数据(已注释,保留以便回滚)===
// beginClientX: 0,
// mouseMoveState: false,
// maxWidth: '',
// confirmWords: '请按住滑块,拖动到最右边',
// confirmSuccess: false,
// width: 350,
// height: 42,
// textSize: '18px',
// === 滑块验证相关数据 end ===
return {
// captchaVerification 改为存储 uuid
captchaUuid: '',
captchaImage: '',
captchaCode: '',
FORM_RULES,
loginForm: {
loginType: 'password',
username: '',
password: '',
captchaVerification: '', // 仍然保留登录时传uuid
mobile: '',
mobileCode: '',
rememberMe: false,
},
countDown: 0,
intervalTimer: null,
};
```
- [ ] Step 3: 注释掉滑块相关方法(`mouseDown`, `successFunction`, `mouseMoveFn`, `moseUpFn`约216-260行
原始方法注释掉后改为:
```javascript
// === 滑块验证方法(已注释,保留以便回滚) ===
// mousedown 事件
// mouseDown(e) {
// if (!this.confirmSuccess) {
// e.preventDefault && e.preventDefault();
// this.mouseMoveState = true;
// this.beginClientX = e.clientX;
// }
// },
// 验证成功函数
// successFunction() {
// getVerify().then((res) => {
// this.loginForm.captchaVerification = res.data;
// this.confirmSuccess = true;
// this.confirmWords = '验证通过';
// });
// // ... (移除 mousemove/mouseup 监听器代码)
// },
// mousemove事件
// mouseMoveFn(e) {
// if (this.mouseMoveState) {
// const width = e.clientX - this.beginClientX;
// if (width > 0 && width <= this.maxWidth) {
// document.getElementsByClassName('handler')[0].style.left = `${width}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
// } else if (width > this.maxWidth) {
// this.successFunction();
// }
// }
// },
// mouseup事件
// moseUpFn(e) {
// this.mouseMoveState = false;
// const width = e.clientX - this.beginClientX;
// if (width < this.maxWidth) {
// document.getElementsByClassName('handler')[0].style.left = `${0}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
// }
// },
// reSetSlider() {
// this.confirmSuccess = false;
// ...
// },
// === 滑块验证方法 end ===
// 新增:刷新验证码
refreshCaptcha() {
getCaptcha().then((res) => {
this.captchaUuid = res.data.uuid;
this.captchaImage = res.data.imageBase64;
this.loginForm.captchaVerification = res.data.uuid;
this.loginForm.captchaCode = '';
});
},
```
- [ ] Step 4: 在 `mounted()` 中注释掉滑块初始化代码新增验证码初始化约278-284行
原始:
```javascript
mounted() {
this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
}
```
改为:
```javascript
mounted() {
// === 滑块初始化(已注释) ===
// this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
// document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
// 新增:初始化图形验证码
this.refreshCaptcha();
}
```
- [ ] Step 5: 在 `beforeDestroy()` 中注释掉清理代码约105-107行
原始:
```javascript
beforeDestroy() {
clearInterval(this.intervalTimer);
}
```
改为:
```javascript
beforeDestroy() {
clearInterval(this.intervalTimer);
// === 滑块清理(已注释) ===
// document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
}
```
- [ ] Step 6: 修改 `onSubmit` 方法中的校验逻辑约125-131行
原始:
```javascript
if (!this.confirmSuccess) {
MessagePlugin.info({
content: '请先完成滑块验证',
duration: 1000,
});
return;
}
```
改为:
```javascript
if (!this.captchaUuid) {
MessagePlugin.info({
content: '请先获取验证码',
duration: 1000,
});
return;
}
if (!this.loginForm.captchaCode || this.loginForm.captchaCode.length !== 4) {
MessagePlugin.info({
content: '请输入4位验证码',
duration: 1000,
});
return;
}
```
- [ ] Step 7: 替换模板中的滑块区域为验证码组件约36-48行
原始:
```html
<t-form-item name="captchaVerification" user-select:none>
<div class="drag" ref="dragDiv">
<div class="drag_bg"></div>
<div class="drag_text">{{ confirmWords }}</div>
<div
ref="moveDiv"
@mousedown="mouseDown($event)"
:class="{ handler_ok_bg: confirmSuccess }"
class="handler handler_bg"
style="position: absolute; top: 0; left: 0"
></div>
</div>
</t-form-item>
```
改为:
```html
<!-- 滑块验证区域(已注释,保留以便回滚) -->
<!--
<t-form-item name="captchaVerification" user-select:none>
<div class="drag" ref="dragDiv">
...
</div>
</t-form-item>
-->
<!-- 新增:图形验证码 -->
<t-form-item name="captchaCode">
<div class="captcha-wrapper">
<img
v-if="captchaImage"
:src="captchaImage"
@click="refreshCaptcha"
class="captcha-img"
alt="验证码"
/>
<t-input
v-model="loginForm.captchaCode"
placeholder="请输入验证码"
maxlength="4"
style="width: 120px"
@enterkey="onSubmit"
/>
<span class="captcha-refresh" @click="refreshCaptcha">刷新</span>
</div>
</t-form-item>
```
- [ ] Step 8: 新增验证码相关样式
`<style>` 末尾约349行后添加
```css
/* === 滑块验证样式(已注释,保留以便回滚) ===
.drag { ... }
.handler { ... }
...
*/
/* 新增:图形验证码样式 */
.captcha-wrapper {
display: flex;
align-items: center;
gap: 12px;
width: 350px;
height: 40px;
}
.captcha-img {
width: 120px;
height: 40px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #ccc;
}
.captcha-refresh {
color: #0052d9;
cursor: pointer;
font-size: 14px;
user-select: none;
}
.captcha-refresh:hover {
text-decoration: underline;
}
```
- [ ] Step 9: 提交
```bash
git add txw-mhzc-web/src/pages/index/views/login/components/login/passwordlogin.vue
git commit -m "refactor(mhzc): 登录页滑块验证改为图形验证码(原代码注释保留)"
```
---
## Task 8: 前端 - phonelogin.vue 重构
**Files:**
- Modify: `txw-mhzc-web/src/pages/index/views/login/components/login/phonelogin.vue`
**Steps:**
- 参照 Task 7 对 `phonelogin.vue` 进行相同改动(注释滑块,新增图形验证码)
**主要改动点:**
1. import `getCaptcha` 替代 `getVerify`
2. 注释 `confirmSuccess` 相关逻辑
3. `onSubmit` 中验证码非空校验
4. `handleCounter`(发送短信前)验证码检查
5. 模板替换 `.drag` 区域
6. `mounted()` 中初始化验证码
7. 样式新增 `.captcha-wrapper`
- [ ] Step 1: 执行 phonelogin.vue 的上述改动
- [ ] Step 2: 提交
```bash
git add txw-mhzc-web/src/pages/index/views/login/components/login/phonelogin.vue
git commit -m "refactor(mhzc): 短信登录页滑块验证改为图形验证码(原代码注释保留)"
```
---
## Task 9: 整体测试
**Steps:**
- [ ] Step 1: 启动 SSO 服务和前端项目
- [ ] Step 2: 访问登录页,验证验证码图片正确显示
- [ ] Step 3: 点击刷新,验证验证码更换
- [ ] Step 4: 输入正确账号密码 + 正确验证码 → 登录成功
- [ ] Step 5: 输入错误验证码 → 登录失败,提示"验证码错误"
- [ ] Step 6: 验证码5分钟过期后使用 → 提示"验证码已过期"
- [ ] Step 7: 短信登录流程测试(获取验证码 → 填入 → 登录)
- [ ] Step 8: 确认滑块代码注释后页面正常,功能不受影响
---
## Task 10: 提交全部改动
```bash
git add -A
git status
```

View File

@ -10,11 +10,12 @@ const headers = {
// let basurl = ''
const basurl = '';
// 登录方法
export function login(username, password, captchaVerification, socialType, socialCode, socialState) {
export function login(username, password, captchaVerification, captchaCode, socialType, socialCode, socialState) {
const data = {
username,
password,
captchaVerification,
captchaCode,
// 社交相关
socialType,
socialCode,
@ -129,6 +130,14 @@ export function Getqrcode() {
method: 'post',
});
}
// 获取图形验证码
export function getCaptcha() {
return fetchSso({
url: `${basurl}/sso/verify/captcha`,
method: 'post',
});
}
//获取登录回调响应结果
export function backresultlogin(params) {
return fetchSso({

View File

@ -36,11 +36,12 @@ const user = {
const username = userInfo.username.trim();
const { password } = userInfo;
const { captchaVerification } = userInfo;
const { captchaCode } = userInfo;
const { socialCode } = userInfo;
const { socialState } = userInfo;
const { socialType } = userInfo;
return new Promise((resolve, reject) => {
login(username, password, captchaVerification, socialType, socialCode, socialState)
login(username, password, captchaVerification, captchaCode, socialType, socialCode, socialState)
.then((res) => {
resolve();
})

View File

@ -33,7 +33,7 @@
import { removePassword, removeRememberMe, removeUsername } from '@/utils/auth';
import { UserIcon, LockOnIcon } from 'tdesign-icons-vue';
import { MessagePlugin } from 'tdesign-vue';
import { getVerify } from '@/pages/index/api/login';
// import { getVerify } from '@/pages/index/api/login'; //
import Passwordlogin from './login/passwordlogin.vue';
import Phonelogin from './login/phonelogin.vue';
@ -52,14 +52,17 @@ export default {
},
data() {
return {
beginClientX: 0 /* 距离屏幕左端距离 */,
mouseMoveState: false /* 触发拖动状态 判断 */,
maxWidth: '' /* 拖动最大宽度,依据滑块宽度算出来的 */,
confirmWords: '请按住滑块,拖动到最右边' /* 滑块文字 */,
confirmSuccess: false /* 验证成功判断 */,
width: 350,
height: 42,
textSize: '18px',
// === 便 ===
// beginClientX: 0,
// mouseMoveState: false,
// maxWidth: '',
// confirmWords: '',
// confirmSuccess: false,
// width: 350,
// height: 42,
// textSize: '18px',
// === end ===
FORM_RULES,
loginForm: {
loginType: 'password',
@ -94,13 +97,14 @@ export default {
});
return;
}
if (!this.confirmSuccess) {
MessagePlugin.info({
content: '请先完成滑块验证',
duration: 1000,
});
return;
}
// === ===
// if (!this.confirmSuccess) {
// MessagePlugin.info({
// content: '',
// duration: 1000,
// });
// return;
// }
} else {
if (!this.loginForm.mobile) {
MessagePlugin.info({
@ -152,13 +156,14 @@ export default {
});
return;
}
if (!this.confirmSuccess) {
MessagePlugin.info({
content: '请先完成滑块验证',
duration: 1000,
});
return;
}
// === ===
// if (!this.confirmSuccess) {
// MessagePlugin.info({
// content: '',
// duration: 1000,
// });
// return;
// }
let params = {
captchaVerification: this.loginForm.captchaVerification,
sjhm1: this.loginForm.dlzh,
@ -186,75 +191,21 @@ export default {
});
});
},
// === 便 ===
// mousedown
mouseDown(e) {
if (!this.confirmSuccess) {
e.preventDefault && e.preventDefault(); //
this.mouseMoveState = true;
this.beginClientX = e.clientX;
}
},
//
successFunction() {
getVerify().then((res) => {
this.loginForm.captchaVerification = res.data;
this.confirmSuccess = true;
this.confirmWords = '验证通过';
});
if (window.addEventListener) {
document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
} else {
document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {});
}
document.getElementsByClassName('drag_text')[0].style.color = '#fff';
document.getElementsByClassName('handler')[0].style.left = `${this.maxWidth}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${this.maxWidth}px`;
},
// mousemove
mouseMoveFn(e) {
if (this.mouseMoveState) {
const width = e.clientX - this.beginClientX;
if (width > 0 && width <= this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${width}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
} else if (width > this.maxWidth) {
this.successFunction();
}
}
},
// mouseup
moseUpFn(e) {
this.mouseMoveState = false;
const width = e.clientX - this.beginClientX;
if (width < this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
}
},
reSet() {
this.formData.sfzhm = '';
this.formData.xm = '';
this.reSetSlider();
},
reSetSlider() {
this.confirmSuccess = false;
this.mouseMoveState = false;
this.cxBtnDisabled = true;
this.confirmWords = '请按住滑块,拖动到最右边';
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
document.getElementsByClassName('drag_text')[0].style.color = 'black';
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
},
// mouseDown(e) { ... },
// successFunction() { ... },
// mouseMoveFn(e) { ... },
// moseUpFn(e) { ... },
// reSet() { ... },
// reSetSlider() { ... },
// === end ===
},
mounted() {
//
this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
//
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
// === ===
// this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
// document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
},
};
</script>
@ -271,48 +222,15 @@ export default {
padding: 15px;
}
}
.drag {
position: relative;
width: 350px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: #e8e8e8;
border: 1px solid #ccc;
border-radius: 4px;
}
.handler {
width: 40px;
height: 38px;
cursor: move;
border: 1px solid #ccc;
border-radius: 4px;
}
.handler_bg {
background: #fff
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo0ZDhlNWY5My05NmI0LTRlNWQtOGFjYi03ZTY4OGYyMTU2ZTYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTEyNTVEMURGMkVFMTFFNEI5NDBCMjQ2M0ExMDQ1OUYiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTEyNTVEMUNGMkVFMTFFNEI5NDBCMjQ2M0ExMDQ1OUYiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo2MTc5NzNmZS02OTQxLTQyOTYtYTIwNi02NDI2YTNkOWU5YmUiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NGQ4ZTVmOTMtOTZiNC00ZTVkLThhY2ItN2U2ODhmMjE1NmU2Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+YiRG4AAAALFJREFUeNpi/P//PwMlgImBQkA9A+bOnfsIiBOxKcInh+yCaCDuByoswaIOpxwjciACFegBqZ1AvBSIS5OTk/8TkmNEjwWgQiUgtQuIjwAxUF3yX3xyGIEIFLwHpKyAWB+I1xGSwxULIGf9A7mQkBwTlhBXAFLHgPgqEAcTkmNCU6AL9d8WII4HOvk3ITkWJAXWUMlOoGQHmsE45ViQ2KuBuASoYC4Wf+OUYxz6mQkgwAAN9mIrUReCXgAAAABJRU5ErkJggg==')
no-repeat center;
}
.handler_ok_bg {
background: #fff
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo0ZDhlNWY5My05NmI0LTRlNWQtOGFjYi03ZTY4OGYyMTU2ZTYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDlBRDI3NjVGMkQ2MTFFNEI5NDBCMjQ2M0ExMDQ1OUYiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDlBRDI3NjRGMkQ2MTFFNEI5NDBCMjQ2M0ExMDQ1OUYiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDphNWEzMWNhMC1hYmViLTQxNWEtYTEwZS04Y2U5NzRlN2Q4YTEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NGQ4ZTVmOTMtOTZiNC00ZTVkLThhY2ItN2U2ODhmMjE1NmU2Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+k+sHwwAAASZJREFUeNpi/P//PwMyKD8uZw+kUoDYEYgloMIvgHg/EM/ptHx0EFk9I8wAoEZ+IDUPiIMY8IN1QJwENOgj3ACo5gNAbMBAHLgAxA4gQ5igAnNJ0MwAVTsX7IKyY7L2UNuJAf+AmAmJ78AEDTBiwGYg5gbifCSxFCZoaBMCy4A4GOjnH0D6DpK4IxNSVIHAfSDOAeLraJrjgJp/AwPbHMhejiQnwYRmUzNQ4VQgDQqXK0ia/0I17wJiPmQNTNBEAgMlQIWiQA2vgWw7QppBekGxsAjIiEUSBNnsBDWEAY9mEFgMMgBk00E0iZtA7AHEctDQ58MRuA6wlLgGFMoMpIG1QFeGwAIxGZo8GUhIysmwQGSAZgwHaEZhICIzOaBkJkqyM0CAAQDGx279Jf50AAAAAABJRU5ErkJggg==')
no-repeat center;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.drag_bg {
width: 0;
height: 38px;
background-color: #7ac23c;
border-radius: 4px 0 0 4px;
}
.drag_text {
position: absolute;
top: 0;
width: 100%;
text-align: center;
user-select: none;
}
/* === 便 ===
.drag { ... }
.handler { ... }
.handler_bg { ... }
.handler_ok_bg { ... }
.drag_bg { ... }
.drag_text { ... }
=== 滑块验证样式 end */
.login-box {
margin-left: 50%;
transform: translateX(-50%);

View File

@ -33,6 +33,8 @@
</template>
</t-input>
</t-form-item>
<!-- 滑块验证区域已注释保留以便回滚 -->
<!--
<t-form-item name="captchaVerification" user-select:none>
<div class="drag" ref="dragDiv">
<div class="drag_bg"></div>
@ -46,6 +48,27 @@
></div>
</div>
</t-form-item>
-->
<!-- 新增图形验证码 -->
<t-form-item name="captchaCode">
<div class="captcha-wrapper">
<t-input
v-model="loginForm.captchaCode"
placeholder="请输入验证码"
:maxlength="4"
size="large"
@enterkey="onSubmit"
/>
<img
v-if="captchaImage"
:src="captchaImage"
@click="refreshCaptcha"
class="captcha-img"
alt="验证码"
/>
</div>
</t-form-item>
</div>
<!-- 短信验证码登录 -->
@ -65,7 +88,8 @@
import { removePassword, removeRememberMe, removeUsername } from '@/utils/auth';
import { UserIcon, LockOnIcon } from 'tdesign-icons-vue';
import { MessagePlugin } from 'tdesign-vue';
import { getVerify } from '@/pages/index/api/login';
// import { getVerify } from '@/pages/index/api/login'; //
import { getCaptcha } from '@/pages/index/api/login';
const FORM_RULES = {
mobile: [{ required: true, message: '手机号必填', type: 'error' }],
@ -80,14 +104,21 @@ export default {
},
data() {
return {
beginClientX: 0 /* 距离屏幕左端距离 */,
mouseMoveState: false /* 触发拖动状态 判断 */,
maxWidth: '' /* 拖动最大宽度,依据滑块宽度算出来的 */,
confirmWords: '请按住滑块,拖动到最右边' /* 滑块文字 */,
confirmSuccess: false /* 验证成功判断 */,
width: 350,
height: 42,
textSize: '18px',
// === 便 ===
// beginClientX: 0,
// mouseMoveState: false,
// maxWidth: '',
// confirmWords: '',
// confirmSuccess: false,
// width: 350,
// height: 42,
// textSize: '18px',
// === end ===
//
captchaUuid: '',
captchaImage: '',
FORM_RULES,
loginForm: {
loginType: 'password',
@ -96,6 +127,7 @@ export default {
captchaVerification: '',
mobile: '',
mobileCode: '',
captchaCode: '',
rememberMe: false,
},
countDown: 0,
@ -122,9 +154,16 @@ export default {
});
return;
}
if (!this.confirmSuccess) {
if (!this.captchaUuid) {
MessagePlugin.info({
content: '请先完成滑块验证',
content: '请先获取验证码',
duration: 1000,
});
return;
}
if (!this.loginForm.captchaCode || this.loginForm.captchaCode.length !== 4) {
MessagePlugin.info({
content: '请输入4位验证码',
duration: 1000,
});
return;
@ -212,75 +251,89 @@ export default {
});
})
},
// === 便 ===
// mousedown
mouseDown(e) {
if (!this.confirmSuccess) {
e.preventDefault && e.preventDefault(); //
this.mouseMoveState = true;
this.beginClientX = e.clientX;
}
},
// mouseDown(e) {
// if (!this.confirmSuccess) {
// e.preventDefault && e.preventDefault();
// this.mouseMoveState = true;
// this.beginClientX = e.clientX;
// }
// },
//
successFunction() {
getVerify().then((res) => {
this.loginForm.captchaVerification = res.data;
this.confirmSuccess = true;
this.confirmWords = '验证通过';
});
if (window.addEventListener) {
document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
} else {
document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {});
}
document.getElementsByClassName('drag_text')[0].style.color = '#fff';
document.getElementsByClassName('handler')[0].style.left = `${this.maxWidth}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${this.maxWidth}px`;
},
// successFunction() {
// getVerify().then((res) => {
// this.loginForm.captchaVerification = res.data;
// this.confirmSuccess = true;
// this.confirmWords = '';
// });
// if (window.addEventListener) {
// document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
// } else {
// document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {});
// }
// document.getElementsByClassName('drag_text')[0].style.color = '#fff';
// document.getElementsByClassName('handler')[0].style.left = `${this.maxWidth}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${this.maxWidth}px`;
// },
// mousemove
mouseMoveFn(e) {
if (this.mouseMoveState) {
const width = e.clientX - this.beginClientX;
if (width > 0 && width <= this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${width}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
} else if (width > this.maxWidth) {
this.successFunction();
}
}
},
// mouseMoveFn(e) {
// if (this.mouseMoveState) {
// const width = e.clientX - this.beginClientX;
// if (width > 0 && width <= this.maxWidth) {
// document.getElementsByClassName('handler')[0].style.left = `${width}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
// } else if (width > this.maxWidth) {
// this.successFunction();
// }
// }
// },
// mouseup
moseUpFn(e) {
this.mouseMoveState = false;
const width = e.clientX - this.beginClientX;
if (width < this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
}
},
reSet() {
this.formData.sfzhm = '';
this.formData.xm = '';
this.reSetSlider();
},
reSetSlider() {
this.confirmSuccess = false;
this.mouseMoveState = false;
this.cxBtnDisabled = true;
this.confirmWords = '请按住滑块,拖动到最右边';
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
document.getElementsByClassName('drag_text')[0].style.color = 'black';
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
// moseUpFn(e) {
// this.mouseMoveState = false;
// const width = e.clientX - this.beginClientX;
// if (width < this.maxWidth) {
// document.getElementsByClassName('handler')[0].style.left = `${0}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
// }
// },
// reSet() {
// this.formData.sfzhm = '';
// this.formData.xm = '';
// this.reSetSlider();
// },
// reSetSlider() {
// this.confirmSuccess = false;
// this.mouseMoveState = false;
// this.cxBtnDisabled = true;
// this.confirmWords = '';
// document.getElementsByClassName('handler')[0].style.left = `${0}px`;
// document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
// document.getElementsByClassName('drag_text')[0].style.color = 'black';
// document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
// },
// === end ===
//
refreshCaptcha() {
getCaptcha().then((res) => {
this.captchaUuid = res.data.uuid;
this.captchaImage = res.data.imageBase64;
this.loginForm.captchaVerification = res.data.uuid;
this.loginForm.captchaCode = '';
});
},
},
mounted() {
//
this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
//
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
// === ===
// this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
// document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
// document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
//
this.refreshCaptcha();
},
};
</script>
@ -346,4 +399,38 @@ export default {
.btn-container {
margin-top: 16px;
}
/* === 便 ===
.drag { ... }
.handler { ... }
.handler_bg { ... }
.handler_ok_bg { ... }
.drag_bg { ... }
.drag_text { ... }
*/
/* 新增:图形验证码样式 */
.captcha-wrapper {
display: flex;
align-items: center;
gap: 12px;
width: 350px;
height: 40px;
}
.captcha-img {
width: 120px;
height: 40px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #ccc;
}
.captcha-refresh {
color: #0052d9;
cursor: pointer;
font-size: 14px;
user-select: none;
}
.captcha-refresh:hover {
text-decoration: underline;
}
</style>

View File

@ -21,33 +21,35 @@
</t-input>
</t-form-item>
<t-form-item class="verification-code" name="sms">
<t-input v-model="loginForm.sms" size="large" placeholder="请输入验证码" key="verifyCode" />
<t-input v-model="loginForm.sms" size="large" placeholder="请输入短信验证码" key="verifyCode" />
<t-button :disabled="countDown > 0" @click="handleCounter">
{{ countDown === 0 ? '发送验证码' : `${countDown}秒后可重发` }}
</t-button>
</t-form-item>
<!-- 滑块验证区域已注释保留以便回滚 -->
<!--
<t-form-item name="captchaVerification" user-select:none>
<div class="drag" ref="dragDiv" v-if="iscxhk">
<div class="drag_bg"></div>
<div class="drag_text">{{ confirmWords }}</div>
<div
ref="moveDiv"
@mousedown="mouseDown($event)"
:class="{ handler_ok_bg: confirmSuccess }"
class="handler handler_bg"
style="position: absolute; top: 0; left: 0"
></div>
</div>
<div class="drag" ref="dragDiv" v-else>
<div class="drag_bg"></div>
<div class="drag_text">{{ confirmWords }}</div>
<div
ref="moveDiv"
@mousedown="mouseDown($event)"
:class="{ handler_ok_bg: confirmSuccess }"
class="handler handler_bg"
style="position: absolute; top: 0; left: 0"
></div>
<div class="drag" ref="dragDiv" v-if="iscxhk">...</div>
<div class="drag" ref="dragDiv" v-else>...</div>
</t-form-item>
-->
<!-- 新增图形验证码 -->
<t-form-item name="captchaCode">
<div class="captcha-wrapper">
<t-input
v-model="loginForm.captchaCode"
placeholder="请输入验证码"
:maxlength="4"
size="large"
/>
<img
v-if="captchaImage"
:src="captchaImage"
@click="refreshCaptcha"
class="captcha-img"
alt="验证码"
/>
</div>
</t-form-item>
</div>
@ -67,7 +69,8 @@
import { removePassword, removeRememberMe, removeUsername } from '@/utils/auth';
import { UserIcon, LockOnIcon } from 'tdesign-icons-vue';
import { MessagePlugin } from 'tdesign-vue';
import { getVerify,loginBySMS,sendMsg } from '@/pages/index/api/login';
// import { getVerify, loginBySMS, sendMsg } from '@/pages/index/api/login'; //
import { getCaptcha, loginBySMS, sendMsg } from '@/pages/index/api/login';
const FORM_RULES = {
sjhm: [{ required: true, message: '手机号必填', type: 'error' }],
@ -80,28 +83,36 @@ export default {
},
data() {
return {
beginClientX: 0 /* 距离屏幕左端距离 */,
mouseMoveState: false /* 触发拖动状态 判断 */,
maxWidth: '' /* 拖动最大宽度,依据滑块宽度算出来的 */,
confirmWords: '请按住滑块,拖动到最右边' /* 滑块文字 */,
confirmSuccess: false /* 验证成功判断 */,
width: 350,
height: 42,
textSize: '18px',
// === 便 ===
// beginClientX: 0,
// mouseMoveState: false,
// maxWidth: '',
// confirmWords: '',
// confirmSuccess: false,
// width: 350,
// height: 42,
// textSize: '18px',
// isCounting: false,
// iscxhk: false,
// === end ===
//
captchaUuid: '',
captchaImage: '',
FORM_RULES,
loginForm: {
loginType: 'password',
username: '',
password: '',
captchaVerification: '',
captchaCode: '',
sjhm: '',
sms: '',
rememberMe: false,
},
countDown: 0,
intervalTimer: null,
isCounting: false, //
iscxhk:false,
};
},
beforeDestroy() {
@ -143,18 +154,8 @@ export default {
})
.catch((error) => {
console.log('22222');
//
// if (this.isCounting) {
// this.stopAndResetTimer();
// this.reSetSlider();
// }
if (this.isCounting) {
this.stopAndResetTimer();
}
return;
// if (error === 1004003) {
// this.reSetSlider();
// }
this.stopAndResetTimer();
return;
});
},
handleCounter() {
@ -165,9 +166,9 @@ handleCounter() {
});
return;
}
if (!this.confirmSuccess) {
if (!this.captchaUuid) {
MessagePlugin.info({
content: '请先完成滑块验证',
content: '请先获取验证码',
duration: 1000,
});
return;
@ -210,94 +211,39 @@ handleCounter() {
//
stopAndResetTimer() {
clearInterval(this.intervalTimer);
this.iscxhk = !this.iscxhk;
this.intervalTimer = null;
this.countDown = 0;
this.isCounting = false;
//
this.reSetSlider();
},
// === 便 ===
// mousedown
mouseDown(e) {
if (!this.confirmSuccess) {
e.preventDefault && e.preventDefault(); //
this.mouseMoveState = true;
this.beginClientX = e.clientX;
}
},
//
successFunction() {
getVerify().then((res) => {
this.loginForm.captchaVerification = res.data;
this.confirmSuccess = true;
this.confirmWords = '验证通过';
// mouseDown(e) { ... },
// successFunction() { ... },
// removeMouseListeners() { ... },
// mouseMoveFn(e) { ... },
// moseUpFn(e) { ... },
// reSet() { ... },
// reSetSlider() { ... },
// addMouseListeners() { ... },
// === end ===
//
refreshCaptcha() {
getCaptcha().then((res) => {
this.captchaUuid = res.data.uuid;
this.captchaImage = res.data.imageBase64;
this.loginForm.captchaVerification = res.data.uuid;
this.loginForm.captchaCode = '';
});
this.removeMouseListeners();
},
//
removeMouseListeners() {
if (window.addEventListener) {
document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
} else {
document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {});
}
document.getElementsByClassName('drag_text')[0].style.color = '#fff';
document.getElementsByClassName('handler')[0].style.left = `${this.maxWidth}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${this.maxWidth}px`;
},
// mousemove
mouseMoveFn(e) {
if (this.mouseMoveState) {
const width = e.clientX - this.beginClientX;
if (width > 0 && width <= this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${width}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
} else if (width > this.maxWidth) {
this.successFunction();
}
}
},
// mouseup
moseUpFn(e) {
this.mouseMoveState = false;
const width = e.clientX - this.beginClientX;
if (width < this.maxWidth) {
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
}
},
reSet() {
this.formData.sfzhm = '';
this.formData.xm = '';
this.reSetSlider();
},
reSetSlider() {
this.confirmSuccess = false;
this.mouseMoveState = false;
this.confirmWords = '请按住滑块,拖动到最右边';
document.getElementsByClassName('handler')[0].style.left = `${0}px`;
document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
document.getElementsByClassName('drag_text')[0].style.color = 'black';
//
this.addMouseListeners();
},
//
addMouseListeners() {
document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
},
},
mounted() {
//
this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
//
this.addMouseListeners();
// === ===
// this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
// this.addMouseListeners();
//
this.refreshCaptcha();
},
};
</script>
@ -363,4 +309,29 @@ stopAndResetTimer() {
.btn-container {
margin-top: 16px;
}
/* === 便 ===
.drag { ... }
.handler { ... }
.handler_bg { ... }
.handler_ok_bg { ... }
.drag_bg { ... }
.drag_text { ... }
*/
/* 新增:图形验证码样式 */
.captcha-wrapper {
display: flex;
align-items: center;
gap: 12px;
width: 350px;
height: 40px;
}
.captcha-img {
width: 120px;
height: 40px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #ccc;
}
</style>

View File

@ -13,7 +13,7 @@ public interface ErrorCodeConstants {
// ========== AUTH 模块 1-002-000-000 ==========
ErrorCode AUTH_LOGIN_BAD_CREDENTIALS = new ErrorCode(1004001, "登录失败,账号密码不正确");
ErrorCode AUTH_LOGIN_USER_DISABLED = new ErrorCode(1004002, "登录失败,账号被禁用");
ErrorCode AUTH_LOGIN_CAPTCHA_CODE_ERROR = new ErrorCode(1004003, "请重新滑动验证");
ErrorCode AUTH_LOGIN_CAPTCHA_CODE_ERROR = new ErrorCode(1004003, "验证码错误,请重新输入");
ErrorCode AUTH_LOGIN_PASSWORD_ERROR_LOCK = new ErrorCode(1004004, "密码输入错误次数过多,账户锁定,请稍后再试");

View File

@ -10,6 +10,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
@ -31,6 +33,14 @@ public class VerifyController {
return verifyService.getVerifyToken(remoteId);
}
@Operation(summary = "获取图形验证码")
@PermitAll
@PostMapping("/captcha")
public CommonResult<Map<String, String>> getCaptcha(HttpServletRequest request) {
final String remoteId = getRemoteId(request);
return verifyService.getCaptcha(remoteId);
}
public static String getRemoteId(HttpServletRequest request) {
String ip = ServletUtils.getClientIP(request);
String ua = request.getHeader("user-agent");

View File

@ -38,6 +38,11 @@ public class AuthLoginReqVO {
@JsonProperty("CaptchaVerification")
private String captchaVerification;
@Schema(description = "用户输入的图形验证码", requiredMode = Schema.RequiredMode.REQUIRED,
example = "Kp7m")
@JsonProperty("CaptchaCode")
private String captchaCode;
// ========== 绑定社交登录时需要传递如下参数 ==========
@Schema(description = "社交平台的类型,参见 SocialTypeEnum 枚举值", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")

View File

@ -112,7 +112,11 @@ public class AuthServiceImpl implements AuthService {
@Override
public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
final Boolean checked = verifyService.checkVerifyToken(reqVO.getCaptchaVerification());
// 校验图形验证码
final Boolean checked = verifyService.checkCaptcha(
reqVO.getCaptchaVerification(),
reqVO.getCaptchaCode()
);
if (!checked) {
throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR);
}

View File

@ -1,6 +1,7 @@
package com.css.txw.sso.service.verify;
import com.css.ggzc.framework.common.pojo.CommonResult;
import java.util.Map;
public interface VerifyService {
@ -8,6 +9,7 @@ public interface VerifyService {
Boolean checkVerifyToken(String verifyToken);
CommonResult<Map<String, String>> getCaptcha(String remoteId);
Boolean checkCaptcha(String uuid, String code);
}

View File

@ -1,12 +1,23 @@
package com.css.txw.sso.service.verify;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.txw.sso.properties.SsoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@ -17,6 +28,16 @@ public class VerifyServiceImpl implements VerifyService {
private StringRedisTemplate stringRedisTemplate;
@Resource
private SsoProperties ssoProperties;
@Resource
private ICaptcha lineCaptcha;
@Bean
public ICaptcha captchaGenerator() {
RandomGenerator randomGenerator = new RandomGenerator("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 4);
cn.hutool.captcha.CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 40, 4, 20);
captcha.setGenerator(randomGenerator);
return captcha;
}
@Override
public CommonResult<String> getVerifyToken(String remoteId) {
@ -38,4 +59,54 @@ public class VerifyServiceImpl implements VerifyService {
String VERIFY_TOKEN = "verify_token:%s";
return String.format(VERIFY_TOKEN, verifyToken);
}
@Override
public CommonResult<Map<String, String>> getCaptcha(String remoteId) {
cn.hutool.captcha.CircleCaptcha circleCaptcha = (cn.hutool.captcha.CircleCaptcha) lineCaptcha;
// 重新生成验证码否则返回的总是相同的图片
circleCaptcha.createCode();
String code = circleCaptcha.getCode();
String uuid = IdUtil.fastSimpleUUID();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(circleCaptcha.getImage(), "png", baos);
} catch (IOException e) {
throw new RuntimeException("生成验证码图片失败", e);
}
String imageBase64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
stringRedisTemplate.opsForValue().set(
formatCaptchaKey(uuid),
code.toLowerCase(),
5,
TimeUnit.MINUTES
);
Map<String, String> result = new HashMap<>();
result.put("uuid", uuid);
result.put("imageBase64", imageBase64);
return CommonResult.success(result);
}
@Override
public Boolean checkCaptcha(String uuid, String code) {
if (!this.ssoProperties.isLoginCaptcha()) {
return true;
}
if (StrUtil.isBlank(uuid) || StrUtil.isBlank(code)) {
return false;
}
String key = formatCaptchaKey(uuid);
String cachedCode = stringRedisTemplate.opsForValue().get(key);
if (cachedCode == null) {
return false;
}
stringRedisTemplate.delete(key);
return cachedCode.equalsIgnoreCase(code);
}
private static String formatCaptchaKey(String uuid) {
return "captcha:" + uuid;
}
}