public void Initialize()
        {
            _smtpClientMock = new Mock <SmtpClient>();
            var temapltesPath = new Dictionary <string, string>();
            var pathFolders   = AppContext.BaseDirectory.Split('\\').ToList();

            if (string.IsNullOrWhiteSpace(pathFolders[pathFolders.Count - 1]))
            {
                pathFolders = pathFolders.Take(pathFolders.Count - 1).ToList();
            }
            pathFolders[0] += '\\';
            pathFolders     = pathFolders.Take(pathFolders.Count - 3).ToList();
            pathFolders.Add("MediaShop.WebApi");
            pathFolders.Add("Content");
            pathFolders.Add("Templates");
            var templatesFoldePath = Path.Combine(pathFolders.ToArray());

            temapltesPath.Add("AccountConfirmationEmailTemplate", Path.Combine(templatesFoldePath, "AccountConfirmationEmailTemplate.html"));
            temapltesPath.Add("AccountPwdRestoreEmailTemplate", Path.Combine(templatesFoldePath, "AccountPwdRestoreEmailTemplate.html"));

            IEmailSettingsConfig emailConf = new EmailSettingsConfig("smtp.gmail.com", 587, "*****@*****.**", "ayTYh?2-3xtUB26j", temapltesPath);

            _mailService = new EmailService(_smtpClientMock.Object, emailConf);
            _confirmDto  = new AccountConfirmationDto()
            {
                Token = TokenHelper.NewToken(),
                Email = "*****@*****.**"
            };

            _restoreDto = new AccountPwdRestoreDto()
            {
                Token = TokenHelper.NewToken(),
                Email = "*****@*****.**"
            };
        }
        public async Task <Account> ConfirmRegistrationAsync(AccountConfirmationDto model)
        {
            var result = _tokenValidator.AccountConfirmation.Validate(model);

            if (!result.IsValid)
            {
                throw new ModelValidateException(result.Errors.Select(m => m.ErrorMessage));
            }

            var user = this._factoryRepository.Accounts.GetByEmail(model.Email);

            if (user.IsConfirmed)
            {
                throw new ConfirmedUserException(Resources.ConfirmationError);
            }

            //User registered fo the first time
            if (!user.IsDeleted)
            {
                var profile = await this._factoryRepository.Profiles.AddAsync(new ProfileDbModel())
                              .ConfigureAwait(false);

                profile = profile ?? throw new AddProfileException();

                var settings = await this._factoryRepository.Settings.AddAsync(new SettingsDbModel())
                               .ConfigureAwait(false);

                settings = settings ?? throw new AddSettingsException();

                user.IsConfirmed = true;
                user.ProfileId   = profile.Id;
                user.Profile     = profile;
                user.SettingsId  = settings.Id;
                user.Settings    = settings;
                user.AccountConfirmationToken = TokenHelper.NewToken();

                var confirmedUser = await this._factoryRepository.Accounts.UpdateAsync(user).ConfigureAwait(false);

                confirmedUser = confirmedUser ?? throw new UpdateAccountException();

                return(Mapper.Map <Account>(confirmedUser));
            }

            //User registers after deleting
            user.IsDeleted   = false;
            user.IsConfirmed = true;
            var account = await this._factoryRepository.Accounts.UpdateAsync(user).ConfigureAwait(false);

            return(Mapper.Map <Account>(account));
        }
Beispiel #3
0
        public void ValidWhenProvidedUserIdAndCode()
        {
            // arrange
            var validator       = new ConfirmationValidator();
            var confirmationDto = new AccountConfirmationDto()
            {
                UserId = validUserId,
                Code   = validCode
            };
            // act
            var result = validator.Validate(confirmationDto);

            // assert
            Assert.True(result.IsValid);
        }
Beispiel #4
0
        public void InvalidWhenCodeNotProvided(string code)
        {
            // arrange
            var validator       = new ConfirmationValidator();
            var confirmationDto = new AccountConfirmationDto()
            {
                UserId = validUserId,
                Code   = code
            };
            // act
            var result = validator.Validate(confirmationDto);

            // assert
            Assert.False(result.IsValid);
        }
        public async Task <IActionResult> ConfirmEmail(AccountConfirmationDto confirmationDto)
        {
            var user = await userManager.FindByIdAsync(confirmationDto.UserId);

            if (user == null)
            {
                return(NotFound("User not exist"));
            }
            var result = await userManager.ConfirmEmailAsync(user, confirmationDto.Code);

            if (result.Succeeded)
            {
                return(NoContent());
            }
            else
            {
                return(Forbid());
            }
        }
        public async Task SendConfirmationAsync(AccountConfirmationDto model)
        {
            var htmlBody = await GetTemplateTextAsync("AccountConfirmationEmailTemplate").ConfigureAwait(false);

            htmlBody = string.Format(htmlBody, model.Origin, HttpUtility.UrlEncode(model.Email), HttpUtility.UrlEncode(model.Token));

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Media shop", ((NetworkCredential)_config.Credentials).UserName));
            message.To.Add(new MailboxAddress(model.Email));
            message.Subject = "Email confirmation";
            var builder = new BodyBuilder();

            builder.HtmlBody = htmlBody;

            message.Body = builder.ToMessageBody();

            await ConnectClientAsync().ContinueWith(t => AutenticateClientAsync().ContinueWith(tt => SendEmailAsync(message))).ConfigureAwait(false);
        }
        /// <summary>
        /// Method for send account confirmation
        /// </summary>
        /// <exception cref="EmailTemplatePathException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="CountOfTryToEmailSendException"></exception>
        /// <param name="model">Confirmation model</param>
        public void SendConfirmation(AccountConfirmationDto model)
        {
            var htmlBody = GetTemplateText("AccountConfirmationEmailTemplate");

            htmlBody = string.Format(htmlBody, model.Origin, HttpUtility.UrlEncode(model.Email), HttpUtility.UrlEncode(model.Token));

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Media shop", ((NetworkCredential)_config.Credentials).UserName));
            message.To.Add(new MailboxAddress(model.Email));
            message.Subject = "Email confirmation";
            var builder = new BodyBuilder();

            builder.HtmlBody = htmlBody;

            message.Body = builder.ToMessageBody();
            ConnectClient();
            AutenticateClient();
            SendEmail(message);
        }
Beispiel #8
0
        public IActionResult Confirm([FromBody] AccountConfirmationDto confirmationData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var confirmationStatus = userService.ConfirmAccount(confirmationData.Token).Status;

            switch (confirmationStatus)
            {
            case ConfirmAccountStatus.Ok:
                return(NoContent());

            case ConfirmAccountStatus.TokenNotFound:
                return(NotFound());

            case ConfirmAccountStatus.TokenExpired:
                return(StatusCode(409));

            default:
                return(StatusCode(500));
            }
        }