예제 #1
0
        public async Task <string> CheckEmail(string email)
        {
            var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email);

            if (user == null)
            {
                throw new CashSchedulerException("There is no such user", new[] { nameof(email) });
            }

            int allowedVerificationInterval = Convert.ToInt32(Configuration["App:Auth:EmailVerificationTokenLifetime"]);
            var verificationCodeService     = ContextProvider.GetService <IUserEmailVerificationCodeService>();

            var existingVerificationCode = verificationCodeService.GetByUserId(user.Id);

            if (existingVerificationCode != null)
            {
                var difference = DateTime.UtcNow.Subtract(existingVerificationCode.ExpiredDate);

                if (difference.TotalSeconds < 0 &&
                    Math.Abs(difference.TotalSeconds) < allowedVerificationInterval * 60 &&
                    !bool.Parse(Configuration["App:Auth:SkipAuth"]))
                {
                    throw new CashSchedulerException(
                              "We already sent you a code. " +
                              $"You can request it again in: {Math.Abs(difference.Minutes)}:{Math.Abs(difference.Seconds)}",
                              new[] { nameof(email) }
                              );
                }
            }

            var verificationCode = await verificationCodeService.Update(new UserEmailVerificationCode(
                                                                            email.Code(Configuration),
                                                                            DateTime.UtcNow.AddMinutes(allowedVerificationInterval),
                                                                            user
                                                                            ));

            var notificationDelegator = new NotificationDelegator();
            var template = notificationDelegator.GetTemplate(
                NotificationTemplateType.VerificationCode,
                new Dictionary <string, string> {
                { "code", verificationCode.Code }
            }
                );
            await Notificator.SendEmail(user.Email, template);

            await ContextProvider.GetService <IUserNotificationService>().Create(new UserNotification
            {
                Title   = template.Subject,
                Content = template.Body,
                User    = user
            });

            return(email);
        }