public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            if (ModelState.IsValid)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                ViewBag.Token = "2";

                if (userManager.IsInRole(user.Id, RoleName))
                {
                    userManager.RemoveFromRole(user.Id, RoleName);
                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;

                var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
                ViewBag.userNames = userList;

                ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
            }

            return View("ManageUserRoles");
        }
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            var account = new AccountController();
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            if (UserManager.IsInRole(user.Id, RoleName))
            {
                UserManager.RemoveFromRole(user.Id, RoleName);
                var employee = context.Employees.Single(x => x.employeeFirstName == user.FirstName && x.employeeLastName ==user.LastName);
                var role = context.RolesForEmployees.Single(x => x.roleName == RoleName);
                var tmp = context.EmployeeRoles.Single(x => x.role == role && x.employee == employee);
                context.EmployeeRoles.Remove(tmp);
                context.SaveChanges();

                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;

            return View("ManageUserRoles");
        }
        public void Details(AspNetUserDetailsViewModel mdl)
        {

            var ctx = new ApplicationDbContext();
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx));

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));


            //if(userManager.IsInRole(mdl.User.Id, "Admin"))
            //{
            //    mdl.RoleId = RoleManager.FindByName("Admin")?.Id;
            //}
            //if(userManager.IsInRole(mdl.User.Id, "NetUser"))
            //{
            //    mdl.RoleId = RoleManager.FindByName("NetUser")?.Id;
            //}


            var role = RoleManager.FindById(mdl.RoleId);
            var roles = RoleManager.Roles.ToList();
            foreach(var item in roles)
            {
                userManager.RemoveFromRole(mdl.User.Id, item.Name);
            }
            userManager.AddToRole(mdl.User.Id, role.Name);
        }
Example #4
0
        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}");
            }
        }
        // DELETE api/memberships/5
        public void Delete(string id)
        {
            //this is a bit hacky - but the association will be coming in here
            //and it's GUID | role
            //so parse that and unassign
            var splits = id.Split('|');
            var userId = splits[0];
            var roleId = splits[1];

            //this is a new user/role assignment
            using (var db = new ApplicationDbContext())
            {
                var role = db.Roles.FirstOrDefault(x => x.Id == roleId);
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

                manager.RemoveFromRole(userId, role.Name);
                var note = new AspNetUserNote();
                note.EnteredBy = User.Identity.Name;
                note.Note = "Removed user from " + role.Name + " role";

                var user = db.Users.FirstOrDefault(x => x.Id == userId);
                user.Notes.Add(note);
                db.SaveChanges();

            }
        }
Example #6
0
        public static void RemoveUserFromAdmin(this string userId)
        {
            ApplicationUser user = db.Users.FirstOrDefault(u => u.Id.Equals(userId));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

            userManager.RemoveFromRole(userId, "Admin");
        }
Example #7
0
 public void ClearUserRoles(string userId)
 {
     var um = new UserManager<User>(new UserStore<User>(new DatabaseContext()));
     um.UserValidator = new UserValidator<User>(um) { AllowOnlyAlphanumericUserNames = false };
     User user = um.FindById(userId);
     List<IdentityUserRole> currentRoles = user.Roles.ToList();
     currentRoles.ForEach(item => um.RemoveFromRole(user.Id, item.Role.Name));
 }
Example #8
0
 public void ClearUserRoles(string userId)
 {
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new EntityDbContext()));
     var user = um.FindById(userId);
     var currentRoles = new List<IdentityUserRole>();
     currentRoles.AddRange(user.Roles);
     foreach (var role in currentRoles)
     {
         um.RemoveFromRole(userId, role.RoleId);
     }
 }
        public JsonResult UpdateSystemRole(string userName, string roleToUpdate)
        {
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            userMgr.UserValidator = new UserValidator<ApplicationUser>(userMgr) { AllowOnlyAlphanumericUserNames = false };
            var user = userMgr.FindByName(userName);
            userMgr.RemoveFromRole(user.Id, Common.Constants.SYSTEM_ROLE_USER);
            userMgr.RemoveFromRole(user.Id, Common.Constants.SYSTEM_ROLE_ADMINISTRATOR);
            var roleresult = userMgr.AddToRole(user.Id, roleToUpdate);
            if (roleresult.Succeeded)
            {
                return Json(new
                {
                    Status = "OK",
                    Msg = ""
                });
            }
            else
            {
                return Json(new { Status = "ERROR", Message = "Unable to add user to role" });
            }

        }
 public void ClearUserRoles(string userId)
 {
     var identityDbContext = new ApplicationDbContext();
     var um = new UserManager<ApplicationUser>(
         new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var user = um.FindById(userId);
     var currentRoles = new List<IdentityUserRole>();
     currentRoles.AddRange(user.Roles);
     foreach (var role in currentRoles)
     {
         var _role = identityDbContext.Roles.FirstOrDefault(x=>x.Id == role.RoleId);
         um.RemoveFromRole(userId, _role.Name);
     }
 }
        public void AddToRole(string role, string employee)
        {
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var user = UserManager.FindByName(employee);
            var userRoles =  user.Roles.ToList();
           
            //user.Roles.Remove(roles);
            foreach (var Role in userRoles)
            {
               var roleName = roleManager.FindById(Role.RoleId);
               UserManager.RemoveFromRole(user.Id, roleName.Name);
            }

            UserManager.AddToRole(user.Id, role);
            
        }
        public ActionResult ExcludeUser(string id)
        {
            var userStore = new UserStore<User>(this.dbContext);
            var userManager = new UserManager<User>(userStore);
            try
            {
                userManager.RemoveFromRole(id, GlobalConstants.EngineerRoleName);
            }
            catch (Exception e)
            {
                this.TempData["Error"] = e.Message;
                return this.RedirectToAction("Index");
            }

            this.TempData["Success"] = "User successfully excluded from the role";
            return this.RedirectToAction("Index");
        }
        public void setRole(string id, string RoleName)
        {
            var context = new ApplicationDbContext();
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            var userId = _db.Users.Find(id);
            var roleId = _db.Roles.First(a => a.Name == RoleName);
            if (userId.Roles.Count(a => a.RoleId == roleId.Id) != 0)
            {
                manager.RemoveFromRole(userId.Id, RoleName);
            }
            else
            {
                var roleresult = manager.AddToRole(userId.Id, RoleName);
                //Отправляем письмо, о том, что пользователя авторизовали
                var mail = new MailMessage
                {
                    Subject = "авторизация пройдена",
                    Body = "<p>Уважаемы пользователь " + userId.NickName + "</p>" + "<p>Вы авторизированы на форуме программы Талисман-SQL</p>"
                };

                switch (RoleName)
                {
                    case "user":
                        mail.Body += "<p>Теперь вы можете создавать темы в разделах форума, а также писать сообщения</p>";
                        break;
                    case "moderator":
                        mail.Body += "<p>Теперь вы можете создавать темы в разделах форума, создавать сообщения, закреплять и закрывать темы</p>";
                        break;

                }
                mail.IsBodyHtml = true;
                mail.To.Add(userId.Email);
                Code.Mail.SendEmail(mail);
            }
        }
Example #14
0
        public ActionResult DeleteAdminPermission(string userId)
        {
            List<MoviesLabUser> user = db.Users.ToList();

            if (user == null)
            {
                return RedirectToAction("UserList", new { message = StatusMessage.UserNotFound });
            }

            var userManager = new UserManager<MoviesLabUser>(new UserStore<MoviesLabUser>(db));

            if (userManager.IsInRole(userId, "Администратор"))
            {
                userManager.RemoveFromRole(userId, "Администратор");
                return RedirectToAction("UserList", new { message = StatusMessage.UserDeleteGrantSuccess });
            }
            else
            {
                return RedirectToAction("UserList", new { message = StatusMessage.UserIsntInRole });
            }
        }
 public ActionResult DeleteRoleForUser(string UserName, string RoleName)
 {
     ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     if (userManager.IsInRole(user.Id, RoleName))
     {
         userManager.RemoveFromRole(user.Id, RoleName);
         ViewBag.ResultMessageDelete = "Role removed from this user successfully";
     }
     else
     {
         ViewBag.ResultMessageDelete = "This user doesn't belong to the selected role";
     }
     // prepopulat roles for the view dropdown
     var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
     var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList();
     ViewBag.Roles = list;
     var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
     ViewBag.Users = listUsers;
     ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text");
     return View("Index");
 }
              protected void cmdUpdateRole_Click(object sender, EventArgs e)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new EventSystemDbContext()));
            var userManager = new UserManager<AppUser>(new UserStore<AppUser>(new EventSystemDbContext()));
            foreach (GridViewRow row in this.GridViewUsers.Rows)
            {
                string username = row.Cells[0].Text;
                CheckBox chkAdmin = (CheckBox)row.Cells[1].Controls[0];
                List<string> roles = new List<string>();

                var userId = this.dbContext.Users.Where(u => u.UserName == username).Select(u => u.Id).FirstOrDefault();

                if (chkAdmin.Checked)
                {
                    userManager.AddToRole(userId, "admin");
                }
                else
                {
                    userManager.RemoveFromRole(userId, "admin");
                }
            }

            BindGridviewData();
        }
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                ApplicationUser user = db.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

                if (um.IsInRole(user.Id, RoleName))
                {
                    um.RemoveFromRole(user.Id, RoleName);
                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }
                // prepopulat roles for the view dropdown
                var list = db.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;

                return View("ManageUserRoles");
            }
        }
 public ActionResult Edit(EditViewModel model)
 {
     ApplicationDbContext db = new ApplicationDbContext();
     if (ModelState.IsValid)
     {
         try
         {
             var u_manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
             var currentUser = u_manager.FindById(model.UserId);
             if (currentUser != null)
             {
                 string userFullName = DataHelper.ToPascalConvention(model.FirstName + " " + model.LastName);
                 currentUser.UserName = model.Email;
                 currentUser.FirstName = model.FirstName;
                 currentUser.LastName = model.LastName;
                 currentUser.FullName = userFullName;
                 currentUser.PhoneNumber = model.ContactNo;
                 currentUser.Email = model.Email;
                 //  currentUser.PasswordHash = Crypto.HashPassword(model.Password);                      
                 db.Entry(currentUser).State = EntityState.Modified;
                 db.SaveChanges();
                 
                 var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
                 var role = roleManager.FindById(model.RoleId);
                 if (role != null)
                 {
                     u_manager.RemoveFromRole(model.UserId, model.RoleName);
                     u_manager.AddToRole(model.UserId, role.Name);
                     db.SaveChanges();
                 }
                 List<Product> listProducts = new List<Product>();
                 int userProductId = DBHandler.UserProductId(model.UserId);
                 ManagerProduct objManagerProduct = new ManagerProduct();
                   
                 if (userProductId > 0)
                 {                          
                                  
                     objManagerProduct = db.ManagerProducts.Find(userProductId);
                     objManagerProduct.ProductIds = model.selectedProduct;         
                     objManagerProduct.ApplicationUserId = objManagerProduct.ApplicationUserId;
                     objManagerProduct.UpdatedOn = DateTime.Now;
                     objManagerProduct.CreatedOn = objManagerProduct.CreatedOn;
                     db.Entry(objManagerProduct).State = EntityState.Modified;
                     db.SaveChanges();  
                 }
                 else
                 {
                     objManagerProduct.UpdatedOn = DateTime.Now;
                     objManagerProduct.ProductIds = model.selectedProduct;         
                     objManagerProduct.ApplicationUserId = model.UserId;
                     objManagerProduct.CreatedOn = DateTime.Now;
                     db.ManagerProducts.Add(objManagerProduct);
                     db.SaveChanges();
                 }
                
                 DBHandler.SaveUserLogged(currentUser, model.RoleId, role.Name, UserLoggedActions.UserUpadated);
                 return RedirectToAction("Index", "User");
             }
         }
         catch (Exception)
         {
             throw;
         }
     }
     ViewBag.RoleId = new SelectList(db.Roles, "Id", "Name", model.RoleId);
     return View(model);
 }
        public async Task<ActionResult> CompleteTeacherRegistration(string id, TeacherInfoViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = this.Data.Users.GetById(id);

                if (user == null)
                {
                    return new HttpStatusCodeResult(400, "Bad Request");
                }

                var teacher = Mapper.Map<Teacher>(model);
                teacher.Id = id;

                var userStore = new UserStore<User>(this.Data.Context.DbContext);
                var userManager = new UserManager<User>(userStore);

                this.Data.Teachers.Add(teacher);
                this.Data.SaveChanges();

                userManager.AddToRole(user.Id, GlobalConstants.COMPLETE_USER);
                userManager.RemoveFromRole(user.Id, GlobalConstants.NOT_COMPLETE_USER);

                this.Data.SaveChanges();

                await this.SignInUser(user);

                CreateNotification(id);

                return RedirectToAction("Index", "Storage");
            }

            return View();
        }
        public ActionResult RemoveManager(int BuildingID, int ClientID, string ManagerID)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            Manager Obj = db.Manager.Find(ManagerID);
            AspNetUsers user = db.AspNetUsers.Find(ManagerID);
            ManagerBuilding managerb = db.ManagerBuilding.Where(c => c.ManagerID == ManagerID).FirstOrDefault();
           
            
            UserManager.RemoveFromRole(ManagerID, "Manager");//from role Manager
            context.SaveChanges();

            db.ManagerBuilding.Remove(managerb);// mapping row building and user
            db.SaveChanges(); 
               
                 db.Manager.Remove(Obj); //manager
                 db.SaveChanges();

                 db.AspNetUsers.Remove(user);//remove user
                db.SaveChanges();

                return RedirectToAction("ManagementBuilding", new { BuildingID = BuildingID });
        }
 public ActionResult DeleteRoleForUser(string UserName, string RoleName)
 {
     //var account = new AccountController();
     UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
     new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCulture)).FirstOrDefault();
     if ( _userManager.IsInRole(user.Id, RoleName))
     {
         _userManager.RemoveFromRole(user.Id, RoleName);
         TempData["ResultMessage"] = "Role removed"; ;
     }
     else
     {
         TempData["ResultMessage"] = "This user doesnt belong to selected role.";
     }
     var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
     ViewBag.Roles = list;
      var UserList = context.Users.OrderBy(r => r.UserName).ToList();
      ViewBag.WebUsers = UserList;
     return View("ManageUserRoles");
 }
 private string DeleteUserPermissiondb(string RoleName, string UserID)
 {
     var result = "";
     var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
     var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     if (RoleManager.RoleExists(RoleName))
     {
         UserManager.RemoveFromRole(UserID, RoleName);
         result = "Successful";
     }
     else { result = "It doesn't exist"; }
     return result;
 }
       public ActionResult DeleteRoleForUser(string UserName, string RoleName)
       {
           ApplicationDbContext context = new ApplicationDbContext();
           var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
           var CurrentUser = db.AspNetUsers.FirstOrDefault(c => c.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));


           if (CurrentUser == null)
           {
               // prepopulat roles for the view dropdown
               ViewBag.Roles = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
               ViewBag.clientlist = db.Clients.Select(c => new SelectListItem { Text = c.ClientName, Value = c.ID.ToString() }).ToList();
      
               ViewBag.ResultMessage = "There is no user with this Username !";
               return View("ManageUserRoles");
           }
           var currentUserID = CurrentUser.Id;
           if (UserManager.IsInRole(currentUserID, RoleName))
           {
               UserManager.RemoveFromRole(currentUserID, RoleName);
               
               ViewBag.ResultMessage = "Role removed from this user successfully !";
     
           }
           else
           {
               ViewBag.ResultMessage = "This user doesn't belong to selected role.";
             
           }
           ViewBag.RolesForThisUser = Roles.GetRolesForUser(UserName);
           // prepopulat roles for the view dropdown
           ViewBag.Roles = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
           ViewBag.clientlist = db.Clients.Select(c => new SelectListItem { Text = c.ClientName, Value = c.ID.ToString() }).ToList();
      
           return View("ManageUserRoles");
       }
        public int removeEmpFromGroup(int GroupId, int EmpId)
        {
            GroupIncharge grpIncharge = db.GroupIncharges.Where(b => b.GroupId == GroupId && b.InchargeId == EmpId).FirstOrDefault();

            db.GroupIncharges.Remove(grpIncharge);

            db.SaveChanges();

            if (db.GroupIncharges.Where(b => b.InchargeId == EmpId).Count() == 0)
            {
                var userStore = new UserStore<IdentityUser>();
                var UserManager = new UserManager<IdentityUser>(userStore);
                var user = UserManager.FindById(db.Employees.Find(EmpId).AuthUserId);
                UserManager.RemoveFromRole(user.Id, "ClientManager");
            }

            return 1;
        }
        public ActionResult ManageUserToRole(string userName, string roleName, string action)
        {
            if (action.Equals("Add User To Role"))
            {
                string userMessage = "User added to role";
                try
                {
                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());

                    if (roleManager.RoleExists(roleName))
                    {
                        var _context = new ApplicationDbContext();
                        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));

                        //Check if user exists
                        var userFromDb = _context.Users.ToList().Where(x => x.UserName.Equals(userName)).ElementAtOrDefault(0);
                        if (userFromDb != null)
                        {
                            userManager.AddToRole(userFromDb.Id, roleName);
                        }
                        else
                        {
                            userMessage = string.Format("Can't find user {0}", userName);
                        }


                    }
                    else
                    {
                        userMessage = string.Format("Role {0} does not exists", roleName);
                    }

                }
                catch (Exception ex)
                {
                    userMessage = ex.Message;
                }

                return RedirectToAction("ManageUser", new RouteValueDictionary(
                                                    new { controller = "UserAdmin", action = "ManageUser", message = userMessage }));
            }


            if (action.Equals("Remove User From Role"))
            {
                string userMessage = "User removed from role";
                try
                {
                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());

                    if (roleManager.RoleExists(roleName))
                    {
                        var _context = new ApplicationDbContext();
                        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));



                        //Check if user exists
                        var userFromDb = _context.Users.ToList().Where(x => x.UserName.Equals(userName)).ElementAtOrDefault(0);
                        if (userFromDb != null)
                        {
                            if(userManager.IsInRole(userFromDb.Id,roleName))
                            {
                                userManager.RemoveFromRole(userFromDb.Id,roleName);
                            }
                        }
                        else
                        {
                            userMessage = string.Format("Can't find user {0}", userName);
                        }


                    }
                    else
                    {
                        userMessage = string.Format("Role {0} does not exists", roleName);
                    }

                }
                catch (Exception ex)
                {
                    userMessage = ex.Message;
                }

                return RedirectToAction("ManageUser", new RouteValueDictionary(
                                                    new { controller = "UserAdmin", action = "ManageUser", message = userMessage }));
            }

            return RedirectToAction("ManageUser", new RouteValueDictionary(
                                                 new { controller = "UserAdmin", action = "ManageUser", message = "Command not recognized" }));
        }
        public ActionResult DeleteRoleFromUser(string userName, string roleName)
        {
            var context = new ApplicationDbContext();

            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            var user = userManager.FindByEmail(userName);
            if (user != null)
            {
                var role = roleManager.FindByName(roleName);
                if (role != null)
                {
                    if (userManager.IsInRole(user.Id, role.Name))
                    {
                        userManager.RemoveFromRole(user.Id, role.Name);
                        context.SaveChanges();
                    }
                }
            }

            return RedirectToAction("RolesIndex", "Account");
        }
Example #27
0
        public ActionResult OnOffAdministrator(int id)
        {
            var user = db.Users.Find(id);

            if (user != null)
            {
                //cuando siepre quiero buscar los usuarios en las tabla ASP.net: de roles y usuarios:
                var userContext = new ApplicationDbContext();
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));

                //Buscamos el role primero:
                var userASP = userManager.FindByEmail(user.userName);

                //Si es diferente de null podemos proceder con el role del ese usuario:
                if (userASP != null)
                {
                    if (userManager.IsInRole(userASP.Id, "Admin"))
                    {
                        userManager.RemoveFromRole(userASP.Id, "Admin");
                    }
                    else
                    {
                        userManager.AddToRole(userASP.Id, "Admin");
                    }
                }

            }     

            return RedirectToAction("Index");
        }
        public ActionResult DeleteRoleForUser(string userName, string roleName)
        {
            List<string> userRoles;
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roles = (from r in roleManager.Roles select r.Name).ToList();

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                users = (from u in userManager.Users select u.UserName).ToList();

                var user = userManager.FindByName(userName);
                if (user == null)
                    throw new Exception("User not found!");

                if (userManager.IsInRole(user.Id, roleName))
                {
                    userManager.RemoveFromRole(user.Id, roleName);
                    context.SaveChanges();

                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                var userRoleIds = (from r in user.Roles select r.RoleId);
                userRoles = (from id in userRoleIds
                             let r = roleManager.FindById(id)
                             select r.Name).ToList();
            }

            ViewBag.RolesForThisUser = userRoles;
            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View("RoleAddToUser");
        }
Example #29
0
        public bool updateUser(User selectedUser)
        {
            //Danger: selected user with new role inside
            if(selectedUser != null)
            {
                IRepository<User> repository = new UserRepository();

                //update in aspUser
                User orginUser = repository.findById(selectedUser.UserID);
                //find old role
                Role oldRole = role_repo.findById(orginUser.RoleID);
                string oldRoleName = oldRole.RoleName;
                Role newRole = role_repo.findById(selectedUser.RoleID);
                string newRoleName = newRole.RoleName;
                var context = new NetCafeWeb.Models.ApplicationDbContext();
                var UserManager = new UserManager<NetCafeWeb.Models.ApplicationUser>(new UserStore<NetCafeWeb.Models.ApplicationUser>(context));
                ApplicationUser aspSelectedUser = context.Users.Where(u => u.UserName.Equals((selectedUser.UserName), StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                var r1 = UserManager.RemoveFromRole(aspSelectedUser.Id, oldRoleName);
                var r2 = UserManager.AddToRole(aspSelectedUser.Id, newRoleName);

                if (r1.Succeeded && r2.Succeeded)
                {
                    //update in user table
                    repository.Update(selectedUser);
                    return true;
                }
                else return false;
            }

            return false;
        }
    protected void RolesUserList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Get the selected role
        string selectedRoleName = RoleList.SelectedValue;

        // Reference the UserNameLabel
        Label UserNameLabel = RolesUserList.Rows[e.RowIndex].FindControl("UserNameLabel") as Label;

        // Remove the user from the role
        var um = new UserManager();
        var user = um.FindByName(UserNameLabel.Text);
        um.RemoveFromRole(user.Id, selectedRoleName);

        // Refresh the GridView
        DisplayUsersBelongingToRole();

        // Display a status message
        ActionStatus.Text = string.Format("User {0} was removed from role {1}.", UserNameLabel.Text, selectedRoleName);

        // Refresh the "by user" interface
        CheckRolesForSelectedUser();
    }