Esempio n. 1
0
        public async Task <ActionResult> Index(string userName, string roleName)
        {
            if (HasAdminPrivileges(User))
            {
                if (ModelState.IsValid)
                {
                    var user = DbContext.Users
                               .Include(u => u.Roles)
                               .Where(u => u.UserName == userName).SingleOrDefault();

                    if (user != null)
                    {
                        string roleId = user.Roles.Single().RoleId;

                        var oldRoleName = DbContext.Roles.Where(r => r.Id == roleId).Single().Name;

                        if (await _userService.RemoveUserFromRole(user.Id, oldRoleName) && await _userService.AddUserToRole(user.Id, roleName))
                        {
                            // If current user has changed his/her role.
                            if (userName == User.Identity.Name)
                            {
                                // Sign the user out.
                                AuthenticationManager.SignOut();

                                // Sign the user back.
                                var identity = await _userService.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                                AuthenticationManager.SignIn(new AuthenticationProperties {
                                    IsPersistent = true
                                }, identity);
                                return(Json(new { success = "User changed his own role succesfully.", redirectUrl = Url.Action("Index", "Home") }));
                            }

                            return(Json(new { success = "User role was succesfully changed." }));
                        }
                        else
                        {
                            return(Json(new { error = "Role or User was Not Found." }));
                        }
                    }

                    return(Json(new { error = "User was Not Found." }));
                }

                return(Json(new { error = "Role or User was Not Found." }));
            }

            return(Json(new { error = "You must have System Administrator rights in order to carry out this action." }));
        }