Esempio n. 1
0
        public virtual async Task <SendVerificationCodeResult> SendVerificationCodeAsync(SendVerificationCodeDto input)
        {
            var user = await UserManager.FindByEmailAsync(input.EmailAddress);

            if (user == null)
            {
                return(new SendVerificationCodeResult(SendVerificationCodeResultType.InvalidEmail));
            }
            var localizer = ServiceProvider.GetRequiredService(
                typeof(IStringLocalizer <>).MakeGenericType(LocalizationOptions.DefaultResourceType)
                ) as IStringLocalizer;

            var companyName = localizer == null ? "" : localizer["AppName"];
            var userName    = user.Name ?? user.UserName;
            var rnd         = new Random((int)DateTime.Now.Ticks);
            var code        = rnd.Next(100000, 999999);

            var cacheItem = await CodeCache.GetOrAddAsync(user.Id,
                                                          () => Task.FromResult(new VerificationCodeCacheItem(0, code.ToString())),
                                                          () => new DistributedCacheEntryOptions
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
            });

            if (cacheItem.Count >= 5)
            {
                cacheItem.Code = "";
                await CodeCache.SetAsync(user.Id, cacheItem, new DistributedCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddHours(24)
                });

                return(new SendVerificationCodeResult(SendVerificationCodeResultType.MaxCount));
            }

            cacheItem.Code   = code.ToString();
            cacheItem.Count += 1;
            await CodeCache.SetAsync(user.Id, cacheItem, new DistributedCacheEntryOptions()
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
            });

            var subject = string.Format(L["VerificationCodeMailSubject"], userName);
            var body    =
                await PasswordResetTemplateService.RunAsync(new PasswordResetModel(companyName, userName,
                                                                                   code.ToString()));

            try
            {
                await EmailSender.SendAsync(user.Email, subject, body);

                return(new SendVerificationCodeResult(SendVerificationCodeResultType.Success));
            }
            catch (Exception e)
            {
                Logger.LogDebug(e.Message, e);
                Logger.LogDebug(e.StackTrace, e);
                Logger.LogInformation($"Error mail message:{user.Email},{subject},{ body}");
                return(new SendVerificationCodeResult(SendVerificationCodeResultType.Error));
            }
        }