17 基于SqlSugar的開發框架循序漸進介紹-- 基于CSRedis實現緩存的處理( 二 )

WebAPI后端,處理邏輯是構建隨機的驗證碼并通過短信發送到手機上,并緩存好對應的驗證碼,后端的處理代碼如下所示
/// <summary>/// 發送登錄動態碼/// </summary>/// <param name="model"></param>/// <returns></returns>[AllowAnonymous][HttpPost][Route("send-login-smscode")]public async Task<CommonResult> SendPhoneLoginSmsCode(PhoneCaptchaModel model){    //獲取隨機6位數字動態驗證碼    var code = RandomChinese.GetRandomNumber(6);    //使用自定義模板處理短信發送    string message = string.Format(ConfigData.MySmsCodeTemplate, code);    var result = await _smsSender.SendAsync(model.PhoneNumber, message);    if (result.Success)    {        var cacheKey = model.PhoneNumber;//以手機號碼作為鍵存儲驗證碼緩存        var cacheItem = new SmsLoginCodeCacheItem { Code = code, PhoneNumber = model.PhoneNumber };RedisHelper.Set(cacheKey, cacheItem, TimeSpan.FromMinutes(ConfigData.SmsCodeExpiredMinutes));        //獲取的時候        //var tmp = RedisHelper.Get<SmsLoginCodeCacheItem>(cacheKey);    }    return result;}順利發送短信驗證碼后,前端會提示用戶驗證碼發送情況,并要求輸入驗證碼進行登錄,前端登錄的代碼如下所示 。
//短信驗證碼登錄loginByCode() {    var params = {        mobile: this.model.mobile,        smscode: this.model.code    };    console.log(params);    user.dynamiclogin(params)        .then(res => {            uni.$u.toast('驗證成功');            this.gotoPage();        })        .catch(error => {            console.log('驗證失敗' + error);            uni.$u.toast(error);        });},后端的登錄處理,主要就是通過在Redis中讀取對應的手機驗證碼,如果匹配進行令牌的生成處理,否則提示錯誤信息 。
/// <summary>/// 登錄授權處理/// </summary>/// <returns></returns>[AllowAnonymous][HttpPost][Route("authenticate-byphone")]public async Task<AuthenticateResultDto> AuthenticateByPhoneCaptcha(PhoneCaptchaModel model){    var authResult = new AuthenticateResultDto();    #region 條件檢查    if (string.IsNullOrEmpty(model.PhoneNumber))    {        throw new MyApiException("手機號不能為空");    }    if (string.IsNullOrEmpty(model.SmsCode))    {        throw new MyApiException("驗證碼不能為空");    }    var userInfo = await _userService.GetFirstAsync(s => s.MobilePhone == model.PhoneNumber);    if (userInfo == null)    {        throw new MyApiException("用戶手機不存在");    }    #endregion    var cacheKey = model.PhoneNumber;//以手機號碼作為鍵存儲驗證碼緩存    var item = RedisHelper.Get<SmsLoginCodeCacheItem>(cacheKey);    if (item != null && item.Code == model.SmsCode)    {        //根據用戶身份生成tokenresult        authResult.AccessToken = GenerateToken(userInfo); //令牌        authResult.Expires = expiredDays * 24 * 3600; //失效秒數        authResult.Success = true;//成功        authResult.UserId = userInfo.Id;//當前用戶Id        //移除緩存短信鍵值        RedisHelper.Del(cacheKey);    }    else    {        authResult.Error = "登錄失敗,無法生成令牌";    }    return authResult;}

推薦閱讀