Example #1
0
        public ActionResult Create(CreateRoleViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var newRole = new Role
                {
                    Name        = vm.Name,
                    Description = vm.Description
                };

                _roleRepository.Create(newRole);
                _unitOfWork.Commit();

                foreach (var permission in vm.PermissionIds)
                {
                    var rolePermission = new RolePermission
                    {
                        RoleId       = newRole.Id,
                        PermissionId = permission
                    };
                    _rolePermissionRepository.Create(rolePermission);
                }

                _unitOfWork.Commit();

                return(RedirectToAction("Index"));
            }

            ViewBag.RolePermissions = new MultiSelectList(_permissionRepository.GetAll(), "Id", "Title");
            return(View(vm));
        }
        public async Task <IActionResult> UpdateRolePermissionAsync([FromBody] UpdateRolePermissionViewModel model_)
        {
            string roleId = (await _roleManager.FindByNameAsync(model_.RoleName)).Id;

            Enum.TryParse(model_.PermissionValue, true, out Permission permissionEnumValue);

            if (model_.Extension == Constants.SoftinuxBaseSecurity && permissionEnumValue != Permission.Admin)
            {
                if (await ReadGrants.IsRoleLastAdminPermissionLevelGrantForExtensionAsync(_roleManager, Storage, model_.RoleName, model_.Extension))
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, "Permission not updated, the role is the last Admin grant to SoftinuxBase.Security extension"));
                }
            }

            IRolePermissionRepository repo = Storage.GetRepository <IRolePermissionRepository>();

            repo.Delete(roleId, model_.Extension);

            var permissionEntity = Storage.GetRepository <IPermissionRepository>().Find(permissionEnumValue);

            repo.Create(new RolePermission {
                RoleId = roleId, PermissionId = permissionEntity.Id, Extension = model_.Extension
            });

            await Storage.SaveAsync();

            return(StatusCode((int)HttpStatusCode.OK));
        }
Example #3
0
        private async Task SetPermissions(Guid roleId, params Guid[] permIds)
        {
            // Add new permissions from list
            var existingPermissions = (await _rolePermissionRepository.GetByRole(roleId)).ToList();

            var permissionsToAdd = permIds.Where(x => existingPermissions.All(p => p.PermissionId != x)).ToList();

            var permissionsToRemove = existingPermissions.Where(p => permIds.All(x => x != p.PermissionId)).ToList();

            foreach (var permId in permissionsToAdd)
            {
                _rolePermissionRepository.Create(new RolePermission
                {
                    RoleId = roleId, PermissionId = permId
                });
            }

            // Remove permissions that no longer apply

            foreach (var perm in permissionsToRemove)
            {
                await _rolePermissionRepository.Delete(perm.RoleId, perm.PermissionId);
            }

            _rolePermissionsCache.Purge(roleId);

            await _rolePermissionRepository.SaveChanges();
        }
Example #4
0
        /// <summary>
        /// First, check that a role with this name doesn't already exist.
        ///
        /// Second, save new data into database.
        /// </summary>
        /// <param name="storage_">Storage interface provided by services container.</param>
        /// <param name="roleManager_">Roles manager object.</param>
        /// <param name="model_">A <see cref="SaveNewRoleAndGrantsViewModel" /> object.</param>
        /// <returns>Null if success, otherwise error message.</returns>
        public static async Task <string> CheckAndSaveNewRoleAndGrantsAsync(IStorage storage_, RoleManager <IdentityRole <string> > roleManager_, SaveNewRoleAndGrantsViewModel model_)
        {
            if (await UpdateRoleAndGrants.CheckThatRoleOfThisNameExistsAsync(roleManager_, model_.RoleName))
            {
                return("A role with this name already exists");
            }

            if (model_.Extensions == null || !model_.Extensions.Any())
            {
                return("At least one extension must be selected");
            }

            try
            {
                // Convert the string to the enum
                if (Enum.TryParse <Common.Enums.Permission>(model_.PermissionValue, true, out var permissionEnumValue))
                {
                    var permissionEntity = storage_.GetRepository <IPermissionRepository>().Find(permissionEnumValue);

                    // Save the Role
                    IdentityRole <string> identityRole = new IdentityRole <string>
                    {
                        // Auto-incremented ID
                        Name = model_.RoleName
                    };
                    await roleManager_.CreateAsync(identityRole);

                    // Save the role-extension-permission link
                    if (model_.Extensions != null)
                    {
                        IRolePermissionRepository repo = storage_.GetRepository <IRolePermissionRepository>();
                        foreach (string extension in model_.Extensions)
                        {
                            repo.Create(new RolePermission
                            {
                                RoleId       = identityRole.Id,
                                PermissionId = permissionEntity.Id,
                                Extension    = extension
                            });
                        }
                    }
                }

                await storage_.SaveAsync();

                return(null);
            }
            catch (Exception e)
            {
                return($"{e.Message} {e.StackTrace}");
            }
        }
Example #5
0
        [HttpGet] // TODO change to POST
        public async Task <IActionResult> UpdateRolePermission(string roleName_, string permissionId_, string scope_)
        {
            string roleId = (await _roleManager.FindByNameAsync(roleName_)).Id;
            IRolePermissionRepository repo = Storage.GetRepository <IRolePermissionRepository>();

            repo.Delete(roleId, scope_);
            if (!string.IsNullOrEmpty(permissionId_.ToLowerInvariant()))
            {
                repo.Create(new RolePermission {
                    RoleId = roleId, PermissionId = permissionId_.UppercaseFirst(), Scope = scope_
                });
            }
            Storage.Save();
            return(new JsonResult(true));
        }
Example #6
0
        /// <summary>
        /// First, check that a role with this name doesn't already exist.
        /// Second, save new data into database.
        /// </summary>
        /// <param name="model_">Model with role name and grant data (extensions and permission level)</param>
        /// <param name="roleManager_"></param>
        /// <param name="storage_"></param>
        /// <returns>Not null when something failed, else null when save went ok</returns>
        public static async Task <string> CheckAndSaveNewRoleAndGrants(SaveNewRoleAndGrantsViewModel model_, RoleManager <IdentityRole <string> > roleManager_, IStorage storage_)
        {
            if (await UpdateRole.CheckThatRoleOfThisNameExists(roleManager_, model_.RoleName))
            {
                return("A role with this name already exists");
            }

            try
            {
                // Convert the string to the enum
                var permissionEnum = Enum.Parse <Security.Common.Enums.Permission>(model_.Permission, true);

                // Save the Role
                IdentityRole <string> identityRole = new IdentityRole <string>
                {
                    // Auto-incremented ID
                    Name = model_.RoleName
                };
                await roleManager_.CreateAsync(identityRole);

                // Save the role-extension-permission link
                if (model_.Extensions != null)
                {
                    IRolePermissionRepository repo = storage_.GetRepository <IRolePermissionRepository>();
                    foreach (string extension in model_.Extensions)
                    {
                        repo.Create(new RolePermission
                        {
                            RoleId = identityRole.Id, PermissionId = permissionEnum.ToString(), Scope = extension
                        });
                    }
                }

                storage_.Save();

                return(null);
            }
            catch (Exception e)
            {
                return($"{e.Message} {e.StackTrace}");
            }
        }
Example #7
0
        public ActionResult Update(RoleModel vm)
        {
            ApiResult <Role> apiResult;

            if (ModelState.IsValid)
            {
                if (vm.Id > 0)
                {
                    apiResult = TryExecute(() =>
                    {
                        var selectedRole = _roleRepository.Get(vm.Id);

                        selectedRole.Name        = vm.Name;
                        selectedRole.Description = vm.Description;

                        // Clean up all Permissions
                        var permissions = _rolePermissionRepository.GetAllBy(r => r.RoleId == vm.Id).ToList();
                        foreach (var permission in permissions)
                        {
                            _rolePermissionRepository.Delete(permission);
                        }

                        _unitOfWork.Commit();

                        foreach (var permission in vm.PermissionIds)
                        {
                            var rolePermission = new RolePermission
                            {
                                RoleId       = vm.Id,
                                PermissionId = permission
                            };
                            _rolePermissionRepository.Create(rolePermission);
                        }

                        _roleRepository.Update(selectedRole);
                        _unitOfWork.Commit();

                        return(selectedRole);
                    }, "Role updated sucessfully");
                }
                else
                {
                    apiResult = TryExecute(() =>
                    {
                        var newRole = new Role
                        {
                            Name        = vm.Name,
                            Description = vm.Description
                        };

                        _roleRepository.Create(newRole);
                        _unitOfWork.Commit();

                        foreach (var permission in vm.PermissionIds)
                        {
                            var rolePermission = new RolePermission
                            {
                                RoleId       = newRole.Id,
                                PermissionId = permission
                            };
                            _rolePermissionRepository.Create(rolePermission);
                        }

                        _unitOfWork.Commit();

                        return(newRole);
                    }, "Role created sucessfully");
                }
            }
            else
            {
                apiResult = ApiResultFromModelErrors <Role>();
            }

            return(Json(apiResult, JsonRequestBehavior.AllowGet));
        }