Exemplo n.º 1
0
        public async Task <IActionResult> OnGetAsync(string userToEditId)
        {
            UserToEditID = userToEditId;

            HomeSchoolDayBookUser userToEdit = await _userManager.Users.Where(u => u.Id == userToEditId).SingleOrDefaultAsync();

            if (userToEdit == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            EditUser = new EditUser
                       (
                userToEdit.Email,
                userToEdit.AccountCreatedTimeStamp,
                userToEdit.EmailConfirmed,
                userToEdit.EmailConfirmsCount,
                userToEdit.ForgotPasswordEmailsCount,
                userToEdit.PendingEmail,
                userToEdit.NewEmailConfirmsCount
                       );

            return(Page());
        }
Exemplo n.º 2
0
        private static async Task <string> EnsureUser(IServiceProvider serviceProvider, string adminPW, string UserName)
        {
            var userManager = serviceProvider.GetService <UserManager <HomeSchoolDayBookUser> >();

            var user = await userManager.FindByNameAsync(UserName);

            if (user == null)
            {
                user = new HomeSchoolDayBookUser {
                    UserName = UserName, Email = UserName, EmailConfirmed = true
                };
                await userManager.CreateAsync(user, adminPW);
            }

            return(user.Id);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> OnPostResendNewEmailConfirmAsync(string userToEditID)
        {
            UserToEditID = userToEditID;

            HomeSchoolDayBookUser userToEdit = await _userManager.Users.Where(u => u.Id == userToEditID).SingleOrDefaultAsync();

            if (userToEdit == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            if (userToEdit.PendingEmail == null)
            {
                DangerMessage = "This user has no pending email address.";

                return(RedirectToPage());
            }

            if (_context.Users.Any(u => u.Email == userToEdit.PendingEmail))
            {
                DangerMessage = "The new email address already exists in the database.";
                return(RedirectToPage());
            }

            string newEmail         = userToEdit.PendingEmail;
            string changeEmailToken = await _userManager.GenerateChangeEmailTokenAsync(userToEdit, newEmail);


            var callbackUrl = Url.Page(
                "/Account/ConfirmChangedEmail",
                pageHandler: null,
                values: new { area = "Identity", userID = userToEdit.Id, changeEmailToken, newEmail },
                protocol: Request.Scheme);


            await _emailSender.SendEmailAsync(
                userToEdit.PendingEmail,
                "Confirm your HomeSchoolDayBook account new email address.",
                $"Please confirm the new email you provided to HomeSchoolDayBook by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            InfoMessage = "An email has been sent to the new address";

            return(RedirectToPage("./Index"));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnGetAsync(string userToDeleteId)
        {
            if (userToDeleteId == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            UserToDelete = await _userManager.Users.Where(u => u.Id == userToDeleteId).FirstOrDefaultAsync();

            if (UserToDelete == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }
            return(Page());
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

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

            if (ModelState.IsValid)
            {
                var user = new HomeSchoolDayBookUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

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

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

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Exemplo n.º 6
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new HomeSchoolDayBookUser {
                    UserName = Input.Email, Email = Input.Email, AccountCreatedTimeStamp = DateTime.Now
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your HomeSchoolDayBook account email address",
                                                      $"Please confirm the email you provided to HomeSchoolDayBook by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    user.EmailConfirmsCount++;
                    await _userManager.UpdateAsync(user);

                    SuccessMessage = "An email has been sent to the address you provided. " +
                                     "Please click on the link in that email to verify your address. " +
                                     "Once your address has been verified, you may login";

                    return(LocalRedirect(returnUrl));
                }
            }

            // If we got this far, something failed, redisplay form
            DangerMessage = "An error occurred when registering as a new user. Please try again.";

            return(RedirectToPage());
        }
Exemplo n.º 7
0
        public async Task <IActionResult> OnPostResendEmailConfirmAsync(string userToEditID)
        {
            UserToEditID = userToEditID;

            HomeSchoolDayBookUser userToEdit = await _userManager.Users.Where(u => u.Id == userToEditID).SingleOrDefaultAsync();

            if (userToEdit == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            if (await _userManager.IsEmailConfirmedAsync(userToEdit))
            {
                DangerMessage = "User email already confirmed.";

                return(RedirectToPage("./Index"));
            }

            string code = await _userManager.GenerateEmailConfirmationTokenAsync(userToEdit);

            string callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { area = "Identity", userId = userToEdit.Id, code },
                protocol: Request.Scheme);

            await _emailSender.SendEmailAsync(
                userToEdit.Email,
                "Confirm your HomeSchoolDayBook account email address",
                $"Please confirm the email you provided to HomeSchoolDayBook by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            SuccessMessage = "Verification email sent.";

            return(RedirectToPage("./Index"));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> OnPostEditAsync(string userToEditId)
        {
            if (userToEditId == null)
            {
                DangerMessage = "User not found.";
                return(RedirectToPage("./Index"));
            }

            EditUser = new EditUser();

            bool modelDidUpdate = await TryUpdateModelAsync <EditUser>(EditUser, "edituser");

            if (!modelDidUpdate)
            {
                DangerMessage = "Changes did not save correctly. Please try again.";
                return(RedirectToPage());
            }

            HomeSchoolDayBookUser userToEdit = await _userManager.Users.Where(u => u.Id == userToEditId).SingleOrDefaultAsync();

            if (userToEdit == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    bool emailKosher = true;

                    if (EditUser.Email != userToEdit.Email)
                    {
                        string changeEmailToken = await _userManager.GenerateChangeEmailTokenAsync(userToEdit, EditUser.Email);

                        IdentityResult changeEmailResult = await _userManager.ChangeEmailAsync(userToEdit, EditUser.Email, changeEmailToken);

                        IdentityResult changeNameResult = await _userManager.SetUserNameAsync(userToEdit, EditUser.Email);

                        if (!changeEmailResult.Succeeded || !changeNameResult.Succeeded)
                        {
                            emailKosher = false;
                        }
                    }

                    userToEdit.EmailConfirmed            = EditUser.EmailConfirmed;
                    userToEdit.EmailConfirmsCount        = EditUser.EmailConfirmsCount;
                    userToEdit.ForgotPasswordEmailsCount = EditUser.ForgotPasswordEmailCount;
                    userToEdit.PendingEmail          = EditUser.PendingEmail;
                    userToEdit.NewEmailConfirmsCount = EditUser.NewEmailConfirmsCount;

                    IdentityResult updateUserResult = await _userManager.UpdateAsync(userToEdit);

                    if (emailKosher && updateUserResult.Succeeded)
                    {
                        transaction.Commit();
                        _logger.LogInformation("User information modified by admin.");
                        return(RedirectToPage("./Index"));
                    }
                    throw new Exception($"emailKosher = {emailKosher}, updateUserResult.Succeeded = {updateUserResult.Succeeded}");
                }
                catch (Exception ex)
                {
                    DangerMessage = $"An error occurred when modifying user data: {ex.Message}";
                    return(RedirectToPage("./Index"));
                }
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> OnPostAsync(string userToDeleteId)
        {
            if (userToDeleteId == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            UserToDelete = await _userManager.Users.Where(u => u.Id == userToDeleteId).FirstOrDefaultAsync();

            if (UserToDelete == null)
            {
                DangerMessage = "User not found.";

                return(RedirectToPage("./Index"));
            }

            if (UserToDelete.UserName == User.Identity.Name)
            {
                DangerMessage = "You cannot delete yourself from the application.";

                return(RedirectToPage("./Index"));
            }

            List <Entry> userEntries = await _context.Entries
                                       .Where(ent => ent.UserID == userToDeleteId)
                                       .Include(ent => ent.Enrollments)
                                       .Include(ent => ent.SubjectAssignments)
                                       .Include(ent => ent.Grades)
                                       .ToListAsync();

            List <Student> userStudents = await _context.Students
                                          .Where(st => st.UserID == userToDeleteId)
                                          .ToListAsync();

            List <Subject> userSubjects = await _context.Subjects
                                          .Where(su => su.UserID == userToDeleteId)
                                          .ToListAsync();

            List <Enrollment> userEnrollments = userEntries
                                                .SelectMany(ent => ent.Enrollments)
                                                .ToList();

            List <SubjectAssignment> userSubjectAssignments = userEntries
                                                              .SelectMany(ent => ent.SubjectAssignments)
                                                              .ToList();

            List <Grade> userGrades = userEntries
                                      .SelectMany(ent => ent.Grades)
                                      .ToList();

            using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                foreach (Entry entry in userEntries)
                {
                    _context.Remove(entry);
                }

                foreach (Student student in userStudents)
                {
                    _context.Remove(student);
                }

                foreach (Subject subject in userSubjects)
                {
                    _context.Remove(subject);
                }

                foreach (Enrollment enrollment in userEnrollments)
                {
                    _context.Remove(enrollment);
                }

                foreach (SubjectAssignment subjectAssignment in userSubjectAssignments)
                {
                    _context.Remove(subjectAssignment);
                }

                foreach (Grade grade in userGrades)
                {
                    _context.Remove(grade);
                }

                await _context.SaveChangesAsync();

                await _userManager.DeleteAsync(UserToDelete);

                transaction.Commit();
            }

            SuccessMessage = $"User and user data deleted.";
            return(RedirectToPage("./Index"));
        }