feat: 新增找回密码功能接口

This commit is contained in:
橙子
2024-10-03 01:10:32 +08:00
parent 94ee0fb058
commit d7629763ef
13 changed files with 362 additions and 222 deletions

View File

@@ -0,0 +1,24 @@
namespace Yi.Framework.Rbac.Application.Contracts.Dtos.Account;
public class RetrievePasswordDto
{
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 唯一标识码
/// </summary>
public string? Uuid { get; set; }
/// <summary>
/// 电话
/// </summary>
public long Phone { get; set; }
/// <summary>
/// 验证码
/// </summary>
public string? Code { get; set; }
}

View File

@@ -27,6 +27,7 @@ using Yi.Framework.Rbac.Domain.Repositories;
using Yi.Framework.Rbac.Domain.Shared.Caches;
using Yi.Framework.Rbac.Domain.Shared.Consts;
using Yi.Framework.Rbac.Domain.Shared.Dtos;
using Yi.Framework.Rbac.Domain.Shared.Enums;
using Yi.Framework.Rbac.Domain.Shared.Etos;
using Yi.Framework.Rbac.Domain.Shared.Options;
using Yi.Framework.SqlSugarCore.Abstractions;
@@ -44,6 +45,7 @@ namespace Yi.Framework.Rbac.Application.Services
private IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> _userCache;
private UserManager _userManager;
private IHttpContextAccessor _httpContextAccessor;
public AccountService(IUserRepository userRepository,
ICurrentUser currentUser,
IAccountManager accountManager,
@@ -127,7 +129,7 @@ namespace Yi.Framework.Rbac.Application.Services
loginEto.UserId = userInfo.User.Id;
await LocalEventBus.PublishAsync(loginEto);
}
return new { Token = accessToken, RefreshToken = refreshToken };
}
@@ -178,14 +180,35 @@ namespace Yi.Framework.Rbac.Application.Services
/// <summary>
/// 注册 手机验证码
/// 手机验证码-注册
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("captcha-phone")]
[AllowAnonymous]
public async Task<object> PostCaptchaPhoneForRegisterAsync(PhoneCaptchaImageDto input)
{
return await PostCaptchaPhoneAsync(ValidationPhoneTypeEnum.Register, input);
}
/// <summary>
/// 手机验证码-找回密码
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("captcha-phone/repassword")]
public async Task<object> PostCaptchaPhoneForRetrievePasswordAsync(PhoneCaptchaImageDto input)
{
return await PostCaptchaPhoneAsync(ValidationPhoneTypeEnum.RetrievePassword, input);
}
/// <summary>
/// 手机验证码
/// </summary>
/// <returns></returns>
[AllowAnonymous]
public async Task<object> PostCaptchaPhone(PhoneCaptchaImageDto input)
private async Task<object> PostCaptchaPhoneAsync(ValidationPhoneTypeEnum validationPhoneType,
PhoneCaptchaImageDto input)
{
await ValidationPhone(input.Phone);
var value = await _phoneCache.GetAsync(new CaptchaPhoneCacheKey(input.Phone));
var value = await _phoneCache.GetAsync(new CaptchaPhoneCacheKey(validationPhoneType, input.Phone));
//防止暴刷
if (value is not null)
@@ -200,7 +223,8 @@ namespace Yi.Framework.Rbac.Application.Services
var uuid = Guid.NewGuid();
await _aliyunManger.SendSmsAsync(input.Phone, code);
await _phoneCache.SetAsync(new CaptchaPhoneCacheKey(input.Phone), new CaptchaPhoneCacheItem(code),
await _phoneCache.SetAsync(new CaptchaPhoneCacheKey(ValidationPhoneTypeEnum.Register, input.Phone),
new CaptchaPhoneCacheItem(code),
new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) });
return new
{
@@ -211,19 +235,44 @@ namespace Yi.Framework.Rbac.Application.Services
/// <summary>
/// 校验电话验证码,需要与电话号码绑定
/// </summary>
private async Task ValidationPhoneCaptchaAsync(RegisterDto input)
private async Task ValidationPhoneCaptchaAsync(ValidationPhoneTypeEnum validationPhoneType, long phone,
string code)
{
var item = await _phoneCache.GetAsync(new CaptchaPhoneCacheKey(input.Phone.ToString()));
if (item is not null && item.Code.Equals($"{input.Code}"))
var item = await _phoneCache.GetAsync(new CaptchaPhoneCacheKey(validationPhoneType, phone.ToString()));
if (item is not null && item.Code.Equals($"{code}"))
{
//成功,需要清空
await _phoneCache.RemoveAsync(new CaptchaPhoneCacheKey(input.Phone.ToString()));
await _phoneCache.RemoveAsync(new CaptchaPhoneCacheKey(validationPhoneType, code.ToString()));
return;
}
throw new UserFriendlyException("验证码错误");
}
/// <summary>
/// 找回密码
/// </summary>
/// <param name="input"></param>
[AllowAnonymous]
[UnitOfWork]
public async Task PostRetrievePasswordAsync(RetrievePasswordDto input)
{
if (_rbacOptions.EnableCaptcha)
{
//校验验证码,根据电话号码获取 value比对验证码已经uuid
await ValidationPhoneCaptchaAsync(ValidationPhoneTypeEnum.RetrievePassword, input.Phone, input.Code);
}
var entity = await _userRepository.GetFirstAsync(x => x.Phone == input.Phone);
if (entity is null)
{
throw new UserFriendlyException("该手机号码未注册");
}
await _accountManager.RestPasswordAsync(entity.Id, input.Password);
}
/// <summary>
/// 注册,需要验证码通过
/// </summary>
@@ -241,16 +290,16 @@ namespace Yi.Framework.Rbac.Application.Services
if (_rbacOptions.EnableCaptcha)
{
//校验验证码,根据电话号码获取 value比对验证码已经uuid
await ValidationPhoneCaptchaAsync(input);
await ValidationPhoneCaptchaAsync(ValidationPhoneTypeEnum.Register, input.Phone, input.Code);
}
//注册领域逻辑
await _accountManager.RegisterAsync(input.UserName, input.Password, input.Phone,input.Nick);
await _accountManager.RegisterAsync(input.UserName, input.Password, input.Phone, input.Nick);
}
/// <summary>
/// 查询已登录的账户信息,已缓存
/// 查询已登录的账户信息
/// </summary>
/// <returns></returns>
[Route("account")]
@@ -270,9 +319,6 @@ namespace Yi.Framework.Rbac.Application.Services
}
/// <summary>
/// 获取当前登录用户的前端路由
/// 支持ruoyi/pure
@@ -280,7 +326,7 @@ namespace Yi.Framework.Rbac.Application.Services
/// <returns></returns>
[Authorize]
[Route("account/Vue3Router/{routerType?}")]
public async Task<object> GetVue3Router([FromRoute]string? routerType)
public async Task<object> GetVue3Router([FromRoute] string? routerType)
{
var userId = _currentUser.Id;
if (_currentUser.Id is null)
@@ -298,18 +344,19 @@ namespace Yi.Framework.Rbac.Application.Services
}
object output = null;
if (routerType is null ||routerType=="ruoyi")
if (routerType is null || routerType == "ruoyi")
{
//将后端菜单转换成前端路由,组件级别需要过滤
output =
ObjectMapper.Map<List<MenuDto>, List<MenuAggregateRoot>>(menus).Vue3RuoYiRouterBuild();
}
else if (routerType =="pure")
else if (routerType == "pure")
{
//将后端菜单转换成前端路由,组件级别需要过滤
output =
ObjectMapper.Map<List<MenuDto>, List<MenuAggregateRoot>>(menus).Vue3PureRouterBuild();
}
return output;
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.Rbac.Domain.Shared.Enums;
namespace Yi.Framework.Rbac.Domain.Shared.Caches
{
@@ -14,13 +15,15 @@ namespace Yi.Framework.Rbac.Domain.Shared.Caches
public class CaptchaPhoneCacheKey
{
public CaptchaPhoneCacheKey(string phone) { Phone = phone; }
public CaptchaPhoneCacheKey(ValidationPhoneTypeEnum validationPhoneType,string phone) { Phone = phone;
ValidationPhoneType = validationPhoneType;
}
public ValidationPhoneTypeEnum ValidationPhoneType { get; set; }
public string Phone { get; set; }
public override string ToString()
{
return $"Phone:{Phone}";
return $"Phone:{ValidationPhoneType.ToString()}:{Phone}";
}
}
}

View File

@@ -0,0 +1,13 @@
namespace Yi.Framework.Rbac.Domain.Shared.Enums;
public enum ValidationPhoneTypeEnum
{
/// <summary>
/// 注册
/// </summary>
Register,
/// <summary>
/// 忘记密码
/// </summary>
RetrievePassword
}

View File

@@ -180,6 +180,8 @@ namespace Yi.Framework.Rbac.Domain.Managers
}
return false;
}
/// <summary>
/// 令牌转换
@@ -250,7 +252,7 @@ namespace Yi.Framework.Rbac.Domain.Managers
}
/// <summary>
/// 重置密码
/// 重置密码,也可以是找回密码
/// </summary>
/// <param name="userId"></param>
/// <param name="password"></param>
@@ -258,7 +260,6 @@ namespace Yi.Framework.Rbac.Domain.Managers
public async Task<bool> RestPasswordAsync(Guid userId, string password)
{
var user = await _repository.GetByIdAsync(userId);
// EntityHelper.TrySetId(user, () => GuidGenerator.Create(), true);
user.EncryPassword.Password = password;
user.BuildPassword();
return await _repository.UpdateAsync(user);
@@ -276,7 +277,6 @@ namespace Yi.Framework.Rbac.Domain.Managers
var user = new UserAggregateRoot(userName, password, phone,nick);
await _userManager.CreateAsync(user);
await _userManager.SetDefautRoleAsync(user.Id);
}
}

View File

@@ -51,12 +51,12 @@ namespace Yi.Framework.Rbac.Domain.Operlog
/// <summary>
/// 请求参数
///</summary>
[SugarColumn(ColumnName = "RequestParam")]
[SugarColumn(ColumnName = "RequestParam",ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string? RequestParam { get; set; }
/// <summary>
/// 请求结果
///</summary>
[SugarColumn(ColumnName = "RequestResult", Length = 9999)]
[SugarColumn(ColumnName = "RequestResult",ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string? RequestResult { get; set; }
public DateTime CreationTime { get; set; }

View File

@@ -146,13 +146,7 @@ align-items: flex-end;
height: 40px;
text-align: center;
}
.div-bottom
{
position: absolute;
bottom: 30px;
color:#CAD2D9;
font-size: 12px;
}
.div-bottom span{
margin: 0 5px;
cursor: pointer;

View File

@@ -108,7 +108,7 @@ const currentUserInfo=computed(()=>{
message: `您好${params.userName},登录成功!`,
type: "success",
});
loginSuccess(res);
await loginSuccess(res);
return res;
} catch (error) {
const { data } = error;

View File

@@ -2,11 +2,24 @@
<div class="box">
<div class="content">
<RouterView />
<div class="div-bottom">
<span>备案<span v-html="configStore.icp"></span></span>
<span>站长{{ configStore.author }}</span>
<span ><router-link to="/contact">联系我们</router-link></span>
<span>关于本站</span>
<span>建议反馈</span>
<span>原创站点</span>
</div>
</div>
</div>
</template>
<!-- <style src="@/assets/styles/login.scss" scoped></style> -->
<script setup>
import useConfigStore from "@/stores/config";
const configStore=useConfigStore();
</script>
<style scoped lang="scss">
.box {
width: 100vw;
@@ -16,4 +29,34 @@
height: 100%;
}
}
.div-bottom
{
position: absolute;
bottom: 30px;
color: #CAD2D9;
font-size: 12px;
width: 100%;
display: flex;
justify-content: center;
span{
margin-right: 10px;
}
a {
$link-color: red;
color: $link-color;
&.visited {
color: $link-color;
}
&:hover {
color: $link-color;
}
&:active {
color: $link-color;
}
}
}
</style>

View File

@@ -28,11 +28,11 @@ const router = createRouter({
// component: () => import("../views/Login.vue"),
component: () => import("../views/login/index.vue"),
},
// {
// name: "register",
// path: "/register",
// component: () => import("../views/Register.vue"),
// },
{
name: "register",
path: "/register",
component: () => import("../views/login/register.vue"),
},
{
name: "auth",
path: "/auth/:type",

View File

@@ -0,0 +1,11 @@
<script setup>
</script>
<template>
</template>
<style scoped lang="scss">
</style>

View File

@@ -1,7 +1,7 @@
<template>
<div class="container">
<!-- 登录 -->
<div class="div-content" v-if="isRegister">
<div class="div-content">
<div class="div-left">
<div class="left-container">
<p class="title title-1">Hello,<span @click="guestlogin">you can go to homepage >></span></p>
@@ -53,101 +53,18 @@
</div>
</div>
<div class="div-right">
<img class="div-img" src="@/assets/login.png"/>
<img class="div-img" src="@/assets/login.png" alt=""/>
</div>
</div>
<!-- 注册 -->
<div class="div-content" v-else>
<div class="div-right-register">
<img class="div-img" src="@/assets/login.png"/>
</div>
<div class="div-left-register">
<div class="left-container">
<p class="title register-title">Thank Join to Yi!</p>
<el-form
class="registerForm"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
>
<div class="input-content">
<div style="display: flex;justify-content: space-between;margin: 0">
<div class="input" style="width: 55%;margin: 0">
<p>*登录账号</p>
<el-form-item prop="userName">
<input type="text" v-model.trim="registerForm.userName">
</el-form-item>
</div>
<div class="input" style="width: 35%;margin: 0">
<p>昵称</p>
<el-form-item prop="userName">
<input type="text" v-model.trim="registerForm.nick">
</el-form-item>
</div>
</div>
<div class="input" style="margin-top: 0">
<p>*电话</p>
<el-form-item prop="phone">
<div class="phone-code">
<input class="phone-code-input" type="text" v-model.trim="registerForm.phone">
<button type="button" class="phone-code-btn" @click="captcha()">{{codeInfo}}</button>
</div>
</el-form-item>
</div>
<div class="input">
<p>*短信验证码</p>
<el-form-item prop="code" >
<input :disabled="!isDisabledCode" type="text" v-model.trim="registerForm.code">
</el-form-item>
</div>
<div class="input">
<p>*密码</p>
<el-form-item prop="password">
<input :disabled="!isDisabledCode" type="password" v-model.trim="registerForm.password">
</el-form-item>
</div>
<div class="input">
<p>*确认密码</p>
<el-form-item>
<input :disabled="!isDisabledCode" type="password" v-model.trim="passwordConfirm">
</el-form-item>
</div>
</div>
</el-form>
<div class="left-btn">
<button type="button" class="btn-login" @click="register(registerFormRef)">注册</button>
<button type="button" class="btn-reg" @click="handleSignInNow">前往登录</button>
</div>
</div>
</div>
</div>
<div class="div-bottom">
<span>备案<span v-html="configStore.icp"></span></span>
<span>站长{{ configStore.author }}</span>
<span @click="handleContact">联系我们</span>
<span>关于本站</span>
<span>建议反馈</span>
<span>原创站点</span>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import useAuths from "@/hooks/useAuths";
import { getCodePhone } from "@/apis/accountApi";
import useUserStore from "@/stores/user";
import useConfigStore from "@/stores/config";
const configStore = useConfigStore();
const { loginFun, registerFun, loginSuccess } = useAuths();
const { loginFun, loginSuccess } = useAuths();
const router = useRouter();
const route = useRoute();
const loginFormRef = ref();
@@ -161,7 +78,12 @@ const loginForm = reactive({
uuid: "",
code: "",
});
const guestlogin = async () => {
//前往注册
const handleRegister=()=>{
router.push("/register");
}
//直接进入首页
const guestlogin = () => {
const redirect = route.query?.redirect ?? "/index";
router.push(redirect);
};
@@ -185,97 +107,6 @@ const login = async (formEl) => {
});
};
// 注册逻辑
const isRegister = ref(true);
const registerFormRef = ref();
// 确认密码
const passwordConfirm = ref("");
const registerForm = reactive({
userName: "",
phone: "",
password: "",
uuid: "",
code: "",
nick:""
});
const registerRules = reactive({
nick: [
{ min: 2, message: "昵称需大于两位", trigger: "blur" },
],
userName: [
{ required: true, message: "请输入用户名", trigger: "blur" },
{ min: 2, message: "用户名需大于两位", trigger: "blur" },
],
phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
password: [
{ required: true, message: "请输入新的密码", trigger: "blur" },
{ min: 6, message: "密码需大于六位", trigger: "blur" },
],
});
const handleRegister = () => {
isRegister.value = !isRegister.value;
};
const register = async (formEl) => {
if (!formEl) return;
await formEl.validate(async (valid) => {
if (valid) {
try {
if (registerForm.password != passwordConfirm.value) {
ElMessage.error("两次密码输入不一致");
return;
}
await registerFun(registerForm);
handleRegister();
} catch (error) {
ElMessage({
message: error.message,
type: "error",
duration: 2000,
});
}
}
});
};
//验证码
const codeInfo = ref("发送短信");
const isDisabledCode = ref(false);
const captcha = async () => {
if (registerForm.phone !== "") {
const { data } = await getCodePhone(registerForm.phone);
registerForm.uuid = data.uuid;
ElMessage({
message: `已向${registerForm.phone}发送验证码,请注意查收`,
type: "success",
});
isDisabledCode.value = true;
let time = 60; //定义剩下的秒数
let timer = setInterval(function () {
if (time == 0) {
//清除定时器和复原按钮
clearInterval(timer);
codeInfo.value = "发送验证码";
time = 60; //这个10是重新开始
} else {
codeInfo.value = "剩余" + time + "秒";
time--;
}
}, 1000);
} else {
ElMessage({
message: `请先输入手机号`,
type: "warning",
});
}
};
// 立即登录
const handleSignInNow = () => {
isRegister.value = !isRegister.value;
};
// 获取图片验证码
const codeImageURL = computed(() => useUserStore().codeImageURL);
const handleGetCodeImage = () => {
@@ -285,10 +116,6 @@ onMounted(async () => {
await useUserStore().updateCodeImage();
});
// 联系我们跳转对应页面
const handleContact = () => {
router.push("/contact");
};
const handleQQLogin = () => {
window.open(

View File

@@ -0,0 +1,178 @@
<script setup>
// 注册逻辑
import {reactive, ref} from "vue";
import {getCodePhone} from "@/apis/accountApi";
import useAuths from "@/hooks/useAuths";
import {useRoute, useRouter} from "vue-router";
const { registerFun } = useAuths();
const router = useRouter();
const route = useRoute();
const registerFormRef = ref();
// 确认密码
const passwordConfirm = ref("");
const registerForm = reactive({
userName: "",
phone: "",
password: "",
uuid: "",
code: "",
nick:""
});
const registerRules = reactive({
nick: [
{ min: 2, message: "昵称需大于两位", trigger: "blur" },
],
userName: [
{ required: true, message: "请输入用户名", trigger: "blur" },
{ min: 2, message: "用户名需大于两位", trigger: "blur" },
],
phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
password: [
{ required: true, message: "请输入新的密码", trigger: "blur" },
{ min: 6, message: "密码需大于六位", trigger: "blur" },
],
});
const register = async (formEl) => {
if (!formEl) return;
await formEl.validate(async (valid) => {
if (valid) {
try {
if (registerForm.password != passwordConfirm.value) {
ElMessage.error("两次密码输入不一致");
return;
}
await registerFun(registerForm);
//注册成功返回登录
handleSignInNow();
} catch (error) {
ElMessage({
message: error.message,
type: "error",
duration: 2000,
});
}
}
});
};
//验证码
const codeInfo = ref("发送短信");
const isDisabledCode = ref(false);
//前往登录
const handleSignInNow=()=>{
router.push("/login");
}
const captcha = async () => {
if (registerForm.phone !== "") {
const { data } = await getCodePhone(registerForm.phone);
registerForm.uuid = data.uuid;
ElMessage({
message: `已向${registerForm.phone}发送验证码,请注意查收`,
type: "success",
});
isDisabledCode.value = true;
let time = 60; //定义剩下的秒数
let timer = setInterval(function () {
if (time == 0) {
//清除定时器和复原按钮
clearInterval(timer);
codeInfo.value = "发送验证码";
time = 60; //这个10是重新开始
} else {
codeInfo.value = "剩余" + time + "秒";
time--;
}
}, 1000);
} else {
ElMessage({
message: `请先输入手机号`,
type: "warning",
});
}
};
</script>
<template>
<div class="container">
<!-- 注册 -->
<div class="div-content">
<div class="div-right-register">
<img class="div-img" src="@/assets/login.png"/>
</div>
<div class="div-left-register">
<div class="left-container">
<p class="title register-title">Thank Join to Yi!</p>
<el-form
class="registerForm"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
>
<div class="input-content">
<div style="display: flex;justify-content: space-between;margin: 0">
<div class="input" style="width: 55%;margin: 0">
<p>*登录账号</p>
<el-form-item prop="userName">
<input type="text" v-model.trim="registerForm.userName">
</el-form-item>
</div>
<div class="input" style="width: 35%;margin: 0">
<p>昵称</p>
<el-form-item prop="nick">
<input type="text" v-model.trim="registerForm.nick">
</el-form-item>
</div>
</div>
<div class="input" style="margin-top: 0">
<p>*电话</p>
<el-form-item prop="phone">
<div class="phone-code">
<input class="phone-code-input" type="text" v-model.trim="registerForm.phone">
<button type="button" class="phone-code-btn" @click="captcha()">{{codeInfo}}</button>
</div>
</el-form-item>
</div>
<div class="input">
<p>*短信验证码</p>
<el-form-item prop="code" >
<input :disabled="!isDisabledCode" type="text" v-model.trim="registerForm.code">
</el-form-item>
</div>
<div class="input">
<p>*密码</p>
<el-form-item prop="password">
<input :disabled="!isDisabledCode" type="password" v-model.trim="registerForm.password">
</el-form-item>
</div>
<div class="input">
<p>*确认密码</p>
<el-form-item>
<input :disabled="!isDisabledCode" type="password" v-model.trim="passwordConfirm">
</el-form-item>
</div>
</div>
</el-form>
<div class="left-btn">
<button type="button" class="btn-login" @click="register(registerFormRef)">注册</button>
<button type="button" class="btn-reg" @click="handleSignInNow">前往登录</button>
</div>
</div>
</div>
</div>
</div>
</template>
<style src="@/assets/styles/login.css" scoped>
</style>