protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.SynchroniseSubscription provisionalAuditTrailEntry)
        {
            if (Subscriptions.Any(s => s.Id == 0))
            {
                throw new ArgumentOutOfRangeException(nameof(Subscriptions), "Subscriptions.Id[] must always have values");
            }

            var subscriptionIdsParameter = (from subs in Subscriptions
                                            select new TableTypes.Products.Subscription(subs.Id))
                                           .AsTableValuedParameter("tenants.udt_Subscription");
            var databaseConnection = await dataSource.GetDbConnection();

            await databaseConnection.ExecuteAsync("tenants.usp_SyncSubscriptionsFromBillingProvider",
                                                  new
            {
                Subscription_External_Identifier = ExternalIdentifier,
                Status_ID = Status,
                Last_Invoice_External_Identifier = LatestInvoiceExternalIdentifier,
                Subscription_IDs = subscriptionIdsParameter
            }, transaction : transaction, commandType : CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.SubscriptionIds = Subscriptions.Select(s => s.Id);
            provisionalAuditTrailEntry.NewStatus       = Status;
            provisionalAuditTrailEntry.ExternalSubscriptionIdentifier  = ExternalIdentifier;
            provisionalAuditTrailEntry.LatestInvoiceExternalIdentifier = LatestInvoiceExternalIdentifier;

            return(true);
        }
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.RevokeInvitation provisionalAuditTrailEntry)
        {
            if (Invitation.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.Id must have a value");
            }
            if (Invitation.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.Tenant must have a value");
            }
            if (Invitation.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.Tenant.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = Invitation.Tenant;

            var successfullyDeleted = await databaseConnection.ExecuteScalarAsync <bool>("tenants.usp_RevokeInvitation",
                                                                                         new { Tenant_ID = Invitation.Tenant.Id, Invitation_ID = Invitation.Id },
                                                                                         transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.Invitation = Invitation;

            return(successfullyDeleted);
        }
Exemple #3
0
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.DeleteGroup provisionalAuditTrailEntry)
        {
            if (Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Id must have a value");
            }
            if (Group.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Tenant must have a value");
            }
            if (Group.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Tenant.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = Group.Tenant;

            var getGroupCommand = new Jibberwock.Persistence.DataAccess.Commands.Security.GetSecurityGroupById(Logger, Group);
            var originalGroup   = await getGroupCommand.Execute(dataSource.GetReadableDataSource());

            var successfullyDeleted = await databaseConnection.ExecuteScalarAsync <bool>("security.usp_DeleteSecurityGroup",
                                                                                         new { Tenant_ID = Group.Tenant.Id, Security_Group_ID = Group.Id },
                                                                                         transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.Group = originalGroup;

            return(successfullyDeleted);
        }
Exemple #4
0
        protected override async Task OnCommandCompleted(IReadWriteDataSource dataSource, ModifyGroup auditTrailEntry, Group result)
        {
            if (Group.Users != null)
            {
                foreach (var mem in Group.Users)
                {
                    var createMembershipCommand = new CreateSecurityGroupMembership(Logger, PerformedBy, ConnectionId, OriginatingService.Id, Comment,
                                                                                    new GroupMembership()
                    {
                        Group = Group, User = mem.User, Enabled = mem.Enabled
                    });

                    await createMembershipCommand.Execute(dataSource);
                }
            }

            if (Group.AccessControlEntries != null)
            {
                foreach (var ace in Group.AccessControlEntries)
                {
                    var createACECommand = new CreateAccessControlEntry(Logger, PerformedBy, ConnectionId, OriginatingService.Id, Comment,
                                                                        new AccessControlEntry()
                    {
                        Group = Group, Permission = ace.Permission, Resource = ace.Resource
                    });

                    await createACECommand.Execute(dataSource);
                }
            }
        }
Exemple #5
0
        protected override async Task <Group> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyGroup provisionalAuditTrailEntry)
        {
            if (Group.Id != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Id must not have a value");
            }
            if (string.IsNullOrWhiteSpace(Group.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Name must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var creationParameters = new DynamicParameters(new
            {
                Name      = Group.Name,
                Tenant_ID = Group.Tenant?.Id
            });

            creationParameters.Add("Security_Group_ID", dbType: DbType.Int64, direction: ParameterDirection.Output);

            provisionalAuditTrailEntry.RelatedTenant = Group.Tenant;

            // Create the group itself, then iterate through its ACLs and memberships, creating those
            await databaseConnection.ExecuteAsync("security.usp_CreateSecurityGroup", creationParameters,
                                                  commandType : CommandType.StoredProcedure, transaction : transaction, commandTimeout : 30);

            Group.Id = creationParameters.Get <long>("Security_Group_ID");

            provisionalAuditTrailEntry.Group    = Group;
            provisionalAuditTrailEntry.NewGroup = true;

            return(Group);
        }
        protected override async Task <Tenant> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyTenant provisionalAuditTrailEntry)
        {
            if (string.IsNullOrWhiteSpace(Tenant.ExternalId))
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.ExternalId must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            await databaseConnection.ExecuteAsync("tenants.usp_SyncTenantFromBillingProvider",
                                                  new
            {
                Tenant_ID   = Tenant.Id == 0 ? (long?)null : Tenant.Id,
                Tenant_Name = Tenant.Name,
                Tenant_External_Identifier = Tenant.ExternalId,
                Contact_Telephone_Number   = Tenant.BillingContact.TelephoneNumber,
                Contact_Email_Address      = Tenant.BillingContact.EmailAddress
            }, transaction : transaction, commandType : CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.NewTenant     = false;
            provisionalAuditTrailEntry.Tenant        = Tenant;
            provisionalAuditTrailEntry.RelatedTenant = Tenant;

            return(Tenant);
        }
Exemple #7
0
        protected override async Task <Group> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyGroup provisionalAuditTrailEntry)
        {
            if (Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Id must have a value");
            }
            if (string.IsNullOrWhiteSpace(Group.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Group), "Group.Name must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = Group.Tenant;

            var resultantGroup = await databaseConnection.QuerySingleAsync <Group>("security.usp_UpdateSecurityGroup",
                                                                                   new { Security_Group_ID = Group.Id, Name = Group.Name },
                                                                                   transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            Group = resultantGroup;

            provisionalAuditTrailEntry.Group    = resultantGroup;
            provisionalAuditTrailEntry.NewGroup = false;

            return(resultantGroup);
        }
Exemple #8
0
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.DeleteAccessControlEntry provisionalAuditTrailEntry)
        {
            if (AccessControlEntry.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Id must have a value");
            }
            if (AccessControlEntry.Group == null)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group must have a value");
            }
            if (AccessControlEntry.Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Id must have a value");
            }
            if (AccessControlEntry.Group.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Tenant must have a value");
            }
            if (AccessControlEntry.Group.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Tenant.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = AccessControlEntry.Group.Tenant;

            var successfullyDeleted = await databaseConnection.ExecuteScalarAsync <bool>("security.usp_DeleteAccessControlEntry",
                                                                                         new { Tenant_ID = AccessControlEntry.Group.Tenant.Id, Security_Group_ID = AccessControlEntry.Group.Id, Access_Control_Entry_ID = AccessControlEntry.Id },
                                                                                         transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.AccessControlEntry = AccessControlEntry;

            return(successfullyDeleted);
        }
Exemple #9
0
        protected override async Task <ProductCharacteristic> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyProductCharacteristic provisionalAuditTrailEntry)
        {
            if (ProductCharacteristic.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(ProductCharacteristic), "ProductCharacteristic.Id must have a value");
            }
            if (string.IsNullOrWhiteSpace(ProductCharacteristic.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(ProductCharacteristic), "ProductCharacteristic.Name must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var resultantCharacteristic = await databaseConnection.QuerySingleAsync <ProductCharacteristic>("products.usp_UpdateCharacteristic",
                                                                                                            new { Characteristic_ID = ProductCharacteristic.Id, Name = ProductCharacteristic.Name,
                                                                                                                  Description       = ProductCharacteristic.Description, Visible = ProductCharacteristic.Visible,
                                                                                                                  Enabled           = ProductCharacteristic.Enabled },
                                                                                                            transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            ProductCharacteristic = resultantCharacteristic;

            provisionalAuditTrailEntry.ProductCharacteristic    = resultantCharacteristic;
            provisionalAuditTrailEntry.NewProductCharacteristic = false;

            return(resultantCharacteristic);
        }
Exemple #10
0
        protected override async Task <Product> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.ModifyProduct provisionalAuditTrailEntry)
        {
            if (Product.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Product), "Product.Id not have a value");
            }
            if (string.IsNullOrWhiteSpace(Product.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Product), "Product.Name must have a value");
            }
            if (string.IsNullOrWhiteSpace(Product.MoreInformationUrl))
            {
                throw new ArgumentOutOfRangeException(nameof(Product), "Product.MoreInformationUrl must have a value");
            }
            if (Product.DefaultProductConfiguration == null)
            {
                throw new ArgumentOutOfRangeException(nameof(Product), "Product.DefaultProductConfiguration must have a value");
            }
            if (string.IsNullOrWhiteSpace(Product.DefaultProductConfiguration.ConfigurationString))
            {
                throw new ArgumentOutOfRangeException(nameof(Product), "Product.DefaultProductConfiguration.ConfigurationString must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var characteristicParameter = (from c in Product.ApplicableCharacteristics
                                           select new Jibberwock.Persistence.DataAccess.TableTypes.Products.ProductCharacteristic(c.Id))
                                          .AsTableValuedParameter("products.udt_ProductCharacteristic");
            var productUpdateBatch = await databaseConnection.QueryMultipleAsync("products.usp_UpdateProduct",
                                                                                 new
            {
                Product_ID                 = Product.Id,
                Name                       = Product.Name,
                Description                = Product.Description,
                More_Information_URL       = Product.MoreInformationUrl,
                Visible                    = Product.Visible,
                Configuration_Control_Name = Product.ConfigurationControlName,
                Configuration_String       = Product.DefaultProductConfiguration.ConfigurationString,
                Characteristics            = characteristicParameter
            },
                                                                                 transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            var resultantProduct = await productUpdateBatch.ReadSingleOrDefaultAsync <Product>();

            var resultantProductConfig = await productUpdateBatch.ReadSingleOrDefaultAsync <RawProductConfiguration>();

            var resultantCharacteristics = await productUpdateBatch.ReadAsync <ProductCharacteristic>();

            resultantProduct.DefaultProductConfiguration = resultantProductConfig;
            resultantProduct.ApplicableCharacteristics   = resultantCharacteristics;

            Product = resultantProduct;

            provisionalAuditTrailEntry.Product    = resultantProduct;
            provisionalAuditTrailEntry.NewProduct = false;

            return(resultantProduct);
        }
Exemple #11
0
        protected override async Task <Subscription> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.Subscription provisionalAuditTrailEntry)
        {
            if (Subscription.Id != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Subscription), "Subscription.Id must not have a value");
            }
            if (Subscription.ProductTier == null)
            {
                throw new ArgumentNullException(nameof(Subscription), "Subscription.ProductTier must have a value");
            }
            if (Subscription.ProductTier.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Subscription), "Subscription.ProductTier.Id must have a value");
            }
            if (Subscription.Configuration == null)
            {
                throw new ArgumentNullException(nameof(Subscription), "Subscription.Configuration must have a value");
            }
            if (string.IsNullOrWhiteSpace(Subscription.Configuration.ConfigurationString))
            {
                throw new ArgumentNullException(nameof(Subscription), "Subscription.Configuration.ConfigurationString must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var subscriptions = await databaseConnection.QueryAsync <Subscription, Tenant, Tier, Subscription>("tenants.usp_CreateSubscription",
                                                                                                               (sub, ten, tier) =>
            {
                if (ten != null && ten.Id != 0)
                {
                    sub.Tenant = ten;
                }
                if (tier != null & tier.Id != 0)
                {
                    sub.ProductTier = tier;
                }

                return(sub);
            },
                                                                                                               new
            {
                Tenant_ID             = Subscription.Tenant.Id,
                Tier_ID               = Subscription.ProductTier.Id,
                Product_Configuration = Subscription.Configuration.ConfigurationString,
                Start_Date            = Subscription.StartDate,
                End_Date              = Subscription.EndDate
            },
                                                                                                               transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            var resultantSubscription = subscriptions.FirstOrDefault();

            Subscription = resultantSubscription;
            provisionalAuditTrailEntry.ResultantSubscription = resultantSubscription;
            provisionalAuditTrailEntry.RelatedTenant         = resultantSubscription.Tenant;

            return(resultantSubscription);
        }
        protected override async Task <GroupMembership> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyGroupMembership provisionalAuditTrailEntry)
        {
            if (GroupMembership.Group == null)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group must have a value");
            }
            if (GroupMembership.Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Id must have a value");
            }
            if (GroupMembership.Group.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Tenant must have a value");
            }
            if (GroupMembership.Group.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Tenant.Id must have a value");
            }
            if (GroupMembership.User == null)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.User must have a value");
            }
            if (GroupMembership.User.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.User.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = GroupMembership.Group.Tenant;
            provisionalAuditTrailEntry.RelatedUser   = GroupMembership.User;

            var resultantMemberships = await databaseConnection.QueryAsync <GroupMembership, Group, User, GroupMembership>("security.usp_CreateSecurityGroupMembership",
                                                                                                                           (sgm, grp, usr) =>
            {
                if (sgm != null && grp != null)
                {
                    sgm.Group = grp;
                }

                if (sgm != null && usr != null)
                {
                    sgm.User = usr;
                }

                return(sgm);
            },
                                                                                                                           new { Tenant_ID = GroupMembership.Group.Tenant.Id, Security_Group_ID = GroupMembership.Group.Id, Member_User_ID = GroupMembership.User.Id, Enabled = GroupMembership.Enabled },
                                                                                                                           transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            GroupMembership = resultantMemberships.FirstOrDefault();

            provisionalAuditTrailEntry.GroupMembership    = GroupMembership;
            provisionalAuditTrailEntry.NewGroupMembership = true;

            return(GroupMembership);
        }
Exemple #13
0
        protected override async Task <Tier> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.ModifyTier provisionalAuditTrailEntry)
        {
            if (Tier.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Tier), "Tier.Id must have a value");
            }
            if (string.IsNullOrWhiteSpace(Tier.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Tier), "Tier.Name must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var characteristicParameter = (from c in Tier.Characteristics
                                           select new Jibberwock.Persistence.DataAccess.TableTypes.Products.TierCharacteristicValue(c.ProductCharacteristic.Id, c.CharacteristicValue))
                                          .AsTableValuedParameter("products.udt_TierCharacteristicValue");
            var updateTierResultSet = await databaseConnection.QueryMultipleAsync("products.usp_UpdateProductTier",
                                                                                  new
            {
                Product_ID            = Tier.Product.Id,
                Tier_ID               = Tier.Id,
                User_ID               = PerformedBy.Id,
                Name                  = Tier.Name,
                Visible               = Tier.Visible,
                Start_Date            = Tier.StartDate,
                End_Date              = Tier.EndDate,
                Characteristic_Values = characteristicParameter
            },
                                                                                  transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            var resultantTier = await updateTierResultSet.ReadSingleAsync <Tier>();

            var characteristicValues = await updateTierResultSet.ReadAsync <dynamic>();

            resultantTier.Characteristics = (from cV in characteristicValues
                                             select new TierProductCharacteristic()
            {
                Id = cV.Id,
                CharacteristicValue = cV.CharacteristicValue,
                ProductCharacteristic = new ProductCharacteristic()
                {
                    Id = cV.CharacteristicId,
                    Name = cV.Name,
                    Description = cV.Description,
                    Visible = cV.Visible,
                    Enabled = cV.Enabled,
                    ValueType = (ProductCharacteristicValueType)cV.ValueType
                }
            }).ToArray();

            Tier = resultantTier;

            provisionalAuditTrailEntry.Tier    = resultantTier;
            provisionalAuditTrailEntry.NewTier = false;

            return(Tier);
        }
Exemple #14
0
        /// <summary>
        /// Converts an <see cref="IReadWriteDataSource"/> into an <see cref="IReadableDataSource"/>.
        /// </summary>
        /// <param name="dataSource">The <see cref="IReadWriteDataSource"/> to convert.</param>
        /// <returns>An <see cref="IReadableDataSource"/>.</returns>
        public static IReadableDataSource GetReadableDataSource(this IReadWriteDataSource dataSource)
        {
            if (dataSource == null)
            {
                throw new ArgumentNullException(nameof(dataSource));
            }

            if (dataSource is SqlServerDataSource sqlServerDataSource)
            {
                return(sqlServerDataSource);
            }

            throw new InvalidCastException($"{nameof(dataSource)} is not an expected type");
        }
Exemple #15
0
        /// <summary>
        /// Gets the correct database connection from this <see cref="IReadWriteDataSource"/>.
        /// </summary>
        /// <param name="dataSource">The <see cref="IReadWriteDataSource"/> to get the database connection from.</param>
        /// <returns>The associated database connection.</returns>
        public static async Task <IDbConnection> GetDbConnection(this IReadWriteDataSource dataSource)
        {
            if (dataSource == null)
            {
                throw new ArgumentNullException(nameof(dataSource));
            }

            if (dataSource is SqlServerDataSource sqlServerDataSource)
            {
                return(await sqlServerDataSource.GetReadWriteDatabaseConnection());
            }

            throw new InvalidCastException($"{nameof(dataSource)} is not an expected type");
        }
Exemple #16
0
        protected override async Task OnCommandCompleted(IReadWriteDataSource dataSource, InviteUser auditTrailEntry, Invitation result)
        {
            var emailQueueClient = SendAsEmail ? _queueDataSource.GetQueueClient(_emailQueueName) : null;

            if (result.EmailBatch != null)
            {
                // If we've got an email batch, then we need to put the message onto the queue!
                var messageToCreate = ServiceBusUtilities.GenerateMessage(new { Metadata = new { baseUrl = _baseUrl } }, result.EmailBatch.ServiceBusMessageId);

                await emailQueueClient.SendAsync(messageToCreate);

                // Don't need to expose this to the clients though
                Invitation.EmailBatch.ServiceBusMessageId = null;
            }
        }
Exemple #17
0
        protected override async Task <Tenant> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyTenant provisionalAuditTrailEntry)
        {
            if (Tenant.Id != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.Id must not have a value");
            }
            if (string.IsNullOrWhiteSpace(Tenant.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.Name must have a value");
            }
            if (Tenant.BillingContact == null)
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.BillingContact must have a value");
            }
            if (Tenant.BillingContact.Id != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.BillingContact.Id must not have a value");
            }
            if (string.IsNullOrWhiteSpace(Tenant.BillingContact.FullName))
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.BillingContact.FullName must have a value");
            }
            if (string.IsNullOrWhiteSpace(Tenant.BillingContact.EmailAddress) && string.IsNullOrWhiteSpace(Tenant.BillingContact.TelephoneNumber))
            {
                throw new ArgumentOutOfRangeException(nameof(Tenant), "Tenant.BillingContact.EmailAddress or Tenant.BillingContact.TelephoneNumber must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var tenantId = await databaseConnection.ExecuteScalarAsync <long>("tenants.usp_CreateTenant",
                                                                              new
            {
                Name                     = Tenant.Name,
                Contact_Name             = Tenant.BillingContact.FullName,
                Contact_Telephone_Number = Tenant.BillingContact.TelephoneNumber,
                Contact_Email_Address    = Tenant.BillingContact.EmailAddress,
                Current_User_ID          = PerformedBy.Id
            }, transaction : transaction, commandType : CommandType.StoredProcedure, commandTimeout : 30);

            Tenant.Id = tenantId;

            provisionalAuditTrailEntry.NewTenant     = true;
            provisionalAuditTrailEntry.Tenant        = Tenant;
            provisionalAuditTrailEntry.RelatedTenant = Tenant;

            return(Tenant);
        }
Exemple #18
0
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.ControlUserAccess provisionalAuditTrailEntry)
        {
            if (User.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(User), "User.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var successfullyControlled = await databaseConnection.ExecuteScalarAsync <int>("security.usp_ControlUserAccess",
                                                                                           new { User_ID = User.Id, Enabled = User.Enabled },
                                                                                           transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.RelatedUser = User;
            provisionalAuditTrailEntry.Enabled     = User.Enabled;

            return(successfullyControlled == 0);
        }
        protected override async Task OnCommandCompleted(IReadWriteDataSource dataSource, ModifyNotification auditTrailEntry, Notification result)
        {
            if (result.EmailBatch != null)
            {
                if (_sendEmail)
                {
                    var emailQueueClient = SendAsEmail ? _queueDataSource.GetQueueClient(_emailQueueName) : null;

                    // If we've created an email batch, then we need to put the message onto the queue!
                    var messageToCreate = ServiceBusUtilities.GenerateMessage(new { Metadata = default(object) }, result.EmailBatch.ServiceBusMessageId, result.StartDate);

                    await emailQueueClient.SendAsync(messageToCreate);
                }

                // Make sure we don't expose the queue's message ID - clients don't need to care
                result.EmailBatch.ServiceBusMessageId = null;
            }
        }
Exemple #20
0
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, DismissNotification provisionalAuditTrailEntry)
        {
            if (Notification.Id == 0)
            {
                throw new ArgumentNullException(nameof(Notification), "Notification.Id must have a value.");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var success = await databaseConnection.ExecuteScalarAsync <bool>("core.usp_DismissNotification",
                                                                             new
            {
                Calling_User_ID = PerformedBy.Id,
                Notification_ID = Notification.Id
            }, commandType : CommandType.StoredProcedure, transaction : transaction, commandTimeout : 30);

            provisionalAuditTrailEntry.Notification = Notification;

            return(success);
        }
Exemple #21
0
        protected override async Task <Tier> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, Jibberwock.DataModels.Security.Audit.EntryTypes.ModifyTier provisionalAuditTrailEntry)
        {
            if (Tier.Id != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Tier), "Tier.Id must not have a value");
            }
            if (string.IsNullOrWhiteSpace(Tier.Name))
            {
                throw new ArgumentOutOfRangeException(nameof(Tier), "Tier.Name must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var characteristicParameter = (from c in Tier.Characteristics
                                           select new Jibberwock.Persistence.DataAccess.TableTypes.Products.TierCharacteristicValue(c.ProductCharacteristic.Id, c.CharacteristicValue))
                                          .AsTableValuedParameter("products.udt_TierCharacteristicValue");
            var tierCreated = await databaseConnection.ExecuteScalarAsync <long>("products.usp_CreateProductTier",
                                                                                 new
            {
                Product_ID            = Tier.Product.Id,
                Name                  = Tier.Name,
                External_Identifier   = Tier.ExternalId,
                Visible               = Tier.Visible,
                Start_Date            = Tier.StartDate,
                End_Date              = Tier.EndDate,
                Characteristic_Values = characteristicParameter
            },
                                                                                 transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            Tier.Id = tierCreated;

            provisionalAuditTrailEntry.Tier    = Tier;
            provisionalAuditTrailEntry.NewTier = true;

            return(Tier);
        }
Exemple #22
0
        protected override async Task <bool> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, DeleteGroupMembership provisionalAuditTrailEntry)
        {
            if (GroupMembership.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Id must have a value");
            }
            if (GroupMembership.Group == null)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group must have a value");
            }
            if (GroupMembership.Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Id must have a value");
            }
            if (GroupMembership.Group.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Tenant must have a value");
            }
            if (GroupMembership.Group.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(GroupMembership), "GroupMembership.Group.Tenant.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = GroupMembership.Group.Tenant;

            var successfullyDeleted = await databaseConnection.ExecuteScalarAsync <bool>("security.usp_DeleteSecurityGroupMembership",
                                                                                         new { Tenant_ID = GroupMembership.Group.Tenant.Id, Security_Group_Membership_ID = GroupMembership.Id },
                                                                                         transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.RelatedUser     = GroupMembership.User;
            provisionalAuditTrailEntry.GroupMembership = GroupMembership;

            return(successfullyDeleted);
        }
Exemple #23
0
 protected abstract Task <TResult> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, TAuditTrailEntry provisionalAuditTrailEntry);
Exemple #24
0
        protected override async Task <Invitation> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, InviteUser provisionalAuditTrailEntry)
        {
            if (Invitation.Tenant == null)
            {
                throw new ArgumentNullException(nameof(Invitation), "Invitation.Tenant must have a value.");
            }
            if (Invitation.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.Tenant.Id must have a value.");
            }
            if (string.IsNullOrWhiteSpace(Invitation.EmailAddress))
            {
                throw new ArgumentNullException(nameof(Invitation), "Invitation.EmailAddress must have a value.");
            }
            if (Invitation.EmailAddress.Length > 256)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.EmailAddress must be less than or equal to 256 characters long.");
            }
            if (string.IsNullOrWhiteSpace(Invitation.ExternalIdentityProvider))
            {
                throw new ArgumentNullException(nameof(Invitation), "Invitation.ExternalIdentityProvider must have a value.");
            }
            if (Invitation.ExternalIdentityProvider.Length > 32)
            {
                throw new ArgumentOutOfRangeException(nameof(Invitation), "Invitation.ExternalIdentityProvider must be less than or equal to 32 characters long.");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            // This is a multi-step approach. We create the record in the database, then generate
            // a message using the QueueClient, then return
            var createdInvitations = await databaseConnection.QueryAsync <Invitation, Tenant, EmailBatch, Invitation>("tenants.usp_CreateInvitation",
                                                                                                                      (inv, ten, eb) =>
            {
                if (ten != null && ten.Id != 0)
                {
                    inv.Tenant = ten;
                }

                if (eb != null && eb.Id != 0)
                {
                    inv.EmailBatch = eb;
                }
                return(inv);
            }, new
            {
                Tenant_ID         = Invitation.Tenant.Id,
                Email_Address     = Invitation.EmailAddress,
                Identity_Provider = Invitation.ExternalIdentityProvider,
                Expiration_Date   = Invitation.ExpirationDate,
                Send_As_Email     = SendAsEmail
            }, commandType : CommandType.StoredProcedure, transaction : transaction, commandTimeout : 30);

            var resultantInvitation = createdInvitations.FirstOrDefault();

            Invitation = resultantInvitation;

            provisionalAuditTrailEntry.EmailBatch    = Invitation.EmailBatch;
            provisionalAuditTrailEntry.RelatedUser   = Invitation.InvitedUser;
            provisionalAuditTrailEntry.RelatedTenant = Invitation.Tenant;

            return(Invitation);
        }
Exemple #25
0
 protected virtual Task OnCommandCompleted(IReadWriteDataSource dataSource, TAuditTrailEntry auditTrailEntry, TResult result)
 {
     return(Task.CompletedTask);
 }
Exemple #26
0
        protected override async Task <AuditedCommandResult <TResult, TAuditTrailEntry> > OnExecute(IReadWriteDataSource dataSource)
        {
            // The audit trail entry and the command will execute in the same transaction
            var databaseConnection = await dataSource.GetDbConnection() as DbConnection;

            var dbTransaction = await databaseConnection.BeginTransactionAsync();

            try
            {
                var auditTrailEntry = new TAuditTrailEntry()
                {
                    Occurrence              = DateTimeOffset.Now,
                    PerformedBy             = PerformedBy,
                    OriginatingConnectionId = ConnectionId,
                    OriginatingService      = OriginatingService,
                    Comment = Comment
                };
                // Provide a spot for the derived classes to execute their command as required, making any final tweaks to the audit trail entry
                var result = await OnAuditedExecute(dataSource, dbTransaction, auditTrailEntry);

                // Create the audit trail entry itself, updating our ID
                auditTrailEntry.Id = await databaseConnection.ExecuteScalarAsync <long>("security.usp_CreateAuditTrailEntry",
                                                                                        new
                {
                    Audit_Trail_Type_ID       = auditTrailEntry.Type,
                    Occurrence_Time           = auditTrailEntry.Occurrence,
                    User_ID                   = auditTrailEntry.RelatedUser?.Id,
                    Tenant_ID                 = auditTrailEntry.RelatedTenant?.Id,
                    Performed_By_User_ID      = auditTrailEntry.PerformedBy?.Id,
                    Originating_Connection_ID = auditTrailEntry.OriginatingConnectionId,
                    Originating_Service_ID    = auditTrailEntry.OriginatingService?.Id,
                    Comment                   = auditTrailEntry.Comment,
                    Metadata                  = auditTrailEntry.Metadata,
                    Result_Value_Type         = 1
                },
                                                                                        transaction : dbTransaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

                // Commit the transaction
                await dbTransaction.CommitAsync();

                // Perform any post-commit activity. This handles situations where some work needs to be performed in an external system (like
                // sending a message to Service Bus) which needs a database record to be created
                await OnCommandCompleted(dataSource, auditTrailEntry, result);

                return(new AuditedCommandResult <TResult, TAuditTrailEntry>(result, auditTrailEntry));
            }
            catch (Exception)
            {
                // If there's an exception, roll the transaction back and rethrow
                await dbTransaction.RollbackAsync();

                throw;
            }
            finally
            {
                if (dbTransaction != null)
                {
                    await dbTransaction.DisposeAsync();
                }
            }
        }
        protected override async Task <Notification> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyNotification provisionalAuditTrailEntry)
        {
            if (Notification.Priority == null)
            {
                throw new ArgumentNullException(nameof(Notification), "Notification.Priority must have a value.");
            }
            if (string.IsNullOrWhiteSpace(Notification.Priority.Name))
            {
                throw new ArgumentNullException(nameof(Notification), "Notification.Priority.Name must have a value.");
            }
            if (Notification.Priority.Name.Length > 32)
            {
                throw new ArgumentOutOfRangeException(nameof(Notification), "Notification.Priority.Name must be less than or equal to 32 characters long.");
            }
            if (string.IsNullOrWhiteSpace(Notification.Subject))
            {
                throw new ArgumentNullException(nameof(Notification), "Notification.Subject must have a value.");
            }
            if (Notification.Subject.Length > 128)
            {
                throw new ArgumentOutOfRangeException(nameof(Notification), "Notification.Subject must be less than or equal to 128 characters long.");
            }
            if (string.IsNullOrWhiteSpace(Notification.Message))
            {
                throw new ArgumentNullException(nameof(Notification), "Notification.Message must have a value.");
            }

            if ((Notification.TargetUser != null && Notification.TargetUser.Id != 0) &&
                (Notification.TargetTenant != null && Notification.TargetTenant.Id != 0))
            {
                throw new ArgumentOutOfRangeException(nameof(Notification), "A notification cannot target both a tenant and a user,");
            }
            ;

            var databaseConnection = await dataSource.GetDbConnection();

            // This is a multi-step approach. We create the record in the database, then generate
            // a message using the QueueClient, then return
            var updateNotificationParameters = new DynamicParameters(new
            {
                Notification_ID = Notification.Id,
                Status_ID       = Notification.Status,
                Type_ID         = Notification.Type,
                Priority_Name   = Notification.Priority?.Name,
                Start_Date      = Notification.StartDate,
                End_Date        = Notification.EndDate,
                Subject         = Notification.Subject,
                Message         = Notification.Message,
                Allow_Dismissal = Notification.AllowDismissal,
                Send_As_Email   = SendAsEmail
            });

            updateNotificationParameters.Add("New_Email_Message_Required", dbType: DbType.Boolean, direction: ParameterDirection.Output);

            var updatedNotifications = await databaseConnection.QueryAsync <Notification, NotificationPriority, User, Tenant, EmailBatch, Notification>("core.usp_UpdateNotification",
                                                                                                                                                        (n, np, usr, ten, eb) =>
            {
                n.Priority = np;

                if (usr != null && usr.Id != 0)
                {
                    n.TargetUser = usr;
                }

                if (ten != null && ten.Id != 0)
                {
                    n.TargetTenant = ten;
                }

                if (eb != null && eb.Id != 0)
                {
                    n.EmailBatch = eb;
                }
                return(n);
            }, updateNotificationParameters,
                                                                                                                                                        commandType : CommandType.StoredProcedure, transaction : transaction, commandTimeout : 30);

            var resultantNotification = updatedNotifications.FirstOrDefault();

            Notification = resultantNotification;
            _sendEmail   = updateNotificationParameters.Get <bool>("New_Email_Message_Required");

            provisionalAuditTrailEntry.ServiceBusMessageId = Notification.EmailBatch?.ServiceBusMessageId;

            provisionalAuditTrailEntry.Notification    = Notification;
            provisionalAuditTrailEntry.RelatedUser     = Notification.TargetUser;
            provisionalAuditTrailEntry.RelatedTenant   = Notification.TargetTenant;
            provisionalAuditTrailEntry.NewNotification = false;
            provisionalAuditTrailEntry.SendAsEmail     = SendAsEmail;

            return(Notification);
        }
Exemple #28
0
        protected override async Task <DeleteCharacteristicStatusCode> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, DeleteProductCharacteristic provisionalAuditTrailEntry)
        {
            if (ProductCharacteristic.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(ProductCharacteristic), "ProductCharacteristic.Id must have a value");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            var deletedCharacteristic = await databaseConnection.ExecuteScalarAsync <DeleteCharacteristicStatusCode>("products.usp_DeleteCharacteristic",
                                                                                                                     new { Characteristic_ID = ProductCharacteristic.Id },
                                                                                                                     transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            provisionalAuditTrailEntry.ProductCharacteristic = ProductCharacteristic;

            return(deletedCharacteristic);
        }
        protected override async Task <AccessControlEntry> OnAuditedExecute(IReadWriteDataSource dataSource, IDbTransaction transaction, ModifyAccessControlEntry provisionalAuditTrailEntry)
        {
            if (AccessControlEntry.Group == null)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group must have a value");
            }
            if (AccessControlEntry.Group.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Id must have a value");
            }
            if (AccessControlEntry.Group.Tenant == null)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Tenant must have a value");
            }
            if (AccessControlEntry.Group.Tenant.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Group.Tenant.Id must have a value");
            }
            if (AccessControlEntry.Resource == null)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Resource must have a value");
            }
            if (AccessControlEntry.Resource.Id == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Resource.Id must have a value");
            }
            if (!Enum.IsDefined(typeof(Permission), AccessControlEntry.Permission))
            {
                throw new ArgumentOutOfRangeException(nameof(AccessControlEntry), "AccessControlEntry.Permission must be a valid Permission");
            }

            var databaseConnection = await dataSource.GetDbConnection();

            provisionalAuditTrailEntry.RelatedTenant = AccessControlEntry.Group.Tenant;

            var resultantAccessControlEntry = await databaseConnection.QueryAsync <AccessControlEntry, Group, dynamic, Tenant, AccessControlEntry>("security.usp_CreateAccessControlEntry",
                                                                                                                                                   (ace, grp, sr, ten) =>
            {
                if (ace != null && grp != null)
                {
                    ace.Group = grp;
                }

                if (ace != null && sr != null)
                {
                    ace.Resource = SecurableResourceHelpers.GetSecurableResourceFromDatabase(sr);
                }

                if (ace != null && ten != null)
                {
                    ace.ResourceTenant = ten;
                }

                return(ace);
            },
                                                                                                                                                   new
            {
                Tenant_ID             = AccessControlEntry.Group.Tenant.Id,
                User_ID               = PerformedBy.Id,
                Security_Group_ID     = AccessControlEntry.Group.Id,
                Securable_Resource_ID = AccessControlEntry.Resource.Id,
                Permission_ID         = AccessControlEntry.Permission
            },
                                                                                                                                                   transaction : transaction, commandType : System.Data.CommandType.StoredProcedure, commandTimeout : 30);

            AccessControlEntry = resultantAccessControlEntry.FirstOrDefault();

            provisionalAuditTrailEntry.AccessControlEntry    = AccessControlEntry;
            provisionalAuditTrailEntry.NewAccessControlEntry = true;

            return(AccessControlEntry);
        }