Exemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page());
            }

            this.Input = TSelfExtensions.TrimStringProperties(this.Input);
            var user = await this.userManager.FindByEmailAsync(this.Input.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(this.RedirectToPage("./ResetPasswordConfirmation"));
            }

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

            if (result.Succeeded)
            {
                return(this.RedirectToPage("./ResetPasswordConfirmation"));
            }

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

            return(this.Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page());
            }

            this.Input = TSelfExtensions.TrimStringProperties(this.Input);
            var user = await this.userManager.GetUserAsync(this.User);

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

            var addPasswordResult = await this.userManager.AddPasswordAsync(user, this.Input.NewPassword);

            if (!addPasswordResult.Succeeded)
            {
                foreach (var error in addPasswordResult.Errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.Description);
                }

                return(this.Page());
            }

            await this.signInManager.RefreshSignInAsync(user);

            this.StatusMessage = "Your password has been set.";

            return(this.RedirectToPage());
        }
        public async Task <IActionResult> Search(PostSearchBindingModel model)
        {
            model = TSelfExtensions.TrimStringProperties(model);
            var modelView = await this.postsService.GetPostsAsync(model);

            return(this.PartialView("_SearchResult", modelView));
        }
        public async Task <IActionResult> Edit(PostEditBindingModel model)
        {
            bool canEditPost = await this.postsService.CheckIfIsAllowedToPerformAsync(this.User.Identity.Name, model.Id);

            if (!canEditPost)
            {
                var messageModel = new MessageModel()
                {
                    Type    = MessageType.Warning,
                    Message = Messages.NotAllowedMsg
                };
                TempDataExtensions.Put(this.TempData, Constants.TempDataKey, messageModel);
                return(this.RedirectToAction("Index"));
            }

            if (!this.ModelState.IsValid)
            {
                model.Categories = await this.postsService.GenerateCategoriesSelectListAsync();

                return(this.View(model));
            }

            model = TSelfExtensions.TrimStringProperties(model);
            int id = await this.postsService.EditPostAsync(model);

            var message = new MessageModel()
            {
                Type    = MessageType.Success,
                Message = string.Format(Messages.EntityEditSuccess, nameof(Post), id)
            };

            TempDataExtensions.Put(this.TempData, Constants.TempDataKey, message);

            return(this.RedirectToAction("Details", new { id = id }));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> ChangePassword(UserChangePasswordBindingModel model)
        {
            bool userExists = await this.usersService.CheckIfUserExistsAsync(model.Id);

            if (!userExists)
            {
                return(this.ProcessNullEntity(nameof(Blog.Models.User)));
            }

            var currentUserId = await this.userProfileService.GetUserIdAsync(this.User.Identity.Name);

            if (model.Id == currentUserId)
            {
                var messageModel = new MessageModel()
                {
                    Type    = MessageType.Warning,
                    Message = Messages.NotAllowedMsg
                };
                TempDataExtensions.Put(this.TempData, Constants.TempDataKey, messageModel);
                return(this.RedirectToAction("Index", "Users", new { Area = "Admin" }));
            }

            if (!this.ModelState.IsValid)
            {
                var viewModel = new UserChangePasswordBindingModel()
                {
                    Id = model.Id, Username = model.Username
                };
                return(this.View(viewModel));
            }

            model = TSelfExtensions.TrimStringProperties(model);
            bool succeeded = await this.usersService.ChangePasswordAsync(model);

            if (succeeded)
            {
                var message = new MessageModel()
                {
                    Type    = MessageType.Success,
                    Message = $"The password of user with Username: {model.Username} has been changed successfully."
                };
                TempDataExtensions.Put(this.TempData, Constants.TempDataKey, message);
            }
            else
            {
                var message = new MessageModel()
                {
                    Type    = MessageType.Warning,
                    Message = $"Unexpected error occurred changing password of User with Username: {model.Username}."
                };
                TempDataExtensions.Put(this.TempData, Constants.TempDataKey, message);
            }

            return(this.RedirectToAction("Details", "Users", new { id = model.Id, Area = "Admin" }));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Search(CommentSearchBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.PartialView("_SearchResult", new List <CommentViewModel>()));
            }

            model = TSelfExtensions.TrimStringProperties(model);
            var modelView = await this.commentsService.GetCommentsForPeriodAsync(model);

            return(this.PartialView("_SearchResult", modelView));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = this.Url.Content("/Identity/Account/Login");

            if (this.ModelState.IsValid)
            {
                this.Input = TSelfExtensions.TrimStringProperties(this.Input);
                var user = new User
                {
                    UserName  = this.Input.Username,
                    Email     = this.Input.Email,
                    AvatarUrl = Constants.DefaultAvatarPath
                };
                var result = await this.userManager.CreateAsync(user, this.Input.Password);

                if (result.Succeeded)
                {
                    this.logger.LogInformation("User created a new account with password.");

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

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

                    await this.emailSender.SendEmailAsync(
                        this.Input.Email,
                        "Confirm your email",
                        $"Please confirm your Blogger account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    var messageModel = new MessageModel()
                    {
                        Type    = MessageType.Success,
                        Message = "You have registered successfully. Please log in."
                    };
                    TempDataExtensions.Put(this.TempData, Constants.TempDataKey, messageModel);

                    return(this.LocalRedirect(returnUrl));
                }

                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());
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? this.Url.Content("~/");

            // Get the information about the user from the external login provider
            var info = await this.signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                this.ErrorMessage = "Error loading external login information during confirmation.";
                return(this.RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (this.ModelState.IsValid)
            {
                this.Input = TSelfExtensions.TrimStringProperties(this.Input);
                var user = new User
                {
                    UserName  = this.Input.Username,
                    Email     = this.Input.Email,
                    AvatarUrl = DefaultAvatarPath
                };
                var result = await this.userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await this.userManager.AddLoginAsync(user, info);

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

                        this.logger.LogInformation(
                            "User created an account using {Name} provider.",
                            info.LoginProvider);
                        return(this.LocalRedirect(returnUrl));
                    }
                }

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

            this.LoginProvider = info.LoginProvider;
            this.ReturnUrl     = returnUrl;
            return(this.Page());
        }
        public async Task <IActionResult> Create(PostCreateBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                model.Categories = await this.postsService.GenerateCategoriesSelectListAsync();

                return(this.View(model));
            }

            model = TSelfExtensions.TrimStringProperties(model);
            int id = await this.postsService.CreatePostAsync(model, this.User.Identity.Name);

            var messageModel = new MessageModel()
            {
                Type    = MessageType.Success,
                Message = string.Format(Messages.EntityCreateSuccess, nameof(Post), id)
            };

            TempDataExtensions.Put(this.TempData, Constants.TempDataKey, messageModel);

            return(this.RedirectToAction("Details", new { id = id }));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Edit(CategoryEditBindingModel model)
        {
            bool categoryExists = await this.categoriesService.CheckIfCategoryExistsAsync(model.Id);

            if (!categoryExists)
            {
                return(this.ProcessNullEntity(nameof(Category)));
            }

            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            model = TSelfExtensions.TrimStringProperties(model);
            var categoryNameWithSameOrder = await this.categoriesService
                                            .CategoryWithSameOrderAsync(model.Id, model.Order);

            if (categoryNameWithSameOrder != null)
            {
                this.ModelState.AddModelError(
                    nameof(model.Order),
                    $"{nameof(Category)} \"{categoryNameWithSameOrder}\" already has order \"{model.Order}\".");
                return(this.View(model));
            }

            int id = await this.categoriesService.EditCategoryAsync(model);

            var messageModel = new MessageModel()
            {
                Type    = MessageType.Success,
                Message = string.Format(Messages.EntityEditSuccess, nameof(Category), id)
            };

            TempDataExtensions.Put(this.TempData, Constants.TempDataKey, messageModel);

            return(this.RedirectToAction("Details", "Categories", new { id = id, Area = "Admin" }));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await this.userManager.GetUserAsync(this.User);

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

            var userName = await this.userManager.GetUserNameAsync(user);

            this.Username  = userName;
            this.AvatarUrl = user.AvatarUrl ?? Constants.DefaultAvatarPath;

            if (!this.ModelState.IsValid)
            {
                return(this.Page());
            }

            this.Input = TSelfExtensions.TrimStringProperties(this.Input);
            var email = await this.userManager.GetEmailAsync(user);

            var userId = await this.userManager.GetUserIdAsync(user);

            if (this.Input.Email != email)
            {
                var setEmailResult = await this.userManager.SetEmailAsync(user, this.Input.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new InvalidOperationException(string.Format(Messages.UnexpectedError, nameof(email), nameof(this.User), userId));
                }
            }

            var phoneNumber = await this.userManager.GetPhoneNumberAsync(user);

            if (this.Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await this.userManager.SetPhoneNumberAsync(user, this.Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new InvalidOperationException(string.Format(Messages.UnexpectedError, nameof(this.Input.PhoneNumber), nameof(this.User), userId));
                }
            }

            if (this.Input.AvatarFile != null)
            {
                bool setAvatarSucceeded = await this.userService
                                          .UploadFileInFileSystemAsync(this.Input.AvatarFile, userId);

                if (!setAvatarSucceeded)
                {
                    throw new InvalidOperationException(string.Format(Messages.UnexpectedError, "Avatar", nameof(this.User), userId));
                }
            }

            if (this.User.IsInRole(Constants.Administrator) || this.User.IsInRole(Constants.Author))
            {
                var name = user.FullName;
                if (this.Input.FullName != null && this.Input.FullName != name)
                {
                    bool setNameSucceeded = await this.userService.SetNameAsync(userId, this.Input.FullName);

                    if (!setNameSucceeded)
                    {
                        throw new InvalidOperationException(string.Format(Messages.UnexpectedError, nameof(name), nameof(this.User), userId));
                    }
                }

                var facebookProfileUrl = user.FacebookProfileUrl;
                if (this.Input.FacebookProfileUrl != null && this.Input.FacebookProfileUrl != facebookProfileUrl)
                {
                    bool setFacebookProfileUrlSucceeded = await this.userService
                                                          .SetFacebookProfileUrlAsync(userId, this.Input.FacebookProfileUrl);

                    if (!setFacebookProfileUrlSucceeded)
                    {
                        throw new InvalidOperationException(string.Format(Messages.UnexpectedError, "Facebook profile Url", nameof(this.User), userId));
                    }
                }

                var twitterProfileUrl = user.TwitterProfileUrl;
                if (this.Input.TwitterProfileUrl != null && this.Input.TwitterProfileUrl != twitterProfileUrl)
                {
                    bool setTwitterProfileUrlSucceeded = await this.userService
                                                         .SetTwitterProfileUrlAsync(userId, this.Input.TwitterProfileUrl);

                    if (!setTwitterProfileUrlSucceeded)
                    {
                        throw new InvalidOperationException(string.Format(Messages.UnexpectedError, "Twitter profile Url", nameof(this.User), userId));
                    }
                }

                var instagramProfileUrl = user.InstagramProfileUrl;
                if (this.Input.InstagramProfileUrl != null && this.Input.InstagramProfileUrl != instagramProfileUrl)
                {
                    bool setInstagramProfileUrlSucceeded = await this.userService
                                                           .SetInstagramProfileUrlAsync(userId, this.Input.InstagramProfileUrl);

                    if (!setInstagramProfileUrlSucceeded)
                    {
                        throw new InvalidOperationException(string.Format(Messages.UnexpectedError, "Instagram profile Url", nameof(this.User), userId));
                    }
                }
            }

            await this.signInManager.RefreshSignInAsync(user);

            this.StatusMessage = "Your profile has been updated";
            return(this.RedirectToPage());
        }