public async Task <ResponseDto> ConfirmEmailAsync(ConfirmEmailDto confirmEmail) { var user = await _userManager.FindByIdAsync(confirmEmail.UserId); if (user == null) { return new ResponseDto { Message = "Korisnik ne postoji", IsSuccess = false } } ; var result = await _userManager.ConfirmEmailAsync(user, Uri.UnescapeDataString(confirmEmail.Token)); if (result.Succeeded) { return new ResponseDto { Message = "Email je uspješno potvrđen.", IsSuccess = true } } ; return(new ResponseDto { Message = "Potvrda Emaila nije uspjela.", IsSuccess = false, Errors = result.Errors.Select(e => e.Description) }); }
public async Task <ApiResponseDto> ConfirmEmail(ConfirmEmailDto confirmEmailParameters) { ApiResponseDto apiResponse = await _authorizeApi.ConfirmEmail(confirmEmailParameters); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); return(apiResponse); }
public async Task Should_HaveErrors_When_EmailConfirmationFailed() { // Arrange var confirmEmailDto = new ConfirmEmailDto { EmailConfirmationToken = "0000", UserId = "1234" }; var userMock = _fixture.UserMock; userMock.SetupGet(m => m.Id).Returns(confirmEmailDto.UserId); var store = new Mock <IUserStore <ApplicationUser> >(); var userManagerMock = new Mock <UserManager <ApplicationUser> >(store.Object, null, null, null, null, null, null, null, null); userManagerMock.Setup(m => m.FindByIdAsync(confirmEmailDto.UserId)).Returns(Task.FromResult(userMock.Object)); userManagerMock.Setup(m => m.ConfirmEmailAsync(userMock.Object, confirmEmailDto.EmailConfirmationToken)) .Returns(Task.FromResult(IdentityResult.Failed())); var sut = new ConfirmEmailService(userManagerMock.Object); // Act await sut.ConfirmEmail(confirmEmailDto); // Assert sut.Status.HasErrors.ShouldBeTrue(); }
public async Task <ApiResponse> ConfirmEmail(ConfirmEmailDto parameters) { if (parameters.UserId == null || parameters.Token == null) { return(new ApiResponse(Status404NotFound, "Пользователя не существует")); } var user = await _userManager.FindByIdAsync(parameters.UserId); if (user == null) { _logger.LogInformation("Пользователя не существует: {0}", parameters.UserId); return(new ApiResponse(Status404NotFound, "Пользователя не существует")); } var token = parameters.Token; var result = await _userManager.ConfirmEmailAsync(user, token); if (!result.Succeeded) { _logger.LogInformation("Ошибка подтверждения пользователя: {0}", string.Join(",", result.Errors.Select(i => i.Description))); return(new ApiResponse(Status400BadRequest, "Ошибка подтверждения пользователя")); } await _signInManager.SignInAsync(user, true); return(new ApiResponse(Status200OK, "Успешно")); }
public async Task <ResultDto> ConfirmEmail(string userid, ConfirmEmailDto model) { var dictionaryResult = new Dictionary <string, string>(); var user = await _userManager.FindByIdAsync(userid); if (user == null) { dictionaryResult.Add("user", "User is not found"); return(new ResultDto { IsSuccessful = false, collectionResult = dictionaryResult, }); } var result = await _userManager.ConfirmEmailAsync(user, model.Code); if (!result.Succeeded) { var errrors = CustomValidator.GetErrorsByIdentityResult(result); return(new ResultDto { IsSuccessful = false, collectionResult = errrors, }); } return(new ResultDto { IsSuccessful = true }); }
public async Task ConfirmEmail(ConfirmEmailDto confirmEmailDto) { try { var userToConfirm = await _userManager.FindByIdAsync(confirmEmailDto.UserId); if (userToConfirm == null) { Status.AddError("A user could not be found with the 'user id' provided"); } if (Status.HasErrors) { return; } var emailConfirm = await _userManager.ConfirmEmailAsync(userToConfirm, confirmEmailDto.EmailConfirmationToken); if (emailConfirm.Succeeded) { return; } Status.AddError("Email confirmation failed."); foreach (var error in emailConfirm.Errors) { Status.AddError(error.Description); } } catch (Exception e) { Status.AddError(e.Message); } }
public async Task Should_Call_ConfirmEmailService() { // Arrange var confirmEmailDto = new ConfirmEmailDto { EmailConfirmationToken = "123yxz", UserId = "001", }; var sut = new AccountController(); var mockConfirmEmailService = new Mock <IConfirmEmailService>(); mockConfirmEmailService.Setup(m => m.Status).Returns(new StatusGenericHandler()); var mockCreateDtoService = new Mock <ICreateDtoService>(); mockCreateDtoService.Setup(m => m.ConfirmEmailDto(confirmEmailDto.UserId, confirmEmailDto.EmailConfirmationToken)).Returns(confirmEmailDto); // Act await sut.ConfirmEmail(confirmEmailDto.UserId, confirmEmailDto.EmailConfirmationToken, mockConfirmEmailService.Object, mockCreateDtoService.Object); // Assert mockConfirmEmailService.Verify(m => m.ConfirmEmail(confirmEmailDto), Times.Once); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailDto confirmEmailDto) { var lang = Request.Headers["language"].ToString(); var errorMessages = new List <string>(); if (confirmEmailDto.userId == null || confirmEmailDto.token == null) { errorMessages.Add(_translator.GetTranslation("ACCOUNT.USER_NOT_FOUND", lang)); return(BadRequest(new { errors = errorMessages })); } var user = await _userManager.FindByIdAsync(confirmEmailDto.userId); if (user == null) { errorMessages.Add(_translator.GetTranslation("ACCOUNT.USER_NOT_FOUND", lang)); return(BadRequest(new { errors = errorMessages })); } var result = await _userManager.ConfirmEmailAsync(user, confirmEmailDto.token); if (result.Succeeded) { return(Ok(true)); } errorMessages.Add(_translator.GetTranslation("ERROR", lang)); return(BadRequest(new { errors = errorMessages })); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailDto confirmEmailDto) { async Task ConfirmEmail() { if (string.IsNullOrEmpty(confirmEmailDto.IdentityId) || string.IsNullOrEmpty(confirmEmailDto.EmailConfirmToken)) { throw new FoodsValidationException("UserId/EmailToken", "", "The user id and email token are required."); } var user = await _userManager.FindByIdAsync(confirmEmailDto.IdentityId); if (user == null) { throw new FoodsValidationException("UserId", "", "Unable to find user"); } var result = await _userManager.ConfirmEmailAsync(user, confirmEmailDto.EmailConfirmToken); CheckIdentityResult(result, "UserId/EmailToken"); result = await _userManager.UpdateSecurityStampAsync(user); CheckIdentityResult(result, "User"); } return(await Execute(ConfirmEmail)); }
public async Task <ApiResponse> ConfirmEmail(ConfirmEmailDto parameters) { if (parameters.UserId == null || parameters.Token == null) { return(new ApiResponse(Status404NotFound, "User does not exist")); } var user = await _userManager.FindByIdAsync(parameters.UserId); if (user == null) { _logger.LogInformation("User does not exist: {0}", parameters.UserId); return(new ApiResponse(Status404NotFound, "User does not exist")); } var token = parameters.Token; var result = await _userManager.ConfirmEmailAsync(user, token); if (!result.Succeeded) { _logger.LogInformation("User Email Confirmation Failed: {0}", string.Join(",", result.Errors.Select(i => i.Description))); return(new ApiResponse(Status400BadRequest, "User Email Confirmation Failed")); } await _signInManager.SignInAsync(user, true); return(new ApiResponse(Status200OK, "Success")); }
public async Task <ApiResponse> ConfirmEmail(ConfirmEmailDto parameters) { if (!ModelState.IsValid) { return(new ApiResponse(400, "User Model is Invalid")); } if (parameters.UserId == null || parameters.Token == null) { return(new ApiResponse(404, "User does not exist")); } var user = await _userManager.FindByIdAsync(parameters.UserId); if (user == null) { _logger.LogInformation("User does not exist: {0}", parameters.UserId); return(new ApiResponse(404, "User does not exist")); } string token = parameters.Token; var result = await _userManager.ConfirmEmailAsync(user, token); if (!result.Succeeded) { _logger.LogInformation("User Email Confirmation Failed: {0}", result.Errors.FirstOrDefault()?.Description); return(new ApiResponse(400, "User Email Confirmation Failed")); } await _signInManager.SignInAsync(user, true); return(new ApiResponse(200, "Success")); }
public async Task <AjaxResult> ConfirmEmail(ConfirmEmailDto dto) { if (!ModelState.IsValid) { return(new AjaxResult("邮箱激活失败:参数不正确", AjaxResultType.Error)); } User user = await _userManager.FindByIdAsync(dto.UserId.ToString()); if (user == null) { return(new AjaxResult("邮箱激活失败:用户不存在", AjaxResultType.Error)); } if (user.EmailConfirmed) { return(new AjaxResult("邮箱已激活,操作取消", AjaxResultType.Info)); } string code = UrlBase64ReplaceChar(dto.Code); IdentityResult result = await _userManager.ConfirmEmailAsync(user, code); try { ServiceProvider.GetService <IOnlineUserCache>()?.Remove(user.UserName); } catch (Exception) { } return(result.ToOperationResult().ToAjaxResult()); }
public async Task Should_UseUserManager_ToConfirmEmail() { // Arrange var confirmEmailDto = new ConfirmEmailDto { EmailConfirmationToken = "0000", UserId = "1234" }; var userMock = _fixture.UserMock; userMock.SetupGet(m => m.Id).Returns(confirmEmailDto.UserId); var store = new Mock <IUserStore <ApplicationUser> >(); var userManagerMock = new Mock <UserManager <ApplicationUser> >(store.Object, null, null, null, null, null, null, null, null); userManagerMock.Setup(m => m.FindByIdAsync(confirmEmailDto.UserId)).Returns(Task.FromResult(userMock.Object)); userManagerMock.Setup(m => m.ConfirmEmailAsync(userMock.Object, confirmEmailDto.EmailConfirmationToken)) .Returns(Task.FromResult(IdentityResult.Success)); var sut = new ConfirmEmailService(userManagerMock.Object); // Act await sut.ConfirmEmail(confirmEmailDto); // Assert userManagerMock.Verify(m => m.ConfirmEmailAsync(userMock.Object, confirmEmailDto.EmailConfirmationToken), Times.Once); }
public async Task <ConfirmationEmailResponseDto> ConfirmEmail(ConfirmEmailDto confirmEmailDto) { var user = await _userManager.Users.FirstOrDefaultAsync(x => x.EmailConfirmationToken == confirmEmailDto.ConfirmationToken); var confirmationEmailResponse = await _userManager.ConfirmEmail(_userStore, user); return(confirmationEmailResponse); }
public async Task<IActionResult> Confirm([FromBody] ConfirmEmailDto confirmEmailDto) { var confirmationResult =await _emailConfirmationManager.ConfirmEmailAsync(confirmEmailDto); return StatusCode(confirmationResult, new { Message = "The email has been confirmed" }); }
public async Task <IActionResult> ReSendConfirmationEmail([FromBody] ConfirmEmailDto confirmEmailDto) { var confirmationToken = await _confirmAccountService.SendEmailConfirmationEmailByToken(confirmEmailDto.ConfirmationToken); if (confirmationToken == null) { return(BadRequest()); } _logger.LogInformation($"User with confirmation token: {confirmEmailDto.ConfirmationToken} - resent email confirmation message"); return(NoContent()); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailDto confirmEmailDto) { var result = await _confirmAccountService.ConfirmEmail(confirmEmailDto); if (!result.Succedeed) { _logger.LogInformation($"User with confirmation token: {confirmEmailDto.ConfirmationToken} has tried to activate account"); return(BadRequest(result)); } _logger.LogInformation($"User with confirmation token: {confirmEmailDto.ConfirmationToken} has activated account"); return(NoContent()); }
public async Task <Message> ConfirmEmail(ConfirmEmailDto input) { bool isSuccess = false; string message = string.Empty; var user_mapping = new ApplicationUserDto(); if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(input.Email); if (user == null || input.accessToken == null) { isSuccess = false; message = message + "User is not valid"; } else { if (user.EmailConfirmed) { isSuccess = true; message = message + "Your Email is already confirmed. "; } else { var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(input.accessToken)); user.IsActive = true; user.EmailConfirmed = true; //arti var userToken = await _userManager.ConfirmEmailAsync(user, code); if (userToken.Succeeded) { await _userManager.UpdateAsync(user); //arti isSuccess = true; message = message + "Your Email is confirmed. "; } else { isSuccess = false; message = message + "Invalid Token "; } } } } return(new Message() { isSuccess = isSuccess, message = message, jsonObj = user_mapping, }); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailDto dto) { ConfirmEmailDtoValidator validator = new ConfirmEmailDtoValidator(); ValidationResult result = await validator.ValidateAsync(dto); if (result.IsValid) { var user = await _userManager.FindByIdAsync(dto.UserId); if (user == null) { return(NotFound()); } await using (var transaction = await _dbContext.Database.BeginTransactionAsync()) { try { if (await _userManager.ConfirmEmailAsync(user, dto.Token) != IdentityResult.Success) { throw new DbUpdateException(); } #region UpdateSecurity var oldSecurityStamp = user.SecurityStamp; if (await _userManager.UpdateSecurityStampAsync(user) != IdentityResult.Success) { throw new DbUpdateException(); } if (await _userManager.ReplaceClaimAsync(user, new Claim(ClaimTypes.Sid, oldSecurityStamp), new Claim(ClaimTypes.Sid, user.SecurityStamp)) != IdentityResult.Success) { throw new DbUpdateException(); } #endregion await transaction.CommitAsync(); } catch (DbUpdateException) { await transaction.RollbackAsync(); throw; } } return(NoContent()); } return(BadRequest(result.Errors)); }
public async Task ConfirmEmail(ConfirmEmailDto input) { var user = await _userManager.FindByIdAsync(input.UserId); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{input.UserId}'."); } var result = await _userManager.ConfirmEmailAsync(user, input.Code); if (!result.Succeeded) { throw new ApplicationException(string.Join('\n', result.Errors)); } }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailDto model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _userService.ConfirmEmail(model); if (result.Message != ApiResultMessages.Ok) { return(BadRequest(result)); } return(Ok(result)); }
public void Should_ReturnTrue_WhenRequiredInfo_IsProvided() { // Arrange var confirmEmailDto = new ConfirmEmailDto { UserId = "1234", EmailConfirmationToken = "00001" }; var emailValidator = new ConfirmEmailValidator(); // Act var validatorResult = emailValidator.Validate(confirmEmailDto); // Assert validatorResult.IsValid.ShouldBeTrue(); }
public void Should_ReturnFalse_WhenRequiredInfo_IsNotProvided(string userId, string emailConfirmationToken) { // Arrange var confirmEmailDto = new ConfirmEmailDto() { UserId = userId, EmailConfirmationToken = emailConfirmationToken }; var emailValidator = new ConfirmEmailValidator(); // Act var validatorResult = emailValidator.Validate(confirmEmailDto); // Assert validatorResult.IsValid.ShouldBeFalse(); }
public async Task Should_Register_And_Confirm_Email() { // Arrange var registerDto = new UserRegisterDto { Email = "*****@*****.**", UserName = "******", Password = UserSeedData.ValidPassword, GivenName = "Ludmilla", Surname = "Schneider", ClientUri = "http://localhost:4200", }; registerDto.StakeholderGroupIds.Add(SectionSeedData.Volunteers.Id); HttpClient client = _unAuthenticatedServer .CreateClient(); // Act HttpResponseMessage responseMessage = await client .PostAsync(ApiEndpoints.AuthController.Register(), BuildStringContent(registerDto)); // Assert responseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent); _fakeSmtpServer.ReceivedEmailCount.Should().Be(1); // Arrange var queryParameters = _fakeSmtpServer.ReceivedEmail.First().MessageParts.First().BodyData.Split("?token=")[1].Split("&email="); var confirmEmailToken = queryParameters[0]; var email = queryParameters[1].Split('"')[0]; var confirmEmailDto = new ConfirmEmailDto { Email = email, Token = confirmEmailToken }; // Act HttpResponseMessage resetResponseMessage = await client .PostAsync(ApiEndpoints.AuthController.ConfirmEmail(), BuildStringContent(confirmEmailDto)); // Assert resetResponseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent); }
public async Task <ActionResult> ConfirmEmail(ConfirmEmailDto confirmEmail) { var user = await _userManager.FindByIdAsync(confirmEmail.userid); if (user == null) { return(Unauthorized("Username not Found")); } var confirm = await _userManager.ConfirmEmailAsync(user, confirmEmail.token); if (confirm.Succeeded) { return(Ok()); } return(BadRequest("Unable to confirm email")); }
public async Task Should_HaveErrors_WhenRequiredInfo_NotProvided(string userId, string emailConfirmationToken) { // Arrange var confirmEmailDto = new ConfirmEmailDto { EmailConfirmationToken = emailConfirmationToken, UserId = userId }; var store = new Mock <IUserStore <ApplicationUser> >(); var userManagerMock = new Mock <UserManager <ApplicationUser> >(store.Object, null, null, null, null, null, null, null, null); var sut = new ConfirmEmailService(userManagerMock.Object); // Act await sut.ConfirmEmail(confirmEmailDto); // Assert sut.Status.HasErrors.ShouldBeTrue(); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailDto model) { var user = await _userManager.FindByIdAsync(model.UserId); if (user == null) { return(NotFound()); } var pendingEmail = await _userManager.GetPendingEmailAsync(user); if (string.IsNullOrWhiteSpace(pendingEmail)) { return(this.IdentityFailure("NoPendignEmail", "There is no email address change to confirm.")); } if (await _userManager.FindByEmailAsync(pendingEmail) != null) { return(this.IdentityFailure("EmailInUse", "Email already in use.")); } var tokenResponse = await _userManager.VerifyEmailConfirmationToken(user, model.Code); if (!tokenResponse.Succeeded) { return(this.IdentityFailure(tokenResponse)); } if (!await _userManager.CheckPasswordAsync(user, model.Password)) { return(this.IdentityFailure("IncorrectPasword", "Incorrect password.")); } var result = await _userManager.ConfirmEmailAsync(user, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(Ok(await GenerateSignInResultDtoAsync(user))); } return(this.IdentityFailure(result)); }
//[AllowAnonymous] public async Task <IActionResult> ConfirmEmail(string userid, [FromBody] ConfirmEmailDto model) { if (!ModelState.IsValid) { var errrors = CustomValidator.GetErrorsByModel(ModelState); return(BadRequest(errrors)); } var result = await _accountService.ConfirmEmail(userid, model); if (result.IsSuccessful == false) { if (result.collectionResult.ContainsKey("user")) { return(BadRequest(new { invalid = "User is not found" })); } return(BadRequest(result.collectionResult)); } return(Ok()); }
public async Task ConfirmEmail_WithInvaildParameters_Returns404() { // Arange var confirmEmailDto = new ConfirmEmailDto(); confirmEmailDto.Token = null; confirmEmailDto.UserId = null; // Act var response = await _accountManager .ConfirmEmail(confirmEmailDto); // Assert Assert.That(response.StatusCode, Is.EqualTo(404)); }
public void Should_Map() { // Arrange var dto = new ConfirmEmailDto { Email = UserTestSeedData.Performer.Email, Token = "token%2B" }; var expectedCommand = new ConfirmEmail.Command { Email = dto.Email, Token = "token+" }; // Act ConfirmEmail.Command command = _mapper.Map <ConfirmEmail.Command>(dto); // Assert command.Should().BeEquivalentTo(expectedCommand); }