public static void TestBody(string callbackUrl, string originatingIpAddress)
        {
            var email = new ConfirmEmailAddress(default(string), callbackUrl, originatingIpAddress);

            Assert.True(email.HtmlBody.Contains(callbackUrl.Replace("&", "&"), StringComparison.Ordinal));
            Assert.True(email.HtmlBody.Contains(originatingIpAddress, StringComparison.OrdinalIgnoreCase));

            Assert.True(email.PlainTextBody.Contains(callbackUrl, StringComparison.Ordinal));
            Assert.True(email.PlainTextBody.Contains(originatingIpAddress, StringComparison.OrdinalIgnoreCase));
        }
Example #2
0
        public override ActionResult Index(ContentModel contentModel)
        {
            var model = new ConfirmEmailAddress(contentModel?.Content);

            model.Metadata = new ViewMetadata
            {
                PageTitle   = model.Name,
                Description = model.Description
            };

            try
            {
                var token  = Request.QueryString["token"];
                var member = FindMemberMatchingThisToken(token);

                if (MemberHasValidEmailToken(member, token))
                {
                    if (RequestedEmailIsNotUsedByAnotherMember(member))
                    {
                        ConfirmNewEmailAddress(member);

                        AddMemberInfoToViewModel(model, member);
                        model.TokenValid = true;
                    }
                    else
                    {
                        model.TokenValid = false;
                    }
                }
                else
                {
                    model.TokenValid = false;
                }
            }
            catch (FormatException)
            {
                model.TokenValid = false;
            }
            return(View("ConfirmEmailAddress", model));
        }
        public static void TestSubject()
        {
            var email = new ConfirmEmailAddress(default(string), default(string), default(string));

            Assert.Equal("Confirm your email address", email.Subject);
        }
        public static void TestTo(string to)
        {
            var email = new ConfirmEmailAddress(to, default(string), default(string));

            Assert.Equal(to, email.To);
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (this.ModelState.IsValid)
            {
                var registrationTokenIsValid =
                    this.registrationTokenValidator.TokenIsValid(this.Input.RegistrationToken);

                if (!registrationTokenIsValid)
                {
                    this.ModelState.AddModelError(
                        $"{nameof(this.Input)}.{nameof(this.Input.RegistrationToken)}",
                        "Registration token not valid.");
                }

                var passwordIsBreached = await this.passwordBreachChecker.PasswordIsBreached(this.Input.Password);

                if (passwordIsBreached)
                {
                    this.ModelState.AddModelError(
                        $"{nameof(this.Input)}.{nameof(this.Input.Password)}",
                        "Password is known to have been compromised in a data breach.");
                }

                if (registrationTokenIsValid && !passwordIsBreached)
                {
                    var user = CreateApplicationUser(this.Input);

                    var result = await this.userManager.CreateAsync(user, this.Input.Password);

                    if (result.Succeeded)
                    {
                        this.logger.LogInformation($"Created user with Id {user.Id}.");

                        this.registrationTokenRepository.DeleteRegistrationToken(this.Input.RegistrationToken);

                        var emailConfirmationToken = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = this.Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { userId = user.Id, code = emailConfirmationToken },
                            protocol: "https");

                        var ipAddress = this.httpContextAccessor.GetOriginatingIpAddress();

                        var confirmationEmail = new ConfirmEmailAddress(this.Input.Email, callbackUrl, ipAddress);

                        this.emailRepository.AddToQueue(confirmationEmail);

                        return(this.RedirectToPage("/RegisterSuccess"));
                    }

                    foreach (var error in result.Errors)
                    {
                        this.ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
Example #6
0
 private static void AddMemberInfoToViewModel(ConfirmEmailAddress model, IMember member)
 {
     model.MemberName   = member.Name;
     model.EmailAddress = member.Email;
 }
Example #7
0
        public virtual ActionResult OpenidRegisterFormSubmit(OpenIdRegistrationViewModel model, bool captchaValid)
        {
            if (!captchaValid)
            {
                ModelState.AddModelError("CAPTCHA", "It seems that you did not type the verification word(s) (CAPTCHA) correctly. Please try again.");
                return(View("OpenidRegister", model));
            }
            if (!ModelState.IsValid)
            {
                return(View("OpenidRegister", model));
            }

            var DecryptedOpenID = Crypto.DecryptStringAES(model.OpenIdClaim, "OpenIDRegistrationFrenzy");
            var validator       = new IsSemiValidURLAttribute();
            var isValid         = validator.IsValid(DecryptedOpenID);

            validator = null;
            if (!isValid)
            {
                //User tried to spoof encryption
                ModelState.AddModelError("OpenID", "There's a problem with the OpenID that you specified.");
                return(View("OpenidRegister", model));
            }

            try
            {
                var db = Current.DB;
                var userNameAvailable = (db.aspnet_Users.Where(u => u.UserName == model.Nickname).FirstOrDefault()) == null;
                if (!userNameAvailable)
                {
                    ModelState.AddModelError("Username", "This username is already taken.");
                    return(View("OpenidRegister", model));
                }

                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Nickname, Membership.GeneratePassword(7, 0), model.EmailAddress);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRoles(model.Nickname, new string[] { RoleNames.ActiveUser, RoleNames.EmailNotConfirmed });
                    AccountProfile.NewUser.Initialize(model.Nickname, true);
                    AccountProfile.NewUser.ReinstateDate = DateTime.MinValue;
                    AccountProfile.NewUser.FullName      = model.FullName.Trim();
                    AccountProfile.NewUser.AboutMe       = (model.AboutMe.IsNullOrEmpty() ? null : HtmlUtilities.Safe(HtmlUtilities.Sanitize(model.AboutMe.Trim())));
                    AccountProfile.NewUser.Save();
                    try
                    {
                        //Check OpenID-whitelist status and add OpenID to whitelist if needed
                        if (WhiteListEnabled)
                        {
                            //If we got here, this means that the user used a valid one-time registration code.
                            var whitelistRecord = new OpenIDWhiteList();
                            whitelistRecord.OpenID    = DecryptedOpenID;
                            whitelistRecord.IsEnabled = true;
                            db.OpenIDWhiteLists.InsertOnSubmit(whitelistRecord);
                            db.SubmitChanges();
                        }

                        var userid = db.aspnet_Users.Where(u => u.UserName == model.Nickname).Single().UserId; // if we fail here, this usually means that we didn't specify a constant ApplicationName in Web.config, so each user has multiple entries in that table.

                        var openid = new UserOpenId();
                        openid.OpenIdClaim = DecryptedOpenID;
                        openid.UserId      = userid;
                        db.UserOpenIds.InsertOnSubmit(openid);
                        db.SubmitChanges();

                        var confirm = new ConfirmEmailAddress();
                        confirm.UserID    = userid;
                        confirm.ConfirmID = Guid.NewGuid();
                        db.ConfirmEmailAddresses.InsertOnSubmit(confirm);
                        db.SubmitChanges();

                        SendEmailVerificationEmail(model.EmailAddress, confirm.ConfirmID);

                        // During beta only
                        try
                        {
                            SendNewUserEmail(userid, model.Nickname);
                        }
                        catch
                        {
                            // No big deal.
                        }


                        FormsAuth.SignIn(model.Nickname, true /* createPersistentCookie */);

                        if (ConfigurationManager.AppSettings["PromptEmailConfirmation"] == "true")
                        {
                            ViewData["email"] = model.EmailAddress;
                            return(View("TimeToValidateYourEmailAddress"));
                        }
                        else
                        {
                            if (model.ReturnURL.HasValue())
                            {
                                return(Redirect(model.ReturnURL));
                            }
                            return(RedirectToAction("Index", "Home"));
                        }
                    }

                    catch
                    {
                        ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                        return(View("OpenidRegister", model));
                    }
                }
                else
                {
                    ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                    return(View("OpenidRegister", model));
                }
            }
            catch
            {
                return(RedirectToAction("InternalServerError", "Error"));
            }
        }