Ejemplo n.º 1
0
        public async Task <ApiResult <string> > VerifyPhone([FromBody] UserVerifyPhoneRequest value)
        {
            if (!ModelState.IsValid)
            {
                return(new ApiResult <string>(l, BasicControllerEnums.UnprocessableEntity,
                                              ModelErrors()));
            }

            #region 发送计数、验证是否已经达到上限
            var dailyLimitKey = UserControllerKeys.Limit_24Hour_Verify_Phone + value.PhoneNumber;

            var _dailyLimit = await redis.GetAsync(dailyLimitKey);

            if (!string.IsNullOrWhiteSpace(_dailyLimit))
            {
                var dailyLimit = int.Parse(_dailyLimit);

                if (dailyLimit > UserControllerKeys.Limit_24Hour_Verify_MAX_Phone)
                {
                    return(new ApiResult <string>(l, UserControllerEnums.VerifyPhone_CallLimited));
                }
            }
            else
            {
                await redis.SetAsync(dailyLimitKey, "0", TimeSpan.FromHours(24));
            }
            #endregion

            #region 验证发送间隔时间是否过快
            //两次发送间隔必须大于指定秒数
            var _lastTimeKey = UserControllerKeys.LastTime_SendCode_Phone + value.PhoneNumber;

            var lastTimeString = await redis.GetAsync(_lastTimeKey);

            if (!string.IsNullOrWhiteSpace(lastTimeString))
            {
                var lastTime = long.Parse(lastTimeString);

                var now = DateTime.UtcNow.AddHours(8).Ticks;

                var usedTime = (now - lastTime) / 10000000;

                if (usedTime < UserControllerKeys.MinimumTime_SendCode_Phone)
                {
                    return(new ApiResult <string>(l, UserControllerEnums.VerifyPhone_TooManyRequests, string.Empty,
                                                  UserControllerKeys.MinimumTime_SendCode_Phone - usedTime));
                }
            }
            #endregion

            #region 发送验证码
            var verifyCode = random.Next(1111, 9999).ToString();
            var smsVars    = JsonConvert.SerializeObject(new { code = verifyCode });
            await sms.SendSmsWithRetryAsync(smsVars, value.PhoneNumber, "9900", 3);

            #endregion

            var verifyCodeKey = UserControllerKeys.VerifyCode_Phone + value.PhoneNumber + ":" + verifyCode;

            // 记录验证码,用于提交报名接口校验
            await redis.SetAsync(verifyCodeKey, string.Empty, TimeSpan.FromSeconds(UserControllerKeys.VerifyCode_Expire_Phone));

            // 记录发送验证码的时间,用于下次发送验证码校验间隔时间
            await redis.SetAsync(_lastTimeKey, DateTime.UtcNow.AddHours(8).Ticks.ToString(), null);

            // 叠加发送次数
            await redis.IncrementAsync(dailyLimitKey);

            return(new ApiResult <string>());
        }
Ejemplo n.º 2
0
        public async Task <ApiResult <string> > ApplyFor([FromBody] ApplyForModel value)
        {
            if (!ModelState.IsValid)
            {
                return(new ApiResult <string>(l, BasicControllerCodes.UnprocessableEntity,
                                              ModelErrors()));
            }

            #region 校验邮箱是否重复
            //if (await db.Users.AnyAsync(x => x.Email.Equals(value.Email)))
            //{
            //    return new SingleResult<string>(StatusCodes.Status406NotAcceptable, l["邮箱已被注册"]);
            //}
            #endregion
            #region 校验邮箱验证码
            //if (!string.IsNullOrWhiteSpace(value.EmailVerifyCode))
            //{
            //    try
            //    {
            //        protector.Unprotect(value.EmailVerifyCode);
            //    }
            //    catch
            //    {
            //        return new SingleResult<string>(StatusCodes.Status406NotAcceptable, l["无效的邮箱验证码"]);
            //    }
            //}
            #endregion

            #region 校验手机号是否重复
            if (await db.Users.AnyAsync(x => x.PhoneNumber.Equals(value.PhoneNumber)))
            {
                return(new ApiResult <string>(l, UserControllerCodes.ApplyFor.PhoneNumberExists));
            }
            #endregion
            #region 校验手机验证码
            var PhoneNumberVerifyCodeKey = RedisKeys.VerifyCode_Phone + value.PhoneNumber + ":" + value.PhoneNumberVerifyCode;

            if (await redis.KeyExists(PhoneNumberVerifyCodeKey) == false)
            {
                return(new ApiResult <string>(l, UserControllerCodes.ApplyFor.PhoneNumberVerifyCodeError));
            }

            await redis.Remove(PhoneNumberVerifyCodeKey);

            #endregion

            #region 创建用户
            var user = new AppUser
            {
                UserName             = value.PhoneNumber + "@xcx.com",
                Email                = value.PhoneNumber + "@xcx.com",
                PhoneNumber          = value.PhoneNumber,
                NickName             = value.NickName,
                Gender               = value.Gender,
                Address              = value.Address,
                Birthday             = value.Birthday,
                PhoneNumberConfirmed = true,
                Stature              = value.Stature,
                Weight               = value.Weight,
                Description          = value.Description,
                CreateDate           = DateTime.UtcNow,
                LastUpdateTime       = DateTime.UtcNow
            };

            // set default tenantId
            user.Tenants.Add(new AspNetUserTenant()
            {
                AppTenantId = 1
            });

            var result = await userManager.CreateAsync(user, "123456aA!");

            if (result.Succeeded)
            {
                #region 确认邮箱验证通过
                // 如果填写了邮件验证码,并且验证通过(不通过不会走到这里)
                //if (!string.IsNullOrWhiteSpace(value.EmailVerifyCode))
                //{
                //    user.EmailConfirmed = true;
                //}
                #endregion

                #region 设置角色
                var RoleIDs = db.Roles.Where(x => x.Name.Equals(Roles.Users) || x.Name.Equals(Roles.Star)).Select(x => x.Id).ToList();

                var UserRoles = RoleIDs.Select(x => new AppUserRole()
                {
                    RoleId = x,
                    UserId = user.Id
                });

                db.UserRoles.AddRange(UserRoles);
                #endregion

                #region 图片
                if (value.ImageUrl != null && value.ImageUrl.Count > 0)
                {
                    db.UserFiles.Add(new AspNetUserFile()
                    {
                        Files     = JsonConvert.SerializeObject(value.ImageUrl),
                        FileType  = FileTypes.Image,
                        AppUserId = user.Id
                    });
                }
                #endregion

                #region 视频
                if (!string.IsNullOrWhiteSpace(value.Video))
                {
                    db.UserFiles.Add(new AspNetUserFile()
                    {
                        Files     = value.Video,
                        FileType  = FileTypes.Video,
                        AppUserId = user.Id
                    });
                }
                #endregion

                #region 文档
                if (!string.IsNullOrWhiteSpace(value.Doc))
                {
                    db.UserFiles.Add(new AspNetUserFile()
                    {
                        Files     = value.Doc,
                        FileType  = FileTypes.Doc,
                        AppUserId = user.Id
                    });
                }
                #endregion

                await db.SaveChangesAsync();

                #region 发送报名成功的短信通知
                var smsVars = JsonConvert.SerializeObject(new { nickname = value.NickName });
                await sms.SendSmsWithRetryAsync(smsVars, value.PhoneNumber, "9901", 3);

                #endregion

                return(new ApiResult <string>());
            }

            else
            {
                return(new ApiResult <string>(l, BasicControllerCodes.ExpectationFailed,
                                              JsonConvert.SerializeObject(result.Errors)));
            }
            #endregion
        }