public static void Initialize(MacheteContext DB) { IdentityResult ir; var rm = new RoleManager<IdentityRole> (new RoleStore<IdentityRole>(DB)); ir = rm.Create(new IdentityRole("Administrator")); ir = rm.Create(new IdentityRole("Manager")); ir = rm.Create(new IdentityRole("Check-in")); ir = rm.Create(new IdentityRole("PhoneDesk")); ir = rm.Create(new IdentityRole("Teacher")); ir = rm.Create(new IdentityRole("User")); ir = rm.Create(new IdentityRole("Hirer")); // This role is used exclusively for the online hiring interface var um = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(DB)); var user = new ApplicationUser() { UserName = "jadmin", IsApproved = true, Email = "[email protected]" }; ir = um.Create(user, "ChangeMe"); ir = um.AddToRole(user.Id, "Administrator"); //Default Administrator, edit to change ir = um.AddToRole(user.Id, "Teacher"); //Required to make tests work DB.Commit(); }
private void InitDefaultUsersAndRoles(UserManager<QuestionsAnswersUser> userManager, RoleManager<IdentityRole> roleManager) { if (roleManager.FindByName("admin") == null) { roleManager.Create(new IdentityRole("admin")); } if (roleManager.FindByName("user") == null) { roleManager.Create(new IdentityRole("user")); } if (userManager.FindByName("admin") == null) { var user = new QuestionsAnswersUser {UserName = "admin"}; var result = userManager.Create(user, "adminadmin"); if (result.Succeeded) { userManager.AddToRole(user.Id, "admin"); } } userManager.Users.Where(u => !u.Roles.Any()).ToList().ForEach(u => userManager.AddToRole(u.Id, "user")); }
private void AddPermisionToADM(ApplicationDbContext db) { var userManarge = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var user = userManarge.FindByName("[email protected]"); if (!userManarge.IsInRole(user.Id, "View")) { userManarge.AddToRole(user.Id, "View"); } if (!userManarge.IsInRole(user.Id, "Create")) { userManarge.AddToRole(user.Id, "Create"); } if (!userManarge.IsInRole(user.Id, "Edit")) { userManarge.AddToRole(user.Id, "Edit"); } if (!userManarge.IsInRole(user.Id, "Delete")) { userManarge.AddToRole(user.Id, "Delete"); } if (!userManarge.IsInRole(user.Id, "Adm")) { userManarge.AddToRole(user.Id, "Adm"); } }
/// <summary> /// Checks for the three roles - Admin, Employee and Complainant and /// creates them if not present /// </summary> public static void InitializeRoles() { // Access the application context and create result variables. ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); RoleManager roleMgr = new RoleManager(); if (!roleMgr.RoleExists("Administrator")) { roleMgr.Create(new ApplicationRole { Name = "Administrator" }); } if (!roleMgr.RoleExists("Employee")) { roleMgr.Create(new ApplicationRole { Name = "Employee" }); } if (!roleMgr.RoleExists("Complainant")) { roleMgr.Create(new ApplicationRole { Name = "Complainant" }); } if (!roleMgr.RoleExists("Auditor")) { roleMgr.Create(new ApplicationRole { Name = "Auditor" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "Administrator", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Admin123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Administrator"); } appUser = new ApplicationUser { UserName = "Auditor", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Auditor123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Auditor")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Auditor"); } }
internal static void SeedAdmin(TechSupportDbContext context) { const string AdminEmail = "[email protected]"; const string AdminPassword = "qweqwe"; if (context.Users.Any(u => u.Email == AdminEmail)) { return; } var userManager = new UserManager<User>(new UserStore<User>(context)); var admin = new User { FirstName = "Pesho", LastName = "Admina", Email = AdminEmail, Address = "Sopot", UserName = AdminEmail }; userManager.Create(admin, AdminPassword); userManager.AddToRole(admin.Id, GlobalConstants.AdminRole); userManager.AddToRole(admin.Id, GlobalConstants.ModeratorRole); userManager.AddToRole(admin.Id, GlobalConstants.DefaultRole); context.SaveChanges(); }
internal static void SeedModerator(TechSupportDbContext context) { const string moderatorEmail = "[email protected]"; const string mderatorPassword = "moderator123456"; if (context.Users.Any(u => u.Email == moderatorEmail)) { return; } var userManager = new UserManager<User>(new UserStore<User>(context)); var admin = new User { FirstName = "Gosho", LastName = "Moderatora", Email = moderatorEmail, Address = "Sopot", UserName = moderatorEmail }; userManager.Create(admin, mderatorPassword); userManager.AddToRole(admin.Id, GlobalConstants.ModeratorRole); userManager.AddToRole(admin.Id, GlobalConstants.DefaultRole); context.SaveChanges(); }
internal static void SeedAdmin(SciHubDbContext context) { const string adminUserName = "theDecider666"; const string adminPassword = "deciderd"; if (context.Users.Any(u => u.UserName == adminUserName)) { return; } var userManager = new UserManager<User>(new UserStore<User>(context)); var admin = new User { UserName = adminUserName, Email = "[email protected]", FirstName = "Admin", LastName = "Adminos", Avatar = UserDefaultPictureConstants.Female, Gender = Gender.Female, About = "I am the Decider!" }; userManager.Create(admin, adminPassword); userManager.AddToRole(admin.Id, UserRoleConstants.Admin); userManager.AddToRole(admin.Id, UserRoleConstants.Default); context.SaveChanges(); }
internal static void SeedAdmin(GiftBoxDbContext context) { const string AdminEmail = "[email protected]"; const string AdminPassword = "123456"; if (context.Users.Any(u => u.Email == AdminEmail)) { return; } var userManager = new UserManager<User>(new UserStore<User>(context)); var admin = new User { FirstName = "Adrian", UserRole = "Admin", LastName = "Apostolov", Email = AdminEmail, UserName = "Adrian.Apostolov", PhoneNumber = "0889972697", ImageUrl = GlobalConstants.DefaultUserPicture, }; userManager.Create(admin, AdminPassword); userManager.AddToRole(admin.Id, GlobalConstants.AdminRole); userManager.AddToRole(admin.Id, GlobalConstants.UserRole); userManager.AddToRole(admin.Id, GlobalConstants.HomeAdministrator); context.SaveChanges(); }
private static void SetupRolesAndUsers(DbContext context) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // add roles if (!roleManager.RoleExists(Role.Guest.ToString())) roleManager.Create(new IdentityRole(Role.Guest.ToString())); if (!roleManager.RoleExists(Role.Supplier.ToString())) roleManager.Create(new IdentityRole(Role.Supplier.ToString())); if (!roleManager.RoleExists(Role.Deactivated.ToString())) roleManager.Create(new IdentityRole(Role.Deactivated.ToString())); if (!roleManager.RoleExists(Role.User.ToString())) roleManager.Create(new IdentityRole(Role.User.ToString())); var adminRole = roleManager.FindByName(Role.Admin.ToString()); if (adminRole == null) { adminRole = new IdentityRole(Role.Admin.ToString()); roleManager.Create(adminRole); } #if DEBUG //add admin user var admin = userManager.Find(Admin_User, Admin_Pass); if (admin == null) { admin = new ApplicationUser { UserName = Admin_User, Email = Admin_Mail, EmailConfirmed = true }; var result = userManager.Create(admin, Admin_Pass); // TODO: verify returned IdentityResult userManager.AddToRole(admin.Id, Role.Admin.ToString()); result = userManager.SetLockoutEnabled(admin.Id, false); } var rolesForUser = userManager.GetRoles(admin.Id); if (!rolesForUser.Contains(adminRole.Name)) { var result = userManager.AddToRole(admin.Id, adminRole.Name); } //add normal user if (userManager.Find("[email protected]", "1q2w3e4r") == null) { var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", EmailConfirmed = true }; userManager.Create(user, "1q2w3e4r"); // TODO: verify returned IdentityResult userManager.AddToRole(user.Id, Role.User.ToString()); } #endif }
public static void Seed(ApplicationDbContext context) { UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context); UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore); RoleStore<Role> roleStore = new RoleStore<Role>(context); RoleManager<Role> roleManager = new RoleManager<Role>(roleStore); if (!roleManager.RoleExists("Admin")) roleManager.Create(new Role { Name = "Admin" }); if (!roleManager.RoleExists("User")) roleManager.Create(new Role { Name = "User" }); IdentityResult result = null; ApplicationUser user1 = userManager.FindByName("[email protected]"); if (user1 == null) { user1 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" }; } result = userManager.Create(user1, "asdfasdf"); if (!result.Succeeded) { string error = result.Errors.FirstOrDefault(); throw new Exception(error); } userManager.AddToRole(user1.Id, "Admin"); user1 = userManager.FindByName("[email protected]"); ApplicationUser user2 = userManager.FindByName("[email protected]"); if (user2 == null) { user2 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" }; } result = userManager.Create(user2, "asdfasfd"); if (!result.Succeeded) { string error = result.Errors.FirstOrDefault(); throw new Exception(error); } userManager.AddToRole(user2.Id, "User"); user2 = userManager.FindByName("[email protected]"); }
//Método para quemar el super usuario del sistema: private void CheckSuperUser() { //me conecto all db: var userContext = new ApplicationDbContext(); //Aqui controlo los usuarios: var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var db = new DemocracyContext(); this.CheckRole("Admin", userContext); this.CheckRole("User", userContext); //validar si el usuario existe en la tabla user: var user = db.Users.Where(u=>u.userName.ToLower().Equals("[email protected]")).FirstOrDefault(); if (user == null) { //creamos nuestro usuario Administrador: user = new User { Address = "Calle Madrid 55", FirstName = "Emilio", LastName = "Barrera", Phone = "693661995", userName = "[email protected]", Photo = "~/Content/Photos/fondo.jpg" }; db.Users.Add(user); db.SaveChanges(); } //valido si el uusarip existe en las tablas de the ASP NET User: var userASP = userManager.FindByName(user.userName); if (userASP == null) { userASP = new ApplicationUser { UserName = user.userName, Email = user.userName, PhoneNumber = user.Phone }; userManager.Create(userASP, "Eabs+++++55555"); userManager.AddToRole(userASP.Id, "Admin"); } userManager.AddToRole(userASP.Id, "Admin"); }
public static void SeedRoles() { var context = new ApplicationDbContext(); if (!context.Roles.Any()) { if (!context.Roles.Any()) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); var roleCreateResult = roleManager.Create(new IdentityRole("Admin")); if (!roleCreateResult.Succeeded) { throw new Exception(string.Join("; ", roleCreateResult.Errors)); } var roleStore = new RoleStore<IdentityRole>(context); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]" }; var createResult = userManager.Create(user, "123456"); if (!createResult.Succeeded) { throw new Exception(string.Join("; ", createResult.Errors)); } userManager.AddToRole(user.Id, "admin"); context.SaveChanges(); } } }
internal void AddUserAndRole() { // access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object. var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); // create admin role if it doesn't already exist if (!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } // create a UserManager object based on the UserStore object and the ApplicationDbContext object. // defines admin email account var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new admin user was successfully created, add the new user to the "admin" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
public static void CreateUserByRole(RoleEnum role, ApplicationUser user, string password, ApplicationDbContext db) { user.Id = Guid.NewGuid().ToString(); var store = new UserStore<ApplicationUser>(db); var manager = new UserManager<ApplicationUser>(store); using (var dbContextTransaction = db.Database.BeginTransaction()) { try { manager.Create(user, password); db.SaveChanges(); manager.AddToRole(user.Id, Enum.GetName(typeof(RoleEnum), (int)role)); db.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); } } }
public ActionResult Create(ClientViewModel client) { if (!ModelState.IsValid) return View(); //Register user and SingIn var accountController = new AccountController {ControllerContext = this.ControllerContext}; var user = accountController.RegisterAccount(new RegisterViewModel() { Email = client.Email, Password = client.Password }); accountController.SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false); //Add user to client role var userStore = new UserStore<ApplicationUser>(_context); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(_context); var roleManager = new RoleManager<IdentityRole>(roleStore); if (!roleManager.RoleExists("Client")) roleManager.Create(new IdentityRole("Client")); userManager.AddToRole(user.Id, "Client"); //Register client if (string.IsNullOrWhiteSpace(user.Id)) return View(); _context.Clients.Add(new Client() { Id = user.Id, Name = client.Name, Age = client.Age }); _context.SaveChanges(); return RedirectToAction("Index", "Home"); }
public ActionResult Doctors_Create([DataSourceRequest]DataSourceRequest request, DoctorGridViewModel doctor) { if (this.ModelState.IsValid) { //TODO:Create service for users var context = new MyMedicalGuideDbContext(); var userManager = new UserManager<User>(new UserStore<User>(context)); var userDoctor = new User() { Email = doctor.Email, FirstName = doctor.FirstName, LastName = doctor.LastName, PhoneNumber = doctor.PhoneNumber, UserName = doctor.Username }; var hospitalId = this.TempData["hospitalId"]; userManager.Create(userDoctor, doctor.Password); var DoctorDb = new MyMedicalGuide.Data.Models.Doctor() { User = userDoctor, HospitalId = (int)hospitalId, DepartmentId = doctor.DepartmentId, CreatedOn = DateTime.Now }; context.Doctors.Add(DoctorDb); userManager.AddToRole(userDoctor.Id, "Doctor"); } return this.Json(new[] { doctor }.ToDataSourceResult(request, this.ModelState)); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); using (var context = new ApplicationDbContext()) { if (context.Roles.Where(a => String.Compare(a.Name, "admin", true) == 0).Count() == 0) { context.Roles.Add(new IdentityRole("admin")); context.SaveChanges(); } var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = new ApplicationUser() { UserName = "Admin", Email = "[email protected]" }; var createResult = um.Create(user, "Aa123!"); if(createResult.Succeeded) { var roleresult = um.AddToRole(user.Id, "admin"); } } }
protected void btnRegister_Click(object sender, EventArgs e) { var userMgr = new UserManager(); var employee = new Employee() { UserName = UserName.Text, FirstName = FirstName.Text, LastName = LastName.Text, PhoneNumber = PhoneNumber.Text, Email = Email.Text, Department = (Grievance.GrievanceTypes)Convert.ToInt32(Department.SelectedValue) }; IdentityResult IdUserResult = userMgr.Create(employee, Password.Text); if (IdUserResult.Succeeded) { if (!userMgr.IsInRole(employee.Id, "Employee")) // Only users of type "Employee" can be created from the "Register Employee" page. { IdUserResult = userMgr.AddToRole(employee.Id, "Employee"); } SuccessMessage.Text = "Employee created successfully"; SuccessMessage.Visible = true; ErrorMessage.Visible = false; UserName.Text = FirstName.Text = LastName.Text = PhoneNumber.Text = Email.Text = Password.Text = ConfirmPassword.Text = string.Empty; } else { ErrorMessage.Text = IdUserResult.Errors.FirstOrDefault(); ErrorMessage.Visible = true; SuccessMessage.Visible = false; } }
protected void RadGridUserList_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e) { var editableitem = ((GridEditableItem)e.Item); UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID); /// var useStore = new UserStore<AppUser>(new ApplicationDbContext()); var manager = new UserManager<AppUser>(useStore); string LogInUserName=(editableitem.FindControl("RtxtLoginID") as RadTextBox).Text.Trim(); var user = new AppUser { UserName = LogInUserName, FName = (editableitem.FindControl("RtxtFirstName") as RadTextBox).Text, LName = (editableitem.FindControl("RtxtLastName") as RadTextBox).Text }; IdentityResult result = manager.Create(user, (editableitem.FindControl("RtxtPassword") as RadTextBox).Text); if (result.Succeeded) { //Get The Current Created UserInfo AppUser CreatedUser = manager.FindByName(LogInUserName); var RoleAddResult = manager.AddToRole(CreatedUser.Id.Trim(), (editableitem.FindControl("RDDListRole") as RadDropDownList).SelectedItem.Text.Trim()); lblMessage.Text = string.Format("User {0} is creted successfully", user.UserName); } else { lblMessage.Text = result.Errors.FirstOrDefault(); e.Canceled = true; } }
internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "administrator", ImgUrl = "user2-160x160.jpg", Description = "High Level", SinceDate = new DateTime(2016, 1, 1) }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
public bool AddUserToRole(string userId, string roleName) { var um = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(new SubHubContext())); var idResult = um.AddToRole(userId, roleName); return idResult.Succeeded; }
public static void AddUserRole(string userName, string roleName) { using (var context = new ApplicationDbContext()) { try { if (!context.Roles.Any(r => r.Name == roleName)) return; var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var store = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(store); var user = userManager.FindByName(userName); var role = roleManager.FindByName(roleName); if (userManager.IsInRole(user.Id, role.Name)) return; userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. // ReSharper disable once UnusedVariable var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); throw; } } }
/*This should be removed after the first admin gets made */ // GET: MakeMeAdmin/Create public ActionResult Create(string email) { using (var context = new ApplicationDbContext()) { var fadmin = context.KeyValueSettings.FirstOrDefault(s => s.Key == "FirstAdminSet"); if (fadmin == null || fadmin.Value == "false") { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); roleManager.Create(new IdentityRole("Admin")); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByEmail(email); userManager.AddToRole(user.Id, "Admin"); if (fadmin == null) { context.KeyValueSettings.Add(new KeyValueSettings() { Key = "FirstAdminSet", Value = "true" }); } else { fadmin.Value = "true"; } context.SaveChanges(); return Json(true, JsonRequestBehavior.AllowGet); } } return Json(false, JsonRequestBehavior.AllowGet); }
public static void Start() { using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new UsersDbContext()))) { foreach (var roleName in RolesList.Where(roleName => !roleManager.RoleExists(roleName))) { roleManager.Create(new IdentityRole(roleName)); } } using ( var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new UsersDbContext())) ) { if (userManager.FindByName(Constants.AdminUserName) != null) { return; } var admin = new ApplicationUser {UserName = Constants.AdminUserName}; var result = userManager.Create(admin, "AdminPass"); if (!result.Succeeded) { var txt = new StringBuilder(); foreach (var error in result.Errors) { txt.AppendLine(error); } throw new Exception(txt.ToString()); } userManager.AddToRole(admin.Id, Constants.Roles.Admin); } }
internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "administrator", }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { //userMgr.RemoveFromRoles(user.Id, "read", "edit"); IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
private void CreateUser(ApplicationDbContext context, string userName, string userEmail, string userPass, string userRole) { if (context.Users.Any()) { return; } var store = new UserStore<User>(context); var manager = new UserManager<User>(store) { PasswordValidator = new PasswordValidator { RequiredLength = WebConstants.MinUserPasswordLength, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, } }; var user = new User { UserName = userName, Email = userEmail }; manager.Create(user, userPass); manager.AddToRole(user.Id, userRole); }
internal bool UpdateUser(string username, string realUsername, string permission) { IdentityResult result = null; Models.ApplicationDbContext context = new Models.ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var user = userMgr.FindByName(username); if (!string.IsNullOrEmpty(realUsername)) { user.RealUserName = realUsername; result = userMgr.Update(user); } if (!string.IsNullOrEmpty(permission) && !userMgr.IsInRole(user.Id, permission)) { userMgr.RemoveFromRoles(user.Id, "read", "edit", "administrator"); switch (permission) { case "administrator": result = userMgr.AddToRole(user.Id, "administrator"); break; case "edit": result = userMgr.AddToRole(user.Id, "edit"); break; default: result = userMgr.AddToRole(user.Id, "read"); break; } } if (result == IdentityResult.Success) return true; else return false; }
private static void seedUserRoles(string Admin, string User, ApplicationDbContext db) { var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); manager.AddToRoles(Admin, Roles.ADMIN); manager.AddToRole(User, Roles.USER); }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { result = manager.AddToRole(user.Id, "Student"); var std = new Student(); std.FirstName = FirstName.Text; std.LastName = lastName.Text; std.UserId = user.Id; std.BirthDate = DateTime.Now; CourseContext cc = new CourseContext(); cc.Students.Add(std); cc.SaveChanges(); IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
public void ListViewUsers_UpdateItem(string Id, string commandArgument) { var item = this.UsersService.GetById(Id); if (item == null) { var errorMessage = $"User with id {this.ID} was not found"; Notificator.AddErrorMessage(errorMessage); this.ModelState.AddModelError("", errorMessage); return; } var isAdmin = ((CheckBox)ListViewAllUsers.Items[ListViewAllUsers.EditIndex].FindControl("CbIsADmin")).Checked; // TODO: extract in separate class or service var userManager = new UserManager<User>(new UserStore<User>(new XShareDbContext())); if (isAdmin) { userManager.AddToRole(item.Id, "admin"); } else { userManager.RemoveFromRole(item.Id, "admin"); } this.TryUpdateModel(item); if (this.ModelState.IsValid) { this.UsersService.UpdateUser(item); Notificator.AddInfoMessage($"You've just updated the info for user {item.UserName}"); } }