예제 #1
0
 public AppGroup Insert(AppGroup appGroup)
 {
     if (_appGroupRepo.CheckContains(x => x.Name == appGroup.Name))
     {
         throw new NameDuplicatedException("Tên không được trùng");
     }
     return(_appGroupRepo.Insert(appGroup));
 }
        public IActionResult Create([FromBody] CreateUserGroupModel model)
        {
            if (!_currentUser.HasRole(Permission.UserAccountAdmin))
            {
                return(Forbidden());
            }

            _logger.LogInformation("Creating a new user group: {0}", model.Name);
            _logger.LogDebug("Request body: {0}", JsonSerializer.Serialize(model));

            Result <string> name = ((Maybe <string>)model.Name)
                                   .ToResult("User group name is not specified")
                                   .OnSuccess(d => d.Trim())
                                   .Ensure(d => d.Length >= 5, "User group name is too short")
                                   .Ensure(d => d.Length <= 50, "User group name is too long")
                                   .Ensure(d => new Regex(@"^([a-zA-Z0-9 ])*$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(2)).IsMatch(d)
                                           , "User group contains invalid characters");

            Result <string> description = ((Maybe <string>)model.Description)
                                          .ToResult("User group description is not specified")
                                          .OnSuccess(d => d.Trim())
                                          .Ensure(d => d.Length <= 250, "User group name is too long");

            Result result = Result.Combine(name, description);

            if (result.IsFailure)
            {
                return(Error(result.Error));
            }

            if (_groupRepo.HasGroup(name.Value))
            {
                return(Error("Specified user group already exist"));
            }

            AppGroup group = new AppGroup(name.Value, description.Value);

            model.SelectedPermissions ??= new string[] { };

            if (model.SelectedPermissions.Any()) // has selected permissions
            {
                Result <List <AppPermission> > selectedPermissions = GetMatchingPermissions(_permissionRepo, model.SelectedPermissions);
                if (selectedPermissions.IsFailure)
                {
                    return(Error(selectedPermissions.Error));
                }

                group.AddPermissions(selectedPermissions.Value);
            }

            _groupRepo.Insert(group);

            return(Ok("User group added"));
        }