public static void DefaultUser(ApplicationDbContext db) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var name = AppConfig.DefaultUser; var pwd = AppConfig.DefaultUserPassword; const string adminRole = "Admin"; const string dashboardRole = "Dashboard"; const string investigateRole = "Investigate"; //Create Role Admin if it does not exist var ar = roleManager.FindByName(adminRole); if (ar == null) { ar = new IdentityRole(adminRole); var roleresult = roleManager.Create(ar); } var dr = roleManager.FindByName(dashboardRole); if (dr == null) { dr = new IdentityRole(dashboardRole); var roleresult = roleManager.Create(dr); } var ir = roleManager.FindByName(investigateRole); if (ir == null) { ir = new IdentityRole(investigateRole); var roleresult = roleManager.Create(ir); } var user = userManager.FindByName(name); if (user == null) { user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true }; var createUser = userManager.Create(user, pwd); createUser = userManager.SetLockoutEnabled(user.Id, false); } // Add user admin to Role Admin if not already added var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains("Admin")) { var result = userManager.AddToRole(user.Id, "Admin"); } }
public async Task<ActionResult> Create(AdminVm.CreateUser model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var createUser = await UserManager.CreateAsync(user, model.Password); if (!createUser.Succeeded) { GetAlert(Danger, createUser.Errors.First()); return View(); } GetAlert(Success, "User Created."); return RedirectToAction("Index"); } GetAlert(Danger, "Model State Is Not Valid."); return View(); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var registerResult = await UserManager.CreateAsync(user, model.Password); if (registerResult.Succeeded) { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); if (Request.Url != null) { var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); ViewBag.Link = callbackUrl; } return View("DisplayEmail"); } GetAlert(Danger, registerResult.Errors.First()); } return View(model); }
internal async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); }