public async Task <ActionResult> ResetPassword(string id, UserPasswordResetViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WebApplication2User user = await userManager.FindByIdAsync(id);

                    if (user != null)
                    {
                        IdentityResult removeResult = await userManager.RemovePasswordAsync(user);

                        if (removeResult.Succeeded)
                        {
                            IdentityResult addResult = await userManager.AddPasswordAsync(user, viewModel.Password);

                            if (addResult.Succeeded)
                            {
                                return(RedirectToAction(nameof(Index)));
                            }
                        }
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "There was an error");
                return(View(viewModel));
            }
        }
        public async Task <ActionResult> Delete(string id, bool notused)
        {
            try
            {
                if (!String.IsNullOrEmpty(id))
                {
                    WebApplication2User user = await userManager.FindByIdAsync(id);

                    if (user != null)
                    {
                        string fullname = string.Empty;
                        fullname = user.Surname + ", " + user.FirstName + " " + user.MiddleName;

                        IdentityResult userResult = await userManager.DeleteAsync(user);

                        if (userResult.Succeeded)
                        {
                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            AddErrors(userResult);
                            return(View("Delete", fullname));
                        }
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                //if some weird error is occurring write logs and return to the index view
                return(RedirectToAction("Index"));
            }
        }
        public async Task <ActionResult> ResetPassword(string id)
        {
            UserPasswordResetViewModel viewModel = new UserPasswordResetViewModel();

            if (!String.IsNullOrEmpty(id))
            {
                WebApplication2User user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    //if user is locked out user has to be unlocked before resetting password
                    bool isLockedOut = await userManager.IsLockedOutAsync(user);

                    if (isLockedOut)
                    {
                        return(RedirectToAction("Index"));
                    }

                    viewModel.Id             = user.Id;
                    viewModel.UserName       = user.UserName;
                    viewModel.Surname        = user.Surname;
                    viewModel.FirstName      = user.FirstName;
                    viewModel.MiddleName     = user.MiddleName;
                    viewModel.Email          = user.Email;
                    viewModel.EmployeeNumber = user.EmployeeNumber;

                    return(View(viewModel));
                }
            }

            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> UnLock(string id)
        {
            UserLockoutViewModel viewModel = new UserLockoutViewModel();

            if (!String.IsNullOrEmpty(id))
            {
                WebApplication2User user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    bool isLockedOut = await userManager.IsLockedOutAsync(user);

                    if (!isLockedOut)
                    {
                        return(RedirectToAction("Index"));
                    }

                    viewModel.Id             = user.Id;
                    viewModel.UserName       = user.UserName;
                    viewModel.Surname        = user.Surname;
                    viewModel.FirstName      = user.FirstName;
                    viewModel.MiddleName     = user.MiddleName;
                    viewModel.Email          = user.Email;
                    viewModel.EmployeeNumber = user.EmployeeNumber;

                    return(View(viewModel));
                }
            }

            return(RedirectToAction("Index"));
        }
Пример #5
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null, string loginProvider = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new WebApplication2User {
                    UserName = model.Email, Email = model.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(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"]     = returnUrl;
            ViewData["LoginProvider"] = loginProvider;
            return(View(model));
        }
Пример #6
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new WebApplication2User
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    IsAdmin  = false
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    //_logger.LogInformation(3, "User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> Edit(string id)
        {
            UserEditViewModel viewModel = new UserEditViewModel();

            if (!String.IsNullOrEmpty(id))
            {
                WebApplication2User user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    viewModel.Id             = user.Id;
                    viewModel.UserName       = user.UserName;
                    viewModel.Surname        = user.Surname;
                    viewModel.FirstName      = user.FirstName;
                    viewModel.MiddleName     = user.MiddleName;
                    viewModel.Email          = user.Email;
                    viewModel.EmployeeNumber = user.EmployeeNumber;
                    viewModel.LockoutEnabled = await userManager.IsLockedOutAsync(user);

                    //add all rolenames default to false
                    viewModel.UserRoles = roleManager.Roles.Select(r => new UserRolesViewModel
                    {
                        Id       = r.Id,
                        RoleName = r.Name,
                        HasRole  = false
                    }).ToList();


                    //get all user's roles
                    IList <string> userRolesList = new List <string>();
                    userRolesList = await userManager.GetRolesAsync(user);

                    //populate HasRole boolean field in the view model if the user has the role because we want to display all roles
                    //marking the ones which the user currently has
                    foreach (var userrole in viewModel.UserRoles)
                    {
                        if (userRolesList.Contains(userrole.RoleName))
                        {
                            userrole.HasRole = true;
                        }
                    }

                    //foreach (var role in userRolesList)
                    //{
                    //    foreach (var userrole in viewModel.UserRoles)
                    //    {
                    //        if (role == userrole.RoleName)
                    //        {
                    //            userrole.HasRole = true;
                    //        }
                    //    }
                    //}

                    return(View(viewModel));
                }
            }

            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> Edit(string id, UserEditViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WebApplication2User user = await userManager.FindByIdAsync(id);

                    if (user != null)
                    {
                        user.Surname        = viewModel.Surname;
                        user.FirstName      = viewModel.FirstName;
                        user.MiddleName     = viewModel.MiddleName;
                        user.Email          = viewModel.Email;
                        user.EmployeeNumber = viewModel.EmployeeNumber;

                        IdentityResult userResult = await userManager.UpdateAsync(user);

                        if (userResult.Succeeded)
                        {
                            //changes to roles are not tracked therefore every role has to be checked for updates
                            foreach (var role in viewModel.UserRoles)
                            {
                                if (await userManager.IsInRoleAsync(user, role.RoleName) & !role.HasRole)
                                {
                                    IdentityResult roleResult = await userManager.RemoveFromRoleAsync(user, role.RoleName);

                                    if (!roleResult.Succeeded)
                                    {
                                        AddErrors(roleResult);
                                    }
                                }
                                else if (role.HasRole & !(await userManager.IsInRoleAsync(user, role.RoleName)))
                                {
                                    IdentityResult roleResult = await userManager.AddToRoleAsync(user, role.RoleName);

                                    if (!roleResult.Succeeded)
                                    {
                                        AddErrors(roleResult);
                                    }
                                }
                            }
                        }
                        else
                        {
                            AddErrors(userResult);
                            return(View(viewModel));
                        }
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                return(View(viewModel));
            }
        }
Пример #9
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(WebApplication2User user, EnableAuthenticatorViewModel model)
        {
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            model.SharedKey        = FormatKey(unformattedKey);
            model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
        }
        public async Task <ActionResult> UnLock(string id, UserLockoutViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WebApplication2User user = await userManager.FindByIdAsync(id);

                    if (user != null)
                    {
                        bool isLockedOut = await userManager.IsLockedOutAsync(user);

                        if (!isLockedOut)
                        {
                            return(RedirectToAction("Index"));
                        }

                        IdentityResult userResult = await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddDays(-1));

                        if (userResult.Succeeded)
                        {
                            IdentityResult resetResult = await userManager.ResetAccessFailedCountAsync(user);

                            IdentityResult lockoutResult = await userManager.SetLockoutEnabledAsync(user, false);

                            if (lockoutResult.Succeeded)
                            {
                                return(RedirectToAction(nameof(Index)));
                            }
                        }
                        else
                        {
                            AddErrors(userResult);
                            return(View(viewModel));
                        }
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "There was an error");
                return(View(viewModel));
            }
        }
Пример #11
0
        private async Task InitializeAdministrator(IServiceProvider serviceProvider)
        {
            var            roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var            userManager = serviceProvider.GetRequiredService <UserManager <WebApplication2User> >();
            string         roleName    = "Administrator";
            IdentityResult roleResult;

            //create an administrator role
            var roleExist = await roleManager.RoleExistsAsync(roleName);

            if (!roleExist)
            {
                roleResult = await roleManager.CreateAsync(new IdentityRole(roleName));

                if (roleResult.Succeeded)
                {
                    //add the administrator related claim to the administrator role
                    Claim        claim        = new Claim(PolicyNames.AdministratorPolicy, "");
                    IdentityRole identityRole = await roleManager.FindByNameAsync(roleName);

                    IdentityResult claimResult = await roleManager.AddClaimAsync(identityRole, claim);
                }
            }

            var administratorUser = new WebApplication2User
            {
                UserName  = Configuration.GetSection("UserSettings")["UserName"],
                Surname   = Configuration.GetSection("UserSettings")["UserSurname"],
                FirstName = Configuration.GetSection("UserSettings")["UserFirstname"]
            };

            string UserPassword = Configuration.GetSection("UserSettings")["UserPassword"];
            var    adminUser    = await userManager.FindByNameAsync(Configuration.GetSection("UserSettings")["UserName"]);

            if (adminUser == null)
            {
                IdentityResult identityUser = await userManager.CreateAsync(administratorUser, UserPassword);

                if (identityUser.Succeeded)
                {
                    //add the Administrator role to the user
                    await userManager.AddToRoleAsync(administratorUser, roleName);
                }
            }
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(WebApplication2User user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
        public async Task <ActionResult> Delete(string id)
        {
            string fullname = string.Empty;

            if (!String.IsNullOrEmpty(id))
            {
                WebApplication2User user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    fullname = user.Surname + ", " + user.FirstName + " " + user.MiddleName;
                }
                else
                {
                    return(RedirectToAction(nameof(Index)));
                }
            }
            return(View("Delete", fullname));
        }
Пример #14
0
        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 WebApplication2User {
                    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());
        }
Пример #15
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new WebApplication2User {
                    UserName = Input.Email, Email = Input.Email
                };
                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 = code },
                        protocol: Request.Scheme);

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

                    await _signInManager.SignInAsync(user, isPersistent : false);

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

            // If we got this far, something failed, redisplay form
            return(Page());
        }