public static async Task SeedUsers(DotNetCoreContext context, UserManager <DotNetCoreUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            //creates the default user and roles
            context.Database.EnsureCreated();

            string roleAdmin = "Admin";
            string roleUser  = "******";

            if (await roleManager.FindByNameAsync(roleAdmin) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(roleAdmin));
            }

            if (await roleManager.FindByNameAsync(roleUser) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(roleUser));
            }
            if (userManager.FindByEmailAsync("*****@*****.**").Result == null)
            {
                DotNetCoreUser user = new DotNetCoreUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Enabled  = true,
                    FromDate = DateTime.Now,
                    ToDate   = DateTime.Now.AddYears(1000)
                };
                IdentityResult result = userManager.CreateAsync(user, "Fi$hb0ne").Result;
                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, roleAdmin).Wait();
                }
            }
        }
Exemplo n.º 2
0
        public async Task <ActionResult> Edit(UserViewModel userViewModel)
        {
            DotNetCoreUser user = _context.Users.SingleOrDefault(x => x.Id == userViewModel.Id);

            if (user == null)
            {
                return(NotFound());
            }
            if (ModelState.IsValid)
            {
                try
                {
                    user.UserName = userViewModel.UserName;
                    user.Enabled  = userViewModel.Enabled;
                    user.FromDate = userViewModel.From;
                    user.ToDate   = userViewModel.To;
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException)
                {
                    ModelState.AddModelError("", "Unable to save changes. " +
                                             "Try again, and if the problem persists, " +
                                             "see your system administrator.");
                }
            }
            return(View(userViewModel));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new DotNetCoreUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    //establishes the role of the user
                    _userManager.AddToRoleAsync(user, "User").Wait();

                    _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());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var            hasher  = new PasswordHasher <DotNetCoreUser>();
                DotNetCoreUser user    = null;
                bool           enabled = false;
                try
                {
                    user    = _context.Users.SingleOrDefault(x => x.Email.Equals(Input.Email));
                    enabled = user.Enabled;
                }
                catch (Exception ex)
                {
                    ViewData["Message"] = "Invalid login attempt.";
                    _logger.LogInformation("Something went wrong.Contact the service provider.");
                    return(Page());
                }
                var passwordHashing = hasher.VerifyHashedPassword(user, user.PasswordHash, Input.Password);
                Microsoft.AspNetCore.Identity.SignInResult result = null;
                if (passwordHashing == PasswordVerificationResult.Success)
                {
                    if (enabled)
                    {
                        if (user.ToDate > DateTime.Now)
                        {
                            result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                            _logger.LogInformation("User logged in.");
                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            ViewData["Message"] = "The validity has expired. Please contact the Admin.";
                            _logger.LogInformation("The validity has expired.");
                            return(Page());
                            //return RedirectToPage("/Index");
                        }
                    }
                    else
                    {
                        ViewData["Message"] = "User in not enabled. Please contact the Admin.";
                        _logger.LogInformation("User in not enabled. Please contact the Admin.");
                        return(Page());
                        //return RedirectToPage("/Index");
                    }
                }
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }
            // If we got this far, something failed, redisplay form
            return(Page());
            //return RedirectToPage("/Index");
        }