前言
本文在修改代码前已经完成了 aj-capcha 的后端集成,后端相关代码编写和修改,完成了前端的集成,登录逻辑相关代码的编写。此文章只做注册逻辑相关代码的修改。
叠甲声明
本人只是一个菜鸟,很多技术和技巧也是学习各位大佬的,写博客只是总结学习,防止以后忘记,说不定哪天自己还能用上,如果有幸被人看到,还能帮到大家本人倍感荣幸,文章中如有错误,还请各位大佬指出,本人定虚心接受学习,本意是自己学习,技术很菜,请各位勿笑。
后端
- 修改路径 com/ruoyi/framework/web/service/SysRegisterService.java 文件的 register 方法。
* 注册
*/
public String register(RegisterBody registerBody)
{
String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
SysUser sysUser = new SysUser();
sysUser.setUserName(username);
// 验证码开关
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled)
{
validateCaptcha(username, registerBody.getCode());
}
if (StringUtils.isEmpty(username))
{
msg = "用户名不能为空";
}
else if (StringUtils.isEmpty(password))
{
msg = "用户密码不能为空";
}
else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
msg = "账户长度必须在2到20个字符之间";
}
else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
msg = "密码长度必须在5到20个字符之间";
}
else if (!userService.checkUserNameUnique(sysUser))
{
msg = "保存用户'" + username + "'失败,注册账号已存在";
}
else
{
sysUser.setNickName(username);
sysUser.setPassword(SecurityUtils.encryptPassword(password));
boolean regFlag = userService.registerUser(sysUser);
if (!regFlag)
{
msg = "注册失败,请联系系统管理人员";
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
}
}
return msg;
}
仅删除了 register 方法中的 uuid 参数。
2.继续在该方法下替换验证码校验方法(validateCaptcha)---该方法是aj-captcha的校验方法
/**
* 校验验证码 aj-captcha验证方式
*
* @param username 用户名
* @param code 验证码
* @return 结果
*/
public void validateCaptcha(String username, String code)
{
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled)
{
CaptchaVO captchaVO = new CaptchaVO();
captchaVO.setCaptchaVerification(code);
ResponseModel response = captchaService.verification(captchaVO);
if (!response.isSuccess())
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
}
}
3.最后一点需要注意,在这里面会使用到 CaptchaService ,但是在注入的时候会选择使用懒注入的方式。可能会需要手动导包。
@Autowired
@Lazy
private CaptchaService captchaService;
记得导入的是这个包
import org.springframework.context.annotation.Lazy;
前端
- 建议直接复制下方代码
<template>
<div class="register">
<el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
<h3 class="title">快洁达后台管理系统</h3>
<el-form-item prop="username">
<el-input v-model="registerForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
<template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="registerForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
@keyup.enter="handleRegister">
<template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
</el-input>
</el-form-item>
<el-form-item prop="confirmPassword">
<el-input v-model="registerForm.confirmPassword" type="password" size="large" auto-complete="off"
placeholder="确认密码" @keyup.enter="handleRegister">
<template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
</el-input>
</el-form-item>
<Verify @success="capctchaCheckSuccess" :mode="'pop'" :captchaType="'blockPuzzle'"
:imgSize="{ width: '330px', height: '155px' }" ref="verify" v-if="captchaEnabled"></Verify>
<el-form-item style="width:100%;">
<el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleRegister">
<span v-if="!loading">注 册</span>
<span v-else>注 册 中...</span>
</el-button>
<div style="float: right;">
<router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
</div>
</el-form-item>
</el-form>
<!-- 底部 -->
<div class="el-register-footer">
<span>Copyright © 2018-2023 ruoyi.vip All Rights Reserved.</span>
</div>
</div>
</template>
<script setup>
import { ElMessageBox } from "element-plus";
import { register } from "@/api/login";
import Verify from "@/components/Verifition/Verify";
import { isCaptchaEnabled } from "@/api/login";
const router = useRouter();
const { proxy } = getCurrentInstance();
const registerForm = ref({
username: "",
password: "",
confirmPassword: "",
code: "",
});
const equalToPassword = (rule, value, callback) => {
if (registerForm.value.password !== value) {
callback(new Error("两次输入的密码不一致"));
} else {
callback();
}
};
const registerRules = {
username: [
{ required: true, trigger: "blur", message: "请输入您的账号" },
{ min: 2, max: 20, message: "用户账号长度必须介于 2 和 20 之间", trigger: "blur" }
],
password: [
{ required: true, trigger: "blur", message: "请输入您的密码" },
{ min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
],
confirmPassword: [
{ required: true, trigger: "blur", message: "请再次输入您的密码" },
{ required: true, validator: equalToPassword, trigger: "blur" }
],
code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};
const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);
function handleRegister() {
// 显示验证码组件
proxy.$refs.verify.show();
}
function capctchaCheckSuccess(params) {
registerForm.value.code = params.captchaVerification;
proxy.$refs.registerRef.validate(valid => {
if (valid) {
loading.value = true;
register(registerForm.value).then(res => {
const username = registerForm.value.username;
ElMessageBox.alert("<font color='red'>恭喜你,您的账号 " + username + " 注册成功!</font>", "系统提示", {
dangerouslyUseHTMLString: true,
type: "success",
}).then(() => {
router.push("/login");
}).catch(() => { });
}).catch(() => {
loading.value = false;
if (captchaEnabled) {
getCaptchaEnabled();
}
});
}
});
}
// 获取验证码开关
function getCaptchaEnabled() {
isCaptchaEnabled().then(res => {
console.log('Captcha enabled:', res.captchaEnabled); // 添加日志输出
captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
});
}
getCaptchaEnabled();
</script>
<style lang='scss' scoped>
.register {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background-image: url("../assets/images/login-background.jpg");
background-size: cover;
}
.title {
margin: 0px auto 30px auto;
text-align: center;
color: #707070;
}
.register-form {
border-radius: 6px;
background: #ffffff;
width: 400px;
padding: 25px 25px 5px 25px;
.el-input {
height: 40px;
input {
height: 40px;
}
}
.input-icon {
height: 39px;
width: 14px;
margin-left: 0px;
}
}
.register-tip {
font-size: 13px;
text-align: center;
color: #bfbfbf;
}
.register-code {
width: 33%;
height: 40px;
float: right;
img {
cursor: pointer;
vertical-align: middle;
}
}
.el-register-footer {
height: 40px;
line-height: 40px;
position: fixed;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
font-family: Arial;
font-size: 12px;
letter-spacing: 1px;
}
.register-code-img {
height: 40px;
padding-left: 12px;
}
</style>
前端代码修改地方
准备工作 --- 导入相关组件和方法
import Verify from "@/components/Verifition/Verify";
import { isCaptchaEnabled } from "@/api/login";
1.增加验证码框
<Verify @success="capctchaCheckSuccess" :mode="'pop'" :captchaType="'blockPuzzle'" :imgSize="{ width: '330px', height: '155px' }" ref="verify" v-if="captchaEnabled"></Verify>
2.删除注册表单中的 uuid 参数
const registerForm = ref({
username: "",
password: "",
confirmPassword: "",
code: "",
});
3.实现验证码开关
// 获取验证码开关
function getCaptchaEnabled() {
isCaptchaEnabled().then(res => {
console.log('Captcha enabled:', res.captchaEnabled); // 添加日志输出
captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
});
}
getCaptchaEnabled();
4.修改登录逻辑
function handleRegister() {
// 显示验证码组件
proxy.$refs.verify.show();
}
function capctchaCheckSuccess(params) {
registerForm.value.code = params.captchaVerification;
proxy.$refs.registerRef.validate(valid => {
if (valid) {
loading.value = true;
register(registerForm.value).then(res => {
const username = registerForm.value.username;
ElMessageBox.alert("<font color='red'>恭喜你,您的账号 " + username + " 注册成功!</font>", "系统提示", {
dangerouslyUseHTMLString: true,
type: "success",
}).then(() => {
router.push("/login");
}).catch(() => { });
}).catch(() => {
loading.value = false;
if (captchaEnabled) {
getCaptchaEnabled();
}
});
}
});
}