public async Task <IActionResult> VerifyEmail(VerifyEmailViewModel verifyEmail)
        {
            //Models.User user = await _userManager.GetUserAsync(HttpContext.User);

            //if (user != null && user.EmailConfirmed)
            //{
            //    RedirectToAction("Login");
            //}
            //var recaptcha = await _recaptcha.Validate(Request);
            //if (!recaptcha.success)
            //{
            //    ModelState.AddModelError("Recaptcha", "There was an error validating recatpcha. Please try again!");
            //    return View(!ModelState.IsValid ? verifyPhone : new VerifyPhoneViewModel());
            //}

            if (ModelState.IsValid)
            {
                if (await _repository.VerifyEmail(verifyEmail, _userManager) == "success")
                {
                    //return RedirectToAction("ProfileComplete");
                    string Id = (await _userManager.FindByEmailAsync(verifyEmail.Email)).Id;
                    return(View("ProfileComplete", new ProfileCompleteViewModel {
                        Id = Id
                    }));
                }
                else
                {
                    ModelState.AddModelError("VerifyCode", "Invalid Code");
                }

                return(View(verifyEmail));
            }
            return(View(verifyEmail));
        }
Example #2
0
        public ActionResult VerifyEmail(VerifyEmailViewModel verifyEmailViewModel)
        {
            var response = _providerUserMediator.VerifyEmailAddress(User.Identity.Name, verifyEmailViewModel);

            ModelState.Clear();

            switch (response.Code)
            {
            case ProviderUserMediatorCodes.VerifyEmailAddress.FailedValidation:
                response.ValidationResult.AddToModelState(ModelState, string.Empty);
                return(View(verifyEmailViewModel));

            case ProviderUserMediatorCodes.VerifyEmailAddress.InvalidCode:
                SetUserMessage(response.Message.Text, response.Message.Level);
                return(View(verifyEmailViewModel));

            case ProviderUserMediatorCodes.VerifyEmailAddress.OkNotYetMigrated:
                _cookieAuthorizationDataProvider.AddClaim(new Claim(SystemClaimTypes.Role, Roles.VerifiedEmail), HttpContext, User.Identity.Name);
                return(RedirectToRoute(RecruitmentRouteNames.OnBoardingComplete));

            case ProviderUserMediatorCodes.VerifyEmailAddress.Ok:
                _cookieAuthorizationDataProvider.AddClaim(new Claim(SystemClaimTypes.Role, Roles.VerifiedEmail), HttpContext, User.Identity.Name);
                return(RedirectToRoute(RecruitmentRouteNames.RecruitmentHome));

            default:
                throw new InvalidMediatorCodeException(response.Code);
            }
        }
Example #3
0
        public async Task <string> VerifyEmail(VerifyEmailViewModel verifyEmail, UserManager <Models.User> userManager)
        {
            //var user = (from u in _dbContext.Users
            //            where u.PhoneNumber == verifyPhone.Phone
            //            select u).FirstOrDefault();
            var user = await userManager.FindByEmailAsync(verifyEmail.Email);

            //var user = (from u in userManager.Users
            //            where u.Email == verifyEmail.Email
            //            select u).FirstOrDefault();

            if (user != null && user.EmailVerifyCode == verifyEmail.VerifyCode)
            {
                user.EmailConfirmed = true;
                //_dbContext.Update(user);
                await userManager.UpdateAsync(user);

                //_dbContext.SaveChangesAsync();
                return("success");
            }
            else
            {
                return("fail");
            }
        }
 public VerifyEmailFormViewModel(VerifyEmailViewModel existing)
 {
     InvalidSpToken = existing.InvalidSpToken;
     Errors         = existing.Errors;
     LoginEnabled   = existing.LoginEnabled;
     LoginUri       = existing.LoginUri;
 }
Example #5
0
        public async Task <ActionResult> GenerateVerifyCode()
        {
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(User.Identity.GetUserId());

            var _regViewModel = new RegisterViewModel()
            {
                Email = User.Identity.GetUserName()
            };
            var user = UserManager.FindByEmail(_regViewModel.Email);

            var callbackUrl  = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            var emailUtility = new EmailUtility();
            var emailParams  = new Dictionary <String, String>();

            emailParams.Add("UserName", _regViewModel.Email);
            emailParams.Add("ActivationLink", callbackUrl);
            await emailUtility.SendEmail("VerifiyEmail2", _regViewModel.Email, emailParams);

            var model = new VerifyEmailViewModel()
            {
                Mode = "codegenerated"
            };

            return(View("Verify", model));
        }
Example #6
0
        //
        // GET: /Manage/SetupEmail
        public ActionResult SendEmail(VerifyEmailViewModel model)
        {
            var          fromAddress  = new MailAddress("*****@*****.**", "FlySwatter");
            var          toAddress    = new MailAddress("*****@*****.**", "User");
            string       code         = UserManager.GenerateEmailConfirmationToken(User.Identity.GetUserId());
            const string fromPassword = "******";
            const string subject      = "Here's the information you need to confirm you password, if that interests you, but it's not really that impor...";
            string       body         = "Your Code:   \n\n" + code;

            var smtp = new SmtpClient
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }
            //Send the email.
            return(RedirectToAction("VerifyEmail", new { email = model.Email }));
        }
Example #7
0
        public ActionResult Verify()
        {
            var model = new VerifyEmailViewModel()
            {
                Mode = "just like that"
            };

            return(View(model));
        }
Example #8
0
        //
        // GET: /Manage/VerifyEmail
        public ActionResult VerifyEmail(string email)
        {
            var model = new VerifyEmailViewModel()
            {
                Email = email
            };

            return(View(model));
        }
        public IActionResult ReSendVerifyEmail(VerifyEmailViewModel model)
        {
            //** Generate Code from database .....

            //** Send Verification email ....

            //** Return to email sent page

            return(RedirectToAction("VerificationEmailSent", "Account"));
        }
Example #10
0
        public async Task <IHttpActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            var result = await UserManager.ConfirmEmailAsync(model.UserId.TrimAndToLowerCase(), model.Nounce);

            if (!result.Succeeded)
            {
                BadRequest("Unable to verify email");
            }

            return(Ok());
        }
        public void VerifyEmailViewModel_PublicProperties()
        {
            var obj = new VerifyEmailViewModel
            {
                UserId = "userid",
                Nounce = "nounce"
            };

            Assert.AreEqual("userid", obj.UserId);
            Assert.AreEqual("nounce", obj.Nounce);
        }
        public async Task <IHttpActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            var result = await UserManager.ConfirmEmailAsync(model.UserId, model.Nounce);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("EmailVerification", new Exception("Unable to verify email"));
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
        public IActionResult VerifyEmail(VerifyEmailViewModel model)
        {
            var result       = this.homeService.VerifyEmail(model);
            var verification = result["verificating"];
            var userId       = this.HttpContext.Session.GetString("userId");

            if (verification == "Yes")
            {
                var type = result["type"];
                return(this.RedirectToLocal(userId, type));
            }

            this.homeService.SendVerifyCodeToEmail(userId);
            return(this.VerifyEmail());
        }
Example #14
0
        public async Task <IActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            if (string.IsNullOrWhiteSpace(model.ProfileId))
            {
                model.Exception     = new ArgumentNullException(nameof(model.ProfileId));
                model.FailureReason = "Unknown profile.";
                return(View(model));
            }
            string statusMessage = $"E-mail confirmation for profile ID: {model.ProfileId} ";

            if (string.IsNullOrWhiteSpace(model.EmailConfirmationToken))
            {
                model.Exception     = new ArgumentNullException(nameof(model.EmailConfirmationToken));
                model.FailureReason = string.Format(InvalidObjectErrorMessage, "Verification link");
                logger.LogError(model.Exception, $"{statusMessage}FAILED");
                return(View(model));
            }
            var  profileFindTask = profileService.FindByIdAsync(model.ProfileId);
            User profile         = await profileFindTask;

            if (profile == null)
            {
                model.Exception     = new ArgumentNullException(nameof(profile));
                model.FailureReason = string.Format(ObjectNotFoundErrorMessage, "Profile");
                logger.LogWarning($"{statusMessage}FAILED{Environment.NewLine}{model.FailureReason}");
                return(View(model));
            }
            model.ProfileName = profile.ToString();
            if (profile.EmailConfirmed == false)
            {
                var emailConfirmationResult = await profileService.ConfirmEmailAsync(profile, model.EmailConfirmationToken);

                if (!emailConfirmationResult.Succeeded)
                {
                    model.Exception = new ArgumentOutOfRangeException(string
                                                                      .Join(Environment.NewLine, emailConfirmationResult.Errors.Select(e => e.Description)));
                    model.FailureReason = string.Format(InvalidObjectErrorMessage, "Verification link")
                                          + Environment.NewLine + "It has either expired or has been tampered with.";
                    logger.LogWarning(model.Exception, $"{statusMessage}FAILED");
                }
                else
                {
                    logger.LogInformation($"{statusMessage}SUCCEEDED");
                }
                return(View(model));
            }
            return(LocalRedirect("/"));
        }
        public void ValidationFailsTest(string code)
        {
            // Arrange.
            var mediator         = GetMediator();
            var verifyEmailModel = new VerifyEmailViewModel {
                VerificationCode = code
            };

            // Act.
            var response = mediator.VerifyEmailAddress(UserName, verifyEmailModel);

            // Assert.
            response.Should().NotBeNull();
            response.ValidationResult.IsValid.Should().BeFalse();
            response.Code.Should().Be(ProviderUserMediatorCodes.VerifyEmailAddress.FailedValidation);
        }
        public async Task <IActionResult> ResetPassword(string email)
        {
            var result = await _repository.ResetPassword(email, _userManager);

            if (result == "confirm")
            {
                VerifyEmailViewModel verifyEmail = new VerifyEmailViewModel();
                verifyEmail.Email = email;
                return(View("VerifyEmail", verifyEmail));
            }
            else
            {
                ViewData["Message"] = "شماره همراه وارد شده وجود ندارد";
                return(View());
            }
        }
Example #17
0
        public async Task <ActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to confirm.
                IdentityResult result = await UserManager.ConfirmEmailAsync(User.Identity.GetUserId(), model.ConfirmCode);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", new { Message = ManageMessageId.ConfirmEmailSuccess }));
                }
            }
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "Failed to verify Email");
            return(View(model));
        }
Example #18
0
        public MediatorResponse <VerifyEmailViewModel> GetVerifyEmailViewModel(string username)
        {
            var providerUserViewModel = _providerUserProvider.GetUserProfileViewModel(username);

            if (providerUserViewModel == null)
            {
                return(GetMediatorResponse(ProviderUserMediatorCodes.GetVerifyEmailViewModel.NoUserProfile, (VerifyEmailViewModel)null, AuthorizeMessages.NoUserProfile, UserMessageLevel.Info));
            }

            var verifyEmailViewModel = new VerifyEmailViewModel
            {
                EmailAddress = providerUserViewModel.EmailAddress
            };

            return(GetMediatorResponse(ProviderUserMediatorCodes.GetVerifyEmailViewModel.Ok, verifyEmailViewModel));
        }
        public void InvalidCodeTest(string code)
        {
            // Arrange.
            MockProviderUserProvider.Setup(x => x.ValidateEmailVerificationCode(UserName, code)).Returns(false);
            var mediator         = GetMediator();
            var verifyEmailModel = new VerifyEmailViewModel {
                VerificationCode = code
            };

            // Act.
            var response = mediator.VerifyEmailAddress(UserName, verifyEmailModel);

            // Assert.
            response.Should().NotBeNull();
            response.ValidationResult.Should().BeNull();
            response.Code.Should().Be(ProviderUserMediatorCodes.VerifyEmailAddress.InvalidCode);
        }
Example #20
0
        public ActionResult VerifyEmail(string token)
        {
            var viewModel = new VerifyEmailViewModel();

            if (String.IsNullOrEmpty(token) || String.IsNullOrWhiteSpace(token))
            {
                viewModel.PageContent = VerifyEmailViewModel.GetInvalidTokenMessage();
                return(View(viewModel));
            }

            token = token.Trim();
            string tokenId = token.Substring(0, token.Length - 18);

            if (!Regex.IsMatch(tokenId, @"^\d+$"))
            {
                viewModel.PageContent = VerifyEmailViewModel.GetInvalidTokenMessage();
            }

            int truckOwnerId = Convert.ToInt32(tokenId);

            var truckOwner = _context.TruckOwners.SingleOrDefault(t => t.TruckOwnerId == truckOwnerId);

            if (truckOwner == null)
            {
                viewModel.PageContent = VerifyEmailViewModel.GetInvalidTokenMessage();
            }
            else
            {
                var login = _context.Logins.SingleOrDefault(l => l.Email == truckOwner.Email);
                if (login == null || login.EmailActivated)
                {
                    viewModel.PageContent = VerifyEmailViewModel.GetInvalidTokenMessage();
                }
                else
                {
                    login.EmailActivated = true;
                    _context.SaveChanges();
                    viewModel.PageContent = VerifyEmailViewModel.GetSuccessMessage();
                    SendGridEmailService.AccountVerifiedEmail(truckOwner.Email, truckOwner.FirstName + " " + truckOwner.LastName);
                }
            }
            return(View(viewModel));
        }
        public void OnBoardingCompleteAndNotMigratedTest()
        {
            // Arrange.
            var mockUser            = new Fixture().Build <ProviderUser>().Create();
            var providerSetToUseFAA = new Fixture().Build <ProviderViewModel>().With(u => u.IsMigrated, false).Create();

            MockProviderUserProvider.Setup(x => x.GetProviderUser(It.IsAny <string>())).Returns(mockUser);
            MockProviderUserProvider.Setup(x => x.ValidateEmailVerificationCode(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            MockProviderProvider.Setup(x => x.GetProviderViewModel(It.IsAny <int>())).Returns(providerSetToUseFAA);
            var mediator         = GetMediator();
            var verifyEmailModel = new VerifyEmailViewModel {
                VerificationCode = "ABC123"
            };

            // Act.
            var response = mediator.VerifyEmailAddress(UserName, verifyEmailModel);

            // Assert.
            response.Code.Should().Be(ProviderUserMediatorCodes.VerifyEmailAddress.OkNotYetMigrated);
        }
Example #22
0
        public MediatorResponse <VerifyEmailViewModel> ResendVerificationCode(string username)
        {
            var providerUserViewModel = _providerUserProvider.GetUserProfileViewModel(username);

            if (providerUserViewModel == null)
            {
                return(GetMediatorResponse(ProviderUserMediatorCodes.ResendVerificationCode.Error, new VerifyEmailViewModel(), VerifyEmailViewModelMessages.VerificationCodeEmailResentFailedMessage, UserMessageLevel.Error));
            }

            var viewModel = new VerifyEmailViewModel
            {
                EmailAddress = providerUserViewModel.EmailAddress
            };

            _providerUserProvider.ResendEmailVerificationCode(username);

            var message = string.Format(VerifyEmailViewModelMessages.VerificationCodeEmailResentMessage, viewModel.EmailAddress);

            return(GetMediatorResponse(ProviderUserMediatorCodes.ResendVerificationCode.Ok, viewModel, message, UserMessageLevel.Success));
        }
Example #23
0
        public async Task <IActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            var user = await userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(Ok(true));
            }

            if (!string.IsNullOrWhiteSpace(model.Id))
            {
                var userById = await userManager.FindByIdAsync(model.Id);

                if (userById != null && user != null && userById.Email == user.Email)
                {
                    return(Ok(true));
                }
            }

            return(Ok(false));
        }
Example #24
0
        public Dictionary <string, string> VerifyEmail(VerifyEmailViewModel model)
        {
            var code  = model.Code;
            var check = this.context.VerificatedCodes
                        .FirstOrDefault(vf => vf.Code == code);
            var result = new Dictionary <string, string>();

            result.Add("verificating", "No");
            if (check != null)
            {
                var userId = check.UserId;
                var user   = this.context.Users.FirstOrDefault(u => u.Id == userId);
                user.VerifiedOn = DateTime.UtcNow;
                this.context.SaveChanges();
                result["verificating"] = "Yes";
                result.Add("userId", user.Id);
                result.Add("type", user.Type);
            }

            return(result);
        }
        public void ValidCodeTest(string code)
        {
            // Arrange.
            var providerSetToUseFAA = new Fixture().Build <ProviderViewModel>().With(u => u.IsMigrated, true).Create();
            var mockUser            = new Fixture().Build <ProviderUser>().Create();

            MockProviderUserProvider.Setup(x => x.ValidateEmailVerificationCode(UserName, code)).Returns(true);
            MockProviderUserProvider.Setup(x => x.GetProviderUser(UserName)).Returns(mockUser);
            MockProviderProvider.Setup(x => x.GetProviderViewModel(It.IsAny <int>())).Returns(providerSetToUseFAA);
            var mediator         = GetMediator();
            var verifyEmailModel = new VerifyEmailViewModel {
                VerificationCode = code
            };

            // Act.
            var response = mediator.VerifyEmailAddress(UserName, verifyEmailModel);

            // Assert.
            response.Should().NotBeNull();
            response.ValidationResult.Should().BeNull();
            response.Code.Should().Be(ProviderUserMediatorCodes.VerifyEmailAddress.Ok);
        }
Example #26
0
        public async Task <IHttpActionResult> VerifyEmail([FromBody] VerifyEmailViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest());
            }

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

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Example #27
0
        public async Task <IActionResult> VerifyEmail(VerifyEmailViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await GetCurrentUserAsync();

            if (user != null)
            {
                var result = await _userManager.ChangeEmailAsync(user, model.Email, model.Code);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeEmailSuccess }));
                }
            }
            // If we got this far, something failed, redisplay the form
            ModelState.AddModelError(string.Empty, "Failed to verify email address");
            return(View(model));
        }
Example #28
0
        public MediatorResponse VerifyEmailAddress(string username, VerifyEmailViewModel verifyEmailViewModel)
        {
            var result = _verifyEmailViewModelValidator.Validate(verifyEmailViewModel);

            if (!result.IsValid)
            {
                return(GetMediatorResponse(ProviderUserMediatorCodes.VerifyEmailAddress.FailedValidation, verifyEmailViewModel, result));
            }

            if (!_providerUserProvider.ValidateEmailVerificationCode(username, verifyEmailViewModel.VerificationCode))
            {
                return(GetMediatorResponse(ProviderUserMediatorCodes.VerifyEmailAddress.InvalidCode, VerifyEmailViewModelMessages.VerificationCodeEmailIncorrectMessage, UserMessageLevel.Error));
            }

            var user     = _providerUserProvider.GetProviderUser(username);
            var provider = _providerProvider.GetProviderViewModel(user.ProviderId);

            if (!provider.IsMigrated)
            {
                return(GetMediatorResponse(ProviderUserMediatorCodes.VerifyEmailAddress.OkNotYetMigrated));
            }

            return(GetMediatorResponse(ProviderUserMediatorCodes.VerifyEmailAddress.Ok));
        }
        public async Task <IActionResult> Register(RegisterViewModel register)
        {
            //var recaptcha = await _recaptcha.Validate(Request);
            //if (!recaptcha.success)
            //{
            //    ModelState.AddModelError("Recaptcha", "There was an error validating recatpcha. Please try again!");
            //    return View(!ModelState.IsValid ? register : new RegisterViewModel());
            //}

            if (ModelState.IsValid)
            {
                VerifyEmailViewModel verifyEmailAddress = new VerifyEmailViewModel();

                var result = await _repository.AddUserAsync(register, "Participant", _userManager, _signInManager);

                if (result == "added" || result.Contains("verify"))
                {
                    Models.User user = null;

                    switch (result)
                    {
                    case "verify username":
                        user = await _userManager.FindByNameAsync(register.Username);

                        break;

                    case "verify email":
                        user = await _userManager.FindByEmailAsync(register.Email);

                        break;

                    case "added":
                        user = await _userManager.FindByEmailAsync(register.Email);

                        break;
                    }

                    verifyEmailAddress.Email = register.Email;

                    return(View("VerifyEmail", verifyEmailAddress));
                }
                else
                {
                    switch (result)
                    {
                    case "both exist":
                        ModelState.AddModelError("Email", "Email Not Available");
                        ModelState.AddModelError("Username", "Username Not Available");
                        break;

                    case "username exists":
                        ModelState.AddModelError("Username", "Username Not Available");
                        break;

                    case "email exists":
                        ModelState.AddModelError("Email", "Email Not Available");
                        break;
                    }
                }

                return(View());
            }

            return(View());
        }
        public IActionResult VerifyEmail()
        {
            VerifyEmailViewModel model = new VerifyEmailViewModel();

            return(this.Page());
        }