Example #1
0
        public void ConfirmEmail(ConfirmEmailModel confirmEmailModel)
        {
            if (confirmEmailModel.UserId == null || confirmEmailModel.UserId == null)
            {
                throw new BusinessException(OperationResultCode.Error, "Wrong Data");
            }

            var id   = new Guid(confirmEmailModel.UserId);
            var user = _userRepository.Get().FirstOrDefault(x => x.Id == id);

            if (user == null || user.EmailConfirmed)
            {
                throw new BusinessException(OperationResultCode.Error, "NotValidToken");
            }
            var result = Sha256Encryption.Sha256HexHashString(user.Email);

            if (result == confirmEmailModel.Code)
            {
                user.EmailConfirmed = true;
                _userRepository.SaveChanges();
            }

            else
            {
                throw new BusinessException(OperationResultCode.Error, "NotValidToken");
            }
        }
Example #2
0
        public IActionResult ConfirmEmail([FromBody] ConfirmEmailModel model)
        {
            try
            {
                var tokenClaims = _userService.Validate(model.token);
                if (tokenClaims == null)
                {
                    return(Unauthorized());
                }

                var userId = tokenClaims.Identity.Name;
                if (model.id.Contains(userId))
                {
                    _userService.ConfirmEmail(model.id);
                    return(Ok());
                }
                else
                {
                    return(Unauthorized(new { message = "Invalid access" }));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new { e }));
            }
        }
Example #3
0
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel body)
        {
            var user = await _userService.GetUserByIdAsync(body.UserId);

            if (user == null)
            {
                _logger.LogWarning($"Invalid email confirmation attempt. User with id {body.UserId} doesn't exist.");
                return(BadRequest());
            }

            if (user.EmailConfirmed)
            {
                return(Ok());
            }

            var result = await _userService.ConfirmEmailAsync(user, body.Token);

            if (result.Succeeded)
            {
                _logger.LogInformation($"User {user.Email} confirmed email address.");
                return(Ok());
            }
            _logger.LogInformation(ControllerExtensions.IdentityErrorBuilder($"Confirmation of email address {body.UserId} failed. Errors: ", result.Errors));
            return(BadRequest());
        }
Example #4
0
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByIdAsync(model.UserId);

            if (user == null)
            {
                //don't reveal if the user does not exist
                return(Ok());
            }

            var result = await _userManager.ConfirmEmailAsync(user, model.Token);

            if (result.Succeeded)
            {
                return(Ok());
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(error.Code, error.Description);
            }
            return(BadRequest(ModelState));
        }
        public async Task <IHttpActionResult> ConfirmEmail(ConfirmEmailModel model)
        {
            if (model.UserId == null || model.Code == null)
            {
                return(InternalServerError());
            }
            IdentityResult result;

            try
            {
                result = await UserManager.ConfirmEmailAsync(model.UserId, model.Code);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                return(InternalServerError()); //TODO: display proper error
            }

            if (result.Succeeded)
            {
                return(Ok());
            }

            // If we got this far, something failed.
            return(InternalServerError()); //TODO: display proper error
        }
        public async Task <IActionResult> ConfirmEmail(ConfirmEmailModel model)
        {
            var user = await _accountManager.GetUserByEmailAsync(model.Email);

            if (user != null)
            {
                if (user.EmailConfirmed)
                {
                    model.IsConfirmed = true;
                    return(View(model));
                }

                var result = await _accountManager.SendConfirmEmailTokenEmailAsync(user);

                if (result)
                {
                    ModelState.Clear();
                    model.IsSuccess = true;
                }
            }
            else
            {
                ModelState.AddModelError("", "There is some issue in sending confirmation link. Please contact us.");
            }

            return(View(model));
        }
Example #7
0
        public async Task <ActionResult> ForgotPasswordCode()
        {
            String status;

            try
            {
                ConfirmEmailModel model = GetModelFromBody <ConfirmEmailModel>();
                // LOWER CASE!
                model.Email = model.Email.ToLower();
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user != null)
                {
                    var verified = await UserManager.VerifyTwoFactorTokenAsync(user.Id, AppUserManager.TWOFACTORPROVIDERS.EMailCode, model.Code);

                    status = verified ? "Success" : "InvalidCode";
                }
                else
                {
                    status = "UserNotFound";
                }
            }
            catch (Exception ex)
            {
                status = ex.Message;
            }
            return(Json(new { Status = status }));
        }
Example #8
0
        public async Task <CustomResponse <string> > ConfirmEmail(ConfirmEmailModel model)
        {
            var infos = new List <string>();

            var user = await _userManager.FindByIdAsync(model.UserId);

            #region Validate User

            if (user == null)
            {
                infos.Add("User not exist.");

                return(new CustomResponse <string> {
                    Message = infos
                });
            }
            ;

            #endregion

            var result = await _userManager.ConfirmEmailAsync(user, model.Token);

            if (!result.Succeeded)
            {
                infos.Add("Failed to confirm email.");
            }

            return(new CustomResponse <string> {
                Succeed = result.Succeeded,
                Data = null,
                Message = infos
            });
        }
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel model)
        {
            try
            {
                var dataJsonBytes = Base64UrlTextEncoder.Decode(model.Token);
                var dataJson      = Encoding.UTF8.GetString(dataJsonBytes);
                var data          = JsonConvert.DeserializeObject <Token>(dataJson);

                await _authenticateService.ConfirmEmail(data.Email, data.Hash);

                var response = new Response {
                    Status = 200
                };
                return(Ok(response));
            }
            catch (Exception e) when(e is InvalidUserException || e is InvalidTokenException)
            {
                return(Ok(new Response {
                    Status = 403, Message = e.Message
                }));
            }
            catch
            {
                return(Ok(new Response {
                    Status = 500, Message = "Internal Server Error."
                }));
            }
        }
Example #10
0
        public async Task <IActionResult> Confirm(ConfirmEmailModel confirmEmailModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(confirmEmailModel.Email);

                if (user == null)
                {
                    ModelState.AddModelError("NotFound", "User with the given email address is not found");
                    return(View(confirmEmailModel));
                }

                var result = await(_userManager as CognitoUserManager <CognitoUser>).ConfirmSignUpAsync(user, confirmEmailModel.EmailVerificationCode, true);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                    return(View(confirmEmailModel));
                }
            }

            return(View(confirmEmailModel));
        }
Example #11
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                throw new InvalidOperationException($"Specify the '{nameof(userId)}' and the '{nameof(code)}' to confirm email.");
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
            }

            var model = new ConfirmEmailModel();

            return(View(model));
        }
Example #12
0
        public IActionResult ConfirmEmail()
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "user/get/" + _tokenDecoder.UserId, HttpMethod.Get);

            if (response.Success)
            {
                UserViewModel userModel = JsonConvert.DeserializeObject <UserViewModel> (response.Data.ToString());

                string encryptedOTP = _mailSender.GanerateAndSendOTP(userModel.Email);

                HttpContext.Session.SetString("OTP", encryptedOTP);

                ConfirmEmailModel model = new ConfirmEmailModel()
                {
                    Id    = userModel.Id,
                    Email = userModel.Email
                };

                return(View(model));
            }
            else
            {
                ErrorViewModel errorModel = new ErrorViewModel()
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", errorModel));
            }
        }
 public ConfirmEmailModelBuilder()
 {
     _model = new ConfirmEmailModel
     {
         UserId = Guid.NewGuid().ToString(),
         Token  = Guid.NewGuid().ToString()
     };
 }
Example #14
0
        public async Task <IActionResult> Post(ConfirmEmailModel model)
        {
            var command = model.Adapt <ConfirmEmailCommand>();

            command.UserId = CurrentUserId;

            return(Ok(await _mediator.Send(command)));
        }
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel confirmation)
        {
            var user = await _store.Read(CreateUserId(confirmation.UserName));

            user.ConfirmationToken = confirmation.Token;
            await _store.Save(user);

            return(Ok());
        }
    public async Task SendConfirmationEmail(FantasyCriticUser user, string link)
    {
        string            emailAddress = user.Email;
        string            emailSubject = "FantasyCritic - Confirm your email address.";
        ConfirmEmailModel model        = new ConfirmEmailModel(user, link);

        var htmlResult = await GetHTMLString("ConfirmEmail.cshtml", model);

        await _emailSender.SendEmailAsync(emailAddress, emailSubject, htmlResult);
    }
        public static async Task SendConfirmationEmail(this IEmailSender emailSender, FantasyCriticUser user, string confirmCode, string baseURL)
        {
            string            emailAddress = user.EmailAddress;
            string            emailSubject = "FantasyCritic - Confirm your email address.";
            ConfirmEmailModel model        = new ConfirmEmailModel(user, confirmCode, baseURL);

            var htmlResult = await GetHTMLString("ConfirmEmail.cshtml", model);

            await emailSender.SendEmailAsync(emailAddress, emailSubject, htmlResult);
        }
Example #18
0
        public async Task <ResponseModel <string> > Register(RegisterModel Input)
        {
            ResponseModel <string> model = new ResponseModel <string>();

            try
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                model.Status = result.Succeeded;
                if (result.Succeeded)
                {
                    model.Data = user.UserName;
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    if (code.Contains("+"))
                    {
                        code = code.Replace("+", " ");
                    }
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { userId = user.Id, code = code },
                    //    protocol: HttpContext.);


                    var dataToConfirm = new ConfirmEmailModel
                    {
                        UserId = user.Id,
                        Code   = code
                    };
                    var encryptedConfirmData = CryptoUtils.Encrypt(JsonConvert.SerializeObject(dataToConfirm));
                    var tt = config.GetSection("AppSetting").Value;
                    //var tt1= config["AppSetting:ConfirmationUrl"];
                    // var ss = config.GetSection("AppSetting");
                    var    token       = config.GetSection("AppSetting:ConfirmationUrl");
                    string callbackUrl = HtmlEncoder.Default.Encode(string.Format(token.Value.ToString(), user.Id, code));
                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='" + callbackUrl + "'>clicking here</a>.");

                    // await _signInManager.SignInAsync(user, isPersistent: false);
                    //  return LocalRedirect(returnUrl);
                }
            }
            catch (Exception ex)
            {
                model.Error  = ex.Message;
                model.Status = false;
                throw;
            }

            return(model);
        }
Example #19
0
        public async Task ConfirmEmail(ConfirmEmailModel confirmEmailModel)
        {
            var result = await _httpClient.PostAsJsonAsync("api/Authorize/ConfirmEmail", confirmEmailModel);

            if (result.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new Exception(await result.Content.ReadAsStringAsync());
            }

            result.EnsureSuccessStatusCode();
        }
        public void GivenGuid_WhenIConfirmEmail_ThenViewHasViewModel()
        {
            ConfirmEmailModel expected = new ConfirmEmailModel();
            Guid expectedIdentifier    = Guid.NewGuid();

            MockAccountManager.Expect(m => m.GenerateConfirmEmailViewModel(expectedIdentifier)).Return(expected);

            ViewResult actual = Target.ConfirmEmail(expectedIdentifier);

            actual.AssertGetViewModel(expected);
        }
Example #21
0
        public async Task <IdentityResult> ConfirmEmail(ConfirmEmailModel data)
        {
            var user = await _userManager.GetUserAsync(User);

            var res = await _userManager.ConfirmEmailAsync(user, data.Token);

            if (res.Succeeded)
            {
                return(await _userManager.AddToRoleAsync(user, Roles.User.ToString()));
            }
            return(res);
        }
Example #22
0
        public async Task <IActionResult> confirmEmail(ConfirmEmailModel model)
        {
            var user = await _userManager.FindByIdAsync(model.UserId);

            var result = await _userManager.ConfirmEmailAsync(user, model.Token);

            if (result.Succeeded)
            {
                return(Ok());
            }
            return(BadRequest());
        }
Example #23
0
        public async Task ConfirmEmail_ConfirmEmailIdentityError_BadRequest()
        {
            UserController controller = new UserController(_loggerMock.Object,
                                                           MockUserService(true, true, true),
                                                           MockEmailService(true),
                                                           _envSettingsMock.Object);
            ConfirmEmailModel confirmEmailModel = CreateConfirmEmailModel();

            var result = await controller.ConfirmEmail(confirmEmailModel);

            Assert.IsType <BadRequestResult>(result);
        }
Example #24
0
        /// <summary>
        /// Generates token for email confirmation
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <(Guid actionGuid, string code)> GenerateEmailConfirmationTokenAsync(User user)
        {
            var codeToSend  = Randomizer.GetRandNumbers(5);
            var resultModel = new ConfirmEmailModel {
                UserId = user.Id, Code = codeToSend
            };
            var actionGuid = Guid.NewGuid();

            _memoryCache.Set(actionGuid, resultModel, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(3)));

            return(actionGuid, codeToSend);
        }
Example #25
0
        public async Task ConfirmEmail_ConfirmSuccess_Ok()
        {
            UserController controller = new UserController(_loggerMock.Object,
                                                           MockUserService(true, true, true, true),
                                                           MockEmailService(true),
                                                           _envSettingsMock.Object);
            ConfirmEmailModel confirmEmailModel = CreateConfirmEmailModel();

            var result = await controller.ConfirmEmail(confirmEmailModel);

            Assert.IsType <OkResult>(result);
        }
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel model)
        {
            var result = await _userService.ConfirmEmail(model.Email, model.Token);

            if (!result.Succeeded)
            {
                _logger.LogInformation("User confirm email validation failed for {Email}", model.Email);
                _logger.LogInformation(JsonConvert.SerializeObject(result));
                return(Unauthorized());
            }

            return(Ok());
        }
        public void Validator_Should_Have_Error_When_UserId_Is_Empty()
        {
            // Arrange
            var confirmEmailModel = new ConfirmEmailModel {
                UserId = string.Empty
            };

            // Act
            var result = _sut.TestValidate(confirmEmailModel);

            // Assert
            result.ShouldHaveValidationErrorFor(ce => ce.UserId);
        }
        public async Task <IActionResult> Confirmemail([FromQuery] ConfirmEmailModel confirmEmailModel)
        {
            try
            {
                await securityService.ConfirmEmailAsync(confirmEmailModel);

                return(Redirect(GlobalConfig.PresentationBaseUrl));
            }
            catch (Exception ex)
            {
                return(HandleExcpetion(ex));
            }
        }
        public async Task ConfirmEmailAsync(ConfirmEmailModel confirmEmailModel)
        {
            var user = await userManager.FindByEmailAsync(confirmEmailModel.Email);

            if (user != null)
            {
                var result = await userManager.ConfirmEmailAsync(user, Base64UrlEncoder.Decode(confirmEmailModel.Token));

                if (!result.Succeeded)
                {
                    var error = result.Errors.FirstOrDefault();
                    throw new ArgumentException(error.Description);
                }
            }
        }
        public async Task <IHttpActionResult> ConfirmEmail(ConfirmEmailModel model)
        {
            bool success = false;
            var  message = "";

            try
            {
                var user = await UserManager.FindByIdAsync(model.UserId);

                if (user != null)
                {
                    var detail = context.UserDetails.Where(a => a.UserID == user.Id).FirstOrDefault();
                    if (detail.UserEmailCode == model.Code)
                    {
                        user.EmailConfirmed = true;
                        var result = await UserManager.UpdateAsync(user);

                        var roleId          = user.Roles.Select(c => c.RoleId).FirstOrDefault();
                        var role            = Util.GetRoleNameById(roleId, context);
                        var alreadyTakePlan = context.UserPlans.Where(x => x.UserID == model.UserId && x.ExpiryDate >= DateTime.UtcNow).FirstOrDefault();
                        if (alreadyTakePlan == null)
                        {
                            FreePlan(user.Id, role);
                        }
                        success = true;
                        message = "Email confirmed successfully.";
                    }
                    else
                    {
                        message = "Invalid code";
                    }
                }
                else
                {
                    message = "Invalid user detail.";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(Ok(new
            {
                Success = success,
                Message = message,
                UserId = model.UserId
            }));
        }