Ejemplo n.º 1
0
        public async Task <ActionResult> ChangeEmail(ChangeUserEmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _applicationManager.UserManager.FindByIdAsync(User.Identity.GetUserId());

                IdentityResult result = await this._applicationManager.UserManager.SetEmailAsync(user.Id, model.Email);

                if (result.Succeeded)
                {
                    SendEmailComfirmation();
                    if (ModelState.IsValid)
                    {
                        TempData["toastrMessage"] = String.Format("Email успешно изменен, на почту выслан запрос на подтверждение");
                        TempData["toastrType"]    = "success";
                    }
                    return(View());
                }
                else
                {
                    AddErrors(result);
                }
            }
            return(View());
        }
Ejemplo n.º 2
0
        public async Task <bool> HandleEmailChangeWithUserConfirmation(ChangeUserEmailViewModel model,
                                                                       SiteUser user,
                                                                       string token,
                                                                       string confirmationUrl,
                                                                       string siteUrl)
        {
            if (!model.EmailIsConfigured)
            {
                Log.LogWarning($"Failed to send email change confirmation email to user with ID {user.Id} because Email not configured.");
                model.SuccessNotification = StringLocalizer["Error: Emails are not configured for this site."];
                return(false);
            }

            await EmailSender.SendEmailChangedConfirmationEmailAsync(
                CurrentSite,
                model.NewEmail,
                model.CurrentEmail,
                StringLocalizer["Confirm email address change"],
                siteUrl,
                confirmationUrl,
                token
                );

            model.SuccessNotification = StringLocalizer["Please check your email inbox, we just sent you a link that you need to click to confirm your account."];
            return(true);
        }
Ejemplo n.º 3
0
        public virtual async Task <IActionResult> ConfirmEmailChange(string userId, string newEmail, string code)
        {
            ModelState.Clear();

            if (userId == null || code == null)
            {
                return(this.RedirectToSiteRoot(CurrentSite));
            }

            var user = await UserManager.FindByIdAsync(userId);

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

            var model = new ChangeUserEmailViewModel
            {
                HasPassword            = await UserManager.HasPasswordAsync(user),
                AccountApproved        = user.AccountApproved,
                CurrentEmail           = user.Email,
                NewEmail               = newEmail,
                AllowUserToChangeEmail = CurrentSite.AllowUserToChangeEmail,
                EmailIsConfigured      = await SiteCapabilities.SupportsEmailNotification(CurrentSite),
                RequireConfirmedEmail  = CurrentSite.RequireConfirmedEmail
            };

            try
            {
                var siteUrl = Url.Action(new UrlActionContext
                {
                    Action     = "Index",
                    Controller = "Home",
                    Protocol   = HttpContext.Request.Scheme
                });

                var success = await EmailChangeHandler.HandleEmailChangeConfirmation(model, user, newEmail, code, siteUrl);

                if (success)
                {
                    this.AlertSuccess(model.SuccessNotification, true);
                }
                else
                {
                    this.AlertDanger(model.SuccessNotification, true);
                }
            }
            catch (Exception ex)
            {
                this.AlertDanger(StringLocalizer["Error - email could not be changed. Contact the site administrator for support."], true);
                Log.LogError(ex, $"Unexpected error occurred changing email address for user ID '{user.Id}'.");
            }

            return(await Index()); // Route back to Index Page, taking toast alerts along
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> ChangeEmail()
        {
            ChangeUserEmailViewModel result = new ChangeUserEmailViewModel();
            var user = await _applicationManager.UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user != null)
            {
                result.Email          = user.Email;
                result.EmailConfirmed = user.EmailConfirmed;
            }
            return(View(result));
        }
Ejemplo n.º 5
0
        // TODO: This should be refactored in task-based way. No PutUser, but ChangeEmail
        // PUT api/User
        //[ResponseType(typeof(User))]
        //public async Task<IHttpActionResult> PutUser(User user)
        public IHttpActionResult PutUser(ChangeUserEmailViewModel changeEmail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userName = User.Identity.GetUserName();

            if (userName.Equals(changeEmail.UserName))
            {
                CommandWorker.ChangeUserEmail(changeEmail);
            }
            else
            {
                return(BadRequest(ModelState));
            }

            return(Ok());

            //ChangeUserEmailViewModel changeEmail = new ChangeUserEmailViewModel()
            //{
            //    UserId = user.UserId,
            //    UserName = user.UserName,
            //    Email = user.Email
            //};            //User cUser = await db.Users.Where(u => u.UserName.Equals(userName)).FirstAsync<Mag14.discitur.Models.User>();

            //if (cUser.UserId != user.UserId)
            //{
            //    return BadRequest();
            //}

            //cUser.Email = user.Email;

            //db.Entry(cUser).State = EntityState.Modified;

            //try
            //{
            //    await db.SaveChangesAsync();
            //}
            //catch (DbUpdateConcurrencyException)
            //{
            //    if (!UserExists(user.UserId))
            //    {
            //        return NotFound();
            //    }
            //    else
            //    {
            //        throw;
            //    }
            //}
            //return Ok(cUser);
        }
Ejemplo n.º 6
0
        public async Task <bool> HandleEmailChangeConfirmation(ChangeUserEmailViewModel model,
                                                               SiteUser user,
                                                               string newEmail,
                                                               string token,
                                                               string siteUrl)
        {
            // do it
            var result = await UserManager.ChangeEmailAsync(user, newEmail, token);

            if (result.Succeeded)
            {
                Log.LogInformation($"User with ID {user.Id} changed email address successfully.");
                model.SuccessNotification = "Email address was changed successfully.";

                if (model.EmailIsConfigured)
                {
                    await EmailSender.SendEmailChangedNotificationEmailsAsync(
                        CurrentSite,
                        String.Empty,       // no need to re-notify new address
                        model.CurrentEmail, // notify old address
                        StringLocalizer["Email address successfully changed"],
                        siteUrl
                        );

                    model.SuccessNotification += " " + StringLocalizer["A notification email will be sent your old email address."];
                }

                model.CurrentEmail = model.NewEmail;
                model.NewEmail     = String.Empty;
            }
            else
            {
                model.SuccessNotification = StringLocalizer["Error - email could not be changed. Contact the site administrator for support."];
                var resultError = $"Error occurred changing email address for user ID '{user.Id}'";
                if (result?.Errors != null && result.Errors.Count() > 0)
                {
                    resultError += result.Errors.First().Description;
                }
                Log.LogError(resultError);
            }

            return(result.Succeeded);
        }
Ejemplo n.º 7
0
        public virtual async Task <IActionResult> ChangeUserEmail()
        {
            var user = await UserManager.FindByIdAsync(HttpContext.User.GetUserId());

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

            var model = new ChangeUserEmailViewModel
            {
                HasPassword            = await UserManager.HasPasswordAsync(user),
                AccountApproved        = user.AccountApproved,
                CurrentEmail           = user.Email,
                AllowUserToChangeEmail = CurrentSite.AllowUserToChangeEmail,
                EmailIsConfigured      = await SiteCapabilities.SupportsEmailNotification(CurrentSite),
                RequireConfirmedEmail  = CurrentSite.RequireConfirmedEmail
            };

            return(View(model));
        }
Ejemplo n.º 8
0
        public virtual async Task <IActionResult> ChangeUserEmail(ChangeUserEmailViewModel model)
        {
            ModelState.Clear();

            var user = await UserManager.FindByIdAsync(HttpContext.User.GetUserId());

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

            var requirePassword = await UserManager.HasPasswordAsync(user);

            model.HasPassword            = requirePassword;
            model.AccountApproved        = user.AccountApproved;
            model.CurrentEmail           = user.Email;
            model.AllowUserToChangeEmail = CurrentSite.AllowUserToChangeEmail;
            model.EmailIsConfigured      = await SiteCapabilities.SupportsEmailNotification(CurrentSite);

            model.RequireConfirmedEmail = CurrentSite.RequireConfirmedEmail;

            if (requirePassword)
            {
                if (string.IsNullOrWhiteSpace(model.Password))
                {
                    ModelState.AddModelError(string.Empty, "Password is required");
                    return(View(model));
                }

                if (!await UserManager.CheckPasswordAsync(user, model.Password))
                {
                    ModelState.AddModelError(string.Empty, "Password not correct.");
                    model.Password = "";
                    return(View(model));
                }
            }

            if (!model.AccountApproved)
            {
                this.AlertDanger(StringLocalizer["This user account is not currently approved."]);
                return(View(model));
            }

            if (!model.AllowUserToChangeEmail)
            {
                this.AlertDanger(StringLocalizer["Site is not configured to allow email changing."]);
                return(View(model));
            }

            // Note - need to check the behaviour of this in related sites mode
            if (await UserManager.EmailExistsInDB(CurrentSite.Id, model.NewEmail))
            {
                this.AlertDanger(StringLocalizer["Error - email could not be changed. Contact the site administrator for support."]);
                return(View(model));
            }

            var token = await UserManager.GenerateChangeEmailTokenAsync(user, model.NewEmail);

            var siteUrl = Url.Action(new UrlActionContext
            {
                Action     = "Index",
                Controller = "Home",
                Protocol   = HttpContext.Request.Scheme
            });

            if (!model.RequireConfirmedEmail)
            {
                // no need for round-trip email confirmation
                try
                {
                    var success = await EmailChangeHandler.HandleEmailChangeWithoutUserConfirmation(model, user, token, siteUrl);

                    if (success)
                    {
                        this.AlertSuccess(model.SuccessNotification, true);
                    }
                    else
                    {
                        this.AlertDanger(model.SuccessNotification, true);
                    }
                }
                catch (Exception ex)
                {
                    this.AlertDanger(StringLocalizer["Error - email could not be changed. Contact the site administrator for support."], true);
                    Log.LogError(ex, $"Unexpected error occurred changing email address for user ID '{user.Id}'.");
                }
            }
            else
            {
                // send token in confirmation email
                try
                {
                    var confirmationUrl = Url.Action(new UrlActionContext
                    {
                        Action     = "ConfirmEmailChange",
                        Controller = "Manage",
                        Values     = new { userId = user.Id.ToString(), newEmail = model.NewEmail, code = token },
                        Protocol   = HttpContext.Request.Scheme
                    });

                    var success = await EmailChangeHandler.HandleEmailChangeWithUserConfirmation(model, user, token, confirmationUrl, siteUrl);

                    if (success)
                    {
                        this.AlertSuccess(model.SuccessNotification, true);
                        return(View("EmailChangeConfirmationSent", model));
                    }
                    else
                    {
                        this.AlertDanger(model.SuccessNotification, true);
                    }
                }
                catch (Exception ex)
                {
                    this.AlertDanger(StringLocalizer["Error - email could not be changed. Contact the site administrator for support."], true);
                    Log.LogError(ex, $"Unexpected error occurred sending email change confirmation for user ID '{user.Id}'.");
                }
            }

            return(await Index());  // Route back to Index Page, taking toast alerts along
        }
Ejemplo n.º 9
0
        public void ChangeUserEmail(ChangeUserEmailViewModel model)
        {
            Guid userId = database.IdMaps.GetAggregateId <User>(model.UserId);

            bus.Send(new ChangeUserEmailCommand(userId, model.Email, model.UserName));
        }