public IActionResult CreateAdmin([FromBody] UserDto user) { try { if (ModelState.IsValid) { var newUser = new PortfolioIdentityUser { UserName = user.Username, Email = user.EmailAddress, Name = user.Name, Surname = user.Surname, EmailConfirmed = false, LockoutEnabled = false, SecurityStamp = Guid.NewGuid().ToString() }; var roleStore = new RoleStore <IdentityRole>(_context); var adminRole = _context.Roles.FirstOrDefault(r => r.Name == "Admin"); if (!_context.Users.Any(u => u.UserName == newUser.UserName)) { var passwordHasher = new PasswordHasher <PortfolioIdentityUser>(); var hashed = passwordHasher.HashPassword(newUser, user.Password); newUser.PasswordHash = hashed; var userStore = new UserStore <PortfolioIdentityUser>(_context); var claim = new Claim("SuperUser", "True"); userStore.AddToRoleAsync(newUser, "Admin"); userStore.AddClaimsAsync(newUser, new List <Claim> { claim }); _context.Users.Add(newUser); } var result = _context.SaveChangesAsync(); if (result != null) { return(Ok()); } } } catch (Exception ex) { _logger.LogError($"Exception thrown while creating user: {ex}"); } return(BadRequest("Failed to login")); }
public void Seed() { var user = new PortfolioIdentityUser { UserName = "******", Email = "*****@*****.**", Name = "Pieter", Surname = "Myburgh", EmailConfirmed = true, LockoutEnabled = false, SecurityStamp = Guid.NewGuid().ToString() }; var roleStore = new RoleStore <IdentityRole>(_context); IdentityRole adminRole = _context.Roles.FirstOrDefault(r => r.Name == "Admin"); if (adminRole == null) { adminRole = new IdentityRole { Name = "Admin", NormalizedName = "Admin" }; _context.Roles.Add(adminRole); } if (!_context.Users.Any(u => u.UserName == user.UserName)) { var password = new PasswordHasher <PortfolioIdentityUser>(); var hashed = password.HashPassword(user, "P@m180584"); user.PasswordHash = hashed; var userStore = new UserStore <PortfolioIdentityUser>(_context); var claim = new Claim("SuperUser", "True"); userStore.AddToRoleAsync(user, "Admin"); userStore.AddClaimsAsync(user, new List <Claim> { claim }); _context.Users.Add(user); } _context.SaveChanges(); }