diff --git a/Disco.BI/BI/DataStore.cs b/Disco.BI/BI/DataStore.cs index 3d907da5..e5dafcbc 100644 --- a/Disco.BI/BI/DataStore.cs +++ b/Disco.BI/BI/DataStore.cs @@ -10,9 +10,9 @@ namespace Disco.BI public static class DataStore { - public static string CreateLocation(DiscoDataContext dbContext, string SubLocation, DateTime? SubSubLocationTimestamp = null) + public static string CreateLocation(DiscoDataContext Database, string SubLocation, DateTime? SubSubLocationTimestamp = null) { - return CreateLocation(dbContext.DiscoConfiguration, SubLocation, SubSubLocationTimestamp); + return CreateLocation(Database.DiscoConfiguration, SubLocation, SubSubLocationTimestamp); } public static string CreateLocation(SystemConfiguration DiscoConfiguration, string SubLocation, DateTime? SubSubLocationTimestamp = null) { diff --git a/Disco.BI/BI/DeviceBI/BatchUtilities.cs b/Disco.BI/BI/DeviceBI/BatchUtilities.cs index 31ac7538..ca6a630a 100644 --- a/Disco.BI/BI/DeviceBI/BatchUtilities.cs +++ b/Disco.BI/BI/DeviceBI/BatchUtilities.cs @@ -9,7 +9,7 @@ namespace Disco.BI.DeviceBI { public static class BatchUtilities { - public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext dbContext) + public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext Database) { return new DeviceBatch() { diff --git a/Disco.BI/BI/DeviceBI/DeviceModelBI.cs b/Disco.BI/BI/DeviceBI/DeviceModelBI.cs index ad7d70cc..bffe8101 100644 --- a/Disco.BI/BI/DeviceBI/DeviceModelBI.cs +++ b/Disco.BI/BI/DeviceBI/DeviceModelBI.cs @@ -32,7 +32,7 @@ namespace Disco.BI if (deviceModel == null) { // Create the Device Model in a different DataContext so we don't have to commit unrelated changes - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { var addDeviceModel = new DeviceModel { @@ -41,8 +41,8 @@ namespace Disco.BI ModelType = ModelType, Description = string.Format("{0} {1}", Manufacturer, Model) }; - dbContext.DeviceModels.Add(addDeviceModel); - dbContext.SaveChanges(); + database.DeviceModels.Add(addDeviceModel); + database.SaveChanges(); } // Obtain the Device Model with the in-scope DataContext diff --git a/Disco.BI/BI/DeviceBI/Enrol.cs b/Disco.BI/BI/DeviceBI/Enrol.cs index f846e0a0..9ecc0906 100644 --- a/Disco.BI/BI/DeviceBI/Enrol.cs +++ b/Disco.BI/BI/DeviceBI/Enrol.cs @@ -11,6 +11,8 @@ using Disco.Models.Repository; using Tamir.SharpSsh; using Disco.Services.Plugins; using Disco.Services.Plugins.Features.CertificateProvider; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.DeviceBI { @@ -24,7 +26,7 @@ namespace Disco.BI.DeviceBI } private static Regex SshPromptRegEx = new Regex("[\\$,\\#]", RegexOptions.Multiline); - public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext dbContext, string Host) + public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext Database, string Host) { MacEnrol trustedRequest = new MacEnrol(); string sessionId = System.Guid.NewGuid().ToString("B"); @@ -32,8 +34,8 @@ namespace Disco.BI.DeviceBI try { EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure); - EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername)); - SshShell shell = new SshShell(Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername, dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); + EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, Database.DiscoConfiguration.Bootstrapper.MacSshUsername)); + SshShell shell = new SshShell(Host, Database.DiscoConfiguration.Bootstrapper.MacSshUsername, Database.DiscoConfiguration.Bootstrapper.MacSshPassword); try { shell.ExpectPattern = "#"; @@ -55,7 +57,7 @@ namespace Disco.BI.DeviceBI output = shell.Expect(":"); EnrolmentLog.LogSessionProgress(sessionId, 27, "Connected, Elevating Credentials"); EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); - shell.WriteLine(dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); + shell.WriteLine(Database.DiscoConfiguration.Bootstrapper.MacSshPassword); System.Threading.Thread.Sleep(250); output = shell.Expect(SshPromptRegEx); sessionElevated = true; @@ -96,7 +98,7 @@ namespace Disco.BI.DeviceBI shell.Close(); } EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment"); - MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(dbContext, trustedRequest, true, sessionId)); + MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(Database, trustedRequest, true, sessionId)); EnrolmentLog.LogSessionFinished(sessionId); MacSecureEnrol = response; } @@ -211,7 +213,7 @@ namespace Disco.BI.DeviceBI #endregion - public static MacEnrolResponse MacEnrol(DiscoDataContext dbContext, MacEnrol Request, bool Trusted, string OpenSessionId = null) + public static MacEnrolResponse MacEnrol(DiscoDataContext Database, MacEnrol Request, bool Trusted, string OpenSessionId = null) { string sessionId; if (OpenSessionId == null) @@ -228,7 +230,7 @@ namespace Disco.BI.DeviceBI try { EnrolmentLog.LogSessionProgress(sessionId, 10, "Querying Database"); - Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); + Device RepoDevice = Database.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); if (!Trusted) { if (RepoDevice == null) @@ -240,9 +242,9 @@ namespace Disco.BI.DeviceBI { EnrolmentLog.LogSessionProgress(sessionId, 50, "New Device, Building Disco Instance"); EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); - DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); + DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); - var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); DeviceModel deviceModel = deviceModelResult.Item1; if (deviceModelResult.Item2) EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); @@ -259,7 +261,7 @@ namespace Disco.BI.DeviceBI CreatedDate = DateTime.Now, EnrolledDate = DateTime.Now }; - dbContext.Devices.Add(RepoDevice); + Database.Devices.Add(RepoDevice); } else { @@ -267,7 +269,7 @@ namespace Disco.BI.DeviceBI EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1) { - var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); DeviceModel deviceModel = deviceModelResult.Item1; if (deviceModelResult.Item2) EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); @@ -295,11 +297,11 @@ namespace Disco.BI.DeviceBI if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null) { ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); - EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); - response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; + EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier); + response.DeviceAssignedUserUsername = AssignedUserInfo.SamAccountName; response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; - response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; + response.DeviceAssignedUserSID = AssignedUserInfo.SecurityIdentifier; } response.DeviceComputerName = RepoDevice.ComputerName; EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); @@ -321,11 +323,11 @@ namespace Disco.BI.DeviceBI } return response; } - public static EnrolResponse Enrol(DiscoDataContext dbContext, string Username, Models.ClientServices.Enrol Request) + public static EnrolResponse Enrol(DiscoDataContext Database, string Username, Models.ClientServices.Enrol Request) { ActiveDirectoryMachineAccount MachineInfo = null; EnrolResponse response = new EnrolResponse(); - User authenticatedUser = null; + AuthorizationToken authenticatedToken = null; bool isAuthenticated = false; string sessionId = System.Guid.NewGuid().ToString("B"); response.SessionId = sessionId; @@ -336,21 +338,21 @@ namespace Disco.BI.DeviceBI EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data"); if (!string.IsNullOrWhiteSpace(Username)) { - authenticatedUser = UserBI.UserCache.GetUser(Username, dbContext); - isAuthenticated = (authenticatedUser != null); + authenticatedToken = UserService.GetAuthorization(Username, Database); + isAuthenticated = (authenticatedToken != null); } EnrolmentLog.LogSessionProgress(sessionId, 13, "Loading Device Data"); - Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); + Device RepoDevice = Database.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); EnrolmentLog.LogSessionProgress(sessionId, 15, "Discovering User/Device Disco Permissions"); if (isAuthenticated) { - if (authenticatedUser.Type != "Admin") + if (!authenticatedToken.Has(Claims.Device.Actions.EnrolDevices)) { - if (authenticatedUser.Type != "Computer") - throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); - if (!authenticatedUser.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase)) - throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); + if (authenticatedToken.Has(Claims.ComputerAccount)) + throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id)); + if (!authenticatedToken.User.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase)) + throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1})", Request.DeviceSerialNumber, authenticatedToken.User.Id)); } } else @@ -375,10 +377,10 @@ namespace Disco.BI.DeviceBI { EnrolmentLog.LogSessionProgress(sessionId, 30, "New Device, Creating Disco Instance"); EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); - DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); + DeviceProfile deviceProfile = Database.DeviceProfiles.Find(Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); - var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); DeviceModel deviceModel = deviceModelResult.Item1; if (deviceModelResult.Item2) EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); @@ -396,14 +398,14 @@ namespace Disco.BI.DeviceBI EnrolledDate = DateTime.Now, LastEnrolDate = DateTime.Now }; - dbContext.Devices.Add(RepoDevice); + Database.Devices.Add(RepoDevice); } else { EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance"); EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); - var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + var deviceModelResult = Database.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); DeviceModel deviceModel = deviceModelResult.Item1; if (deviceModelResult.Item2) EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); @@ -425,7 +427,7 @@ namespace Disco.BI.DeviceBI { EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account"); if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention) - RepoDevice.ComputerName = RepoDevice.ComputerNameRender(dbContext); + RepoDevice.ComputerName = RepoDevice.ComputerNameRender(Database); EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName); MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName); response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); @@ -458,7 +460,7 @@ namespace Disco.BI.DeviceBI // Enforce Computer Name Convention if (RepoDevice.DeviceProfile.EnforceComputerNameConvention) { - var calculatedComputerName = RepoDevice.ComputerNameRender(dbContext); + var calculatedComputerName = RepoDevice.ComputerNameRender(Database); if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase)) { EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName)); @@ -476,15 +478,18 @@ namespace Disco.BI.DeviceBI // Enforce Organisation Unit if (response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit) { - if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && MachineInfo.ParentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU - || !MachineInfo.ParentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU + var parentDistinguishedName = MachineInfo.ParentDistinguishedName(); + + if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && parentDistinguishedName != null + && parentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU + || !parentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU { string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers"; - EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", MachineInfo.ParentDistinguishedName, newOU)); - EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, MachineInfo.ParentDistinguishedName, newOU); + EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", parentDistinguishedName, newOU)); + EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, parentDistinguishedName, newOU); MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit); - MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.sAMAccountName); + MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.SamAccountName); response.RequireReboot = true; } } @@ -507,12 +512,12 @@ namespace Disco.BI.DeviceBI { EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account"); ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); - EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); + EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.SamAccountName, AssignedUserInfo.Domain, AssignedUserInfo.SecurityIdentifier); response.AllowBootstrapperUninstall = true; - response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; + response.DeviceAssignedUserUsername = AssignedUserInfo.SamAccountName; response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; - response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; + response.DeviceAssignedUserSID = AssignedUserInfo.SecurityIdentifier; } } else @@ -523,7 +528,7 @@ namespace Disco.BI.DeviceBI { EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning a Wireless Certificate"); - var allocationResult = RepoDevice.AllocateCertificate(dbContext); + var allocationResult = RepoDevice.AllocateCertificate(Database); var deviceCertificate = allocationResult.Item1; if (deviceCertificate != null) { diff --git a/Disco.BI/BI/DeviceBI/Importing/Import.cs b/Disco.BI/BI/DeviceBI/Importing/Import.cs index a1f4b77c..28bb1994 100644 --- a/Disco.BI/BI/DeviceBI/Importing/Import.cs +++ b/Disco.BI/BI/DeviceBI/Importing/Import.cs @@ -2,6 +2,7 @@ using Disco.Data.Repository; using Disco.Models.BI.Device; using Disco.Models.Repository; +using Disco.Services.Users; using System; using System.Collections.Generic; using System.IO; @@ -24,13 +25,13 @@ namespace Disco.BI.DeviceBI.Importing return (ImportDeviceSession)HttpRuntime.Cache.Get(parseKey); } - internal static bool ImportRecord(this ImportDevice device, DiscoDataContext dbContext, PopulateRecordReferences references) + internal static bool ImportRecord(this ImportDevice device, DiscoDataContext Database, PopulateRecordReferences references) { // Skips If Errors if (device.Errors == null || device.Errors.Count == 0) { // Re-Populate & Skip If Errors - device.PopulateRecord(dbContext, references); + device.PopulateRecord(Database, references); if (device.Errors == null || device.Errors.Count == 0) { Device discoDevice = device.Device; @@ -44,7 +45,7 @@ namespace Disco.BI.DeviceBI.Importing CreatedDate = DateTime.Now, AllowUnauthenticatedEnrol = true, }; - dbContext.Devices.Add(discoDevice); + Database.Devices.Add(discoDevice); } if (discoDevice.DeviceModelId != device.DeviceModelId) @@ -60,10 +61,10 @@ namespace Disco.BI.DeviceBI.Importing if (discoDevice.AssignedUserId != device.AssignedUserId) { - discoDevice.AssignDevice(dbContext, device.AssignedUser); + discoDevice.AssignDevice(Database, device.AssignedUser); } - dbContext.SaveChanges(); + Database.SaveChanges(); return true; } @@ -71,16 +72,16 @@ namespace Disco.BI.DeviceBI.Importing return false; } - internal static PopulateRecordReferences GetPopulateRecordReferences(DiscoDataContext dbContext) + internal static PopulateRecordReferences GetPopulateRecordReferences(DiscoDataContext Database) { return new PopulateRecordReferences( - dbContext.DeviceModels.ToDictionary(dm => dm.Id), - dbContext.DeviceProfiles.ToDictionary(dp => dp.Id), - dbContext.DeviceBatches.ToDictionary(db => db.Id) + Database.DeviceModels.ToDictionary(dm => dm.Id), + Database.DeviceProfiles.ToDictionary(dp => dp.Id), + Database.DeviceBatches.ToDictionary(db => db.Id) ); } - internal static void PopulateRecord(this ImportDevice device, DiscoDataContext dbContext, PopulateRecordReferences references) + internal static void PopulateRecord(this ImportDevice device, DiscoDataContext Database, PopulateRecordReferences references) { var deviceModels = references.Item1; @@ -90,7 +91,7 @@ namespace Disco.BI.DeviceBI.Importing // SERIAL NUMBER - Existing Device if (!device.Errors.ContainsKey("SerialNumber")) { - device.Device = dbContext.Devices.Find(device.SerialNumber); + device.Device = Database.Devices.Find(device.SerialNumber); if (device.Device != null && device.Device.DecommissionedDate.HasValue) device.Errors.Add("SerialNumber", "The device is decommissioned"); } @@ -135,7 +136,7 @@ namespace Disco.BI.DeviceBI.Importing { try { - device.AssignedUser = UserBI.UserCache.GetUser(device.AssignedUserId, dbContext, true); + device.AssignedUser = UserService.GetUser(device.AssignedUserId, Database, true); } catch (ArgumentException) { diff --git a/Disco.BI/BI/DeviceBI/Importing/ImportParseTask.cs b/Disco.BI/BI/DeviceBI/Importing/ImportParseTask.cs index 2d3de6aa..ff8a0af4 100644 --- a/Disco.BI/BI/DeviceBI/Importing/ImportParseTask.cs +++ b/Disco.BI/BI/DeviceBI/Importing/ImportParseTask.cs @@ -45,14 +45,14 @@ namespace Disco.BI.DeviceBI.Importing this.Status.UpdateStatus(20, "Parsing CSV File", string.Format("Linking {0} Records", records.Count)); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - var populateReferences = Import.GetPopulateRecordReferences(dbContext); + var populateReferences = Import.GetPopulateRecordReferences(database); DateTime lastUpdate = DateTime.Now; foreach (var record in records) { - record.PopulateRecord(dbContext, populateReferences); + record.PopulateRecord(database, populateReferences); if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1) { diff --git a/Disco.BI/BI/DeviceBI/Importing/ImportProcessTask.cs b/Disco.BI/BI/DeviceBI/Importing/ImportProcessTask.cs index 2dc3ca9e..c0d416e5 100644 --- a/Disco.BI/BI/DeviceBI/Importing/ImportProcessTask.cs +++ b/Disco.BI/BI/DeviceBI/Importing/ImportProcessTask.cs @@ -35,14 +35,14 @@ namespace Disco.BI.DeviceBI.Importing this.Status.UpdateStatus(0, "Processing Device Import", "Importing Devices"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - var populateReferences = Import.GetPopulateRecordReferences(dbContext); + var populateReferences = Import.GetPopulateRecordReferences(database); DateTime lastUpdate = DateTime.Now; foreach (var record in records) { - if (record.ImportRecord(dbContext, populateReferences)) + if (record.ImportRecord(database, populateReferences)) recordsImported++; if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 1) diff --git a/Disco.BI/BI/DeviceBI/Migration/LogMacAddressImporting.cs b/Disco.BI/BI/DeviceBI/Migration/LogMacAddressImporting.cs index 4d7779aa..3f63ef53 100644 --- a/Disco.BI/BI/DeviceBI/Migration/LogMacAddressImporting.cs +++ b/Disco.BI/BI/DeviceBI/Migration/LogMacAddressImporting.cs @@ -19,26 +19,26 @@ namespace Disco.BI.DeviceBI.Migration public override bool CancelInitiallySupported { get { return false; } } #region Required Helpers - private static string RequiredFilePath(DiscoDataContext dbContext) + private static string RequiredFilePath(DiscoDataContext Database) { - if (dbContext.DiscoConfiguration.DataStoreLocation != null) - return System.IO.Path.Combine(dbContext.DiscoConfiguration.DataStoreLocation, "_LogMacAddressImportingRequired.txt"); + if (Database.DiscoConfiguration.DataStoreLocation != null) + return System.IO.Path.Combine(Database.DiscoConfiguration.DataStoreLocation, "_LogMacAddressImportingRequired.txt"); else return null; } - public static bool IsRequired(DiscoDataContext dbContext) + public static bool IsRequired(DiscoDataContext Database) { - var requiredFilePath = RequiredFilePath(dbContext); + var requiredFilePath = RequiredFilePath(Database); if (requiredFilePath == null) return false; else return System.IO.File.Exists(requiredFilePath); } - public static void SetRequired(DiscoDataContext dbContext) + public static void SetRequired(DiscoDataContext Database) { - var requiredFilePath = RequiredFilePath(dbContext); + var requiredFilePath = RequiredFilePath(Database); if (requiredFilePath != null) { @@ -49,9 +49,9 @@ namespace Disco.BI.DeviceBI.Migration } #endregion - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { - if (IsRequired(dbContext)) + if (IsRequired(Database)) { // Schedule in 15mins var trigger = TriggerBuilder.Create() @@ -73,7 +73,7 @@ namespace Disco.BI.DeviceBI.Migration protected override void ExecuteTask() { - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { Status.UpdateStatus(0, "Importing MAC Addresses", "Querying Logs for Details"); // Load Logs @@ -82,7 +82,7 @@ namespace Disco.BI.DeviceBI.Migration Module = DeviceBI.EnrolmentLog.Current.ModuleId, EventTypes = new List() { (int)DeviceBI.EnrolmentLog.EventTypeIds.SessionDeviceInfo } }; - var results = logRetriever.Query(dbContext); + var results = logRetriever.Query(database); Status.UpdateStatus(50, string.Format("Passing {0} logs", results.Count)); @@ -93,7 +93,7 @@ namespace Disco.BI.DeviceBI.Migration Status.UpdateStatus(75, string.Format("Importing {0} details", addresses.Count)); - var devices = dbContext.Devices.Include("DeviceDetails").ToList(); + var devices = database.Devices.Include("DeviceDetails").ToList(); Tuple addressResult; foreach (var device in devices) @@ -109,10 +109,10 @@ namespace Disco.BI.DeviceBI.Migration Status.UpdateStatus(90, "Saving to Database"); - dbContext.SaveChanges(); + database.SaveChanges(); // Finished - Remove Placeholder File - var requiredFilePath = RequiredFilePath(dbContext); + var requiredFilePath = RequiredFilePath(database); if (System.IO.File.Exists(requiredFilePath)) System.IO.File.Delete(requiredFilePath); } diff --git a/Disco.BI/BI/DeviceBI/Searching.cs b/Disco.BI/BI/DeviceBI/Searching.cs index 2440152f..5b6ea0e5 100644 --- a/Disco.BI/BI/DeviceBI/Searching.cs +++ b/Disco.BI/BI/DeviceBI/Searching.cs @@ -29,7 +29,7 @@ namespace Disco.BI.DeviceBI }).ToList(); } - public static List Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool SearchDetails = false) + public static List Search(DiscoDataContext Database, string Term, int? LimitCount = null, bool SearchDetails = false) { IQueryable query; @@ -37,7 +37,7 @@ namespace Disco.BI.DeviceBI if (SearchDetails) { - query = dbContext.Devices.Where(d => + query = Database.Devices.Where(d => d.AssetNumber.Contains(Term) || d.ComputerName.Contains(Term) || d.SerialNumber.Contains(Term) || @@ -48,7 +48,7 @@ namespace Disco.BI.DeviceBI } else { - query = dbContext.Devices.Where(d => + query = Database.Devices.Where(d => d.AssetNumber.Contains(Term) || d.ComputerName.Contains(Term) || d.SerialNumber.Contains(Term) || @@ -59,17 +59,17 @@ namespace Disco.BI.DeviceBI return Search_SelectDeviceSearchResultItem(query, LimitCount); } - public static List SearchDeviceModel(DiscoDataContext dbContext, int DeviceModelId, int? LimitCount = null) + public static List SearchDeviceModel(DiscoDataContext Database, int DeviceModelId, int? LimitCount = null) { - return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount); + return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount); } - public static List SearchDeviceProfile(DiscoDataContext dbContext, int DeviceProfileId, int? LimitCount = null) + public static List SearchDeviceProfile(DiscoDataContext Database, int DeviceProfileId, int? LimitCount = null) { - return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount); + return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount); } - public static List SearchDeviceBatch(DiscoDataContext dbContext, int DeviceBatchId, int? LimitCount = null) + public static List SearchDeviceBatch(DiscoDataContext Database, int DeviceBatchId, int? LimitCount = null) { - return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount); + return Search_SelectDeviceSearchResultItem(Database.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount); } } diff --git a/Disco.BI/BI/DocumentTemplateBI/DocumentTemplateQRCodeLocationCache.cs b/Disco.BI/BI/DocumentTemplateBI/DocumentTemplateQRCodeLocationCache.cs index f128f700..2b66c007 100644 --- a/Disco.BI/BI/DocumentTemplateBI/DocumentTemplateQRCodeLocationCache.cs +++ b/Disco.BI/BI/DocumentTemplateBI/DocumentTemplateQRCodeLocationCache.cs @@ -16,7 +16,7 @@ namespace Disco.BI.DocumentTemplateBI { private static ConcurrentDictionary> _Cache = new ConcurrentDictionary>(); - public static List GetLocations(DocumentTemplate dt, DiscoDataContext dbContext) + public static List GetLocations(DocumentTemplate dt, DiscoDataContext Database) { // Check Cache List locations; @@ -25,7 +25,7 @@ namespace Disco.BI.DocumentTemplateBI return locations; } // Generate Cache - return GenerateLocations(dt, dbContext); + return GenerateLocations(dt, Database); } public static bool InvalidateLocations(DocumentTemplate dt) @@ -47,9 +47,9 @@ namespace Disco.BI.DocumentTemplateBI return _Cache.TryAdd(DocumentTemplateId, Locations); } - internal static List GenerateLocations(DocumentTemplate dt, DiscoDataContext dbContext) + internal static List GenerateLocations(DocumentTemplate dt, DiscoDataContext Database) { - string templateFilename = dt.RepositoryFilename(dbContext); + string templateFilename = dt.RepositoryFilename(Database); PdfReader pdfReader = new PdfReader(templateFilename); List locations = new List(); diff --git a/Disco.BI/BI/DocumentTemplateBI/DocumentUniqueIdentifier.cs b/Disco.BI/BI/DocumentTemplateBI/DocumentUniqueIdentifier.cs index 4b4efe17..6ade8f62 100644 --- a/Disco.BI/BI/DocumentTemplateBI/DocumentUniqueIdentifier.cs +++ b/Disco.BI/BI/DocumentTemplateBI/DocumentUniqueIdentifier.cs @@ -115,7 +115,7 @@ namespace Disco.BI.DocumentTemplateBI } throw new System.ArgumentException(string.Format("Invalid Document Unique Identifier Version ({0})", s[1]), "UniqueIdentifier"); } - public bool LoadComponents(DiscoDataContext Context) + public bool LoadComponents(DiscoDataContext Database) { bool LoadComponents; if (!this._loadedComponentsOk.HasValue) @@ -142,7 +142,7 @@ namespace Disco.BI.DocumentTemplateBI } else { - this._documentTemplate = Context.DocumentTemplates.Find(this.TemplateTypeId); + this._documentTemplate = Database.DocumentTemplates.Find(this.TemplateTypeId); if (this._documentTemplate != null) { scopeType = this._documentTemplate.Scope; @@ -158,7 +158,7 @@ namespace Disco.BI.DocumentTemplateBI switch (scopeType) { case DocumentTemplate.DocumentTemplateScopes.Device: - Device d = Context.Devices.Find(this.DataId); + Device d = Database.Devices.Find(this.DataId); if (d != null) { this._data = d; @@ -169,7 +169,7 @@ namespace Disco.BI.DocumentTemplateBI } break; case DocumentTemplate.DocumentTemplateScopes.Job: - Job i = Context.Jobs.Find(int.Parse(this.DataId)); + Job i = Database.Jobs.Find(int.Parse(this.DataId)); if (i != null) { this._data = i; @@ -180,7 +180,7 @@ namespace Disco.BI.DocumentTemplateBI } break; case DocumentTemplate.DocumentTemplateScopes.User: - User u = Context.Users.Find(this.DataId); + User u = Database.Users.Find(this.DataId); if (u != null) { this._data = u; diff --git a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentDropBoxMonitor.cs b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentDropBoxMonitor.cs index 5e02162a..1565643b 100644 --- a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentDropBoxMonitor.cs +++ b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentDropBoxMonitor.cs @@ -16,15 +16,15 @@ namespace Disco.BI.DocumentTemplateBI.Importer public const string WatcherFilter = "*.pdf"; public string DropBoxLocation { get; private set; } - - public DocumentDropBoxMonitor(DiscoDataContext Context, ISchedulerFactory SchedulerFactory, Cache HttpCache) + + public DocumentDropBoxMonitor(DiscoDataContext Database, ISchedulerFactory SchedulerFactory, Cache HttpCache) { - if (Context == null) + if (Database == null) throw new System.ArgumentNullException("Context"); this._httpCache = HttpCache; - var location = DataStore.CreateLocation(Context, "DocumentDropBox"); + var location = DataStore.CreateLocation(Database, "DocumentDropBox"); this.DropBoxLocation = location.EndsWith(@"\") ? location : string.Concat(location, @"\"); this._scheduler = SchedulerFactory.GetScheduler(); diff --git a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterCleanCacheJob.cs b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterCleanCacheJob.cs index 97795704..c9674fc0 100644 --- a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterCleanCacheJob.cs +++ b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterCleanCacheJob.cs @@ -13,7 +13,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer public override bool SingleInstanceTask { get { return true; } } public override bool CancelInitiallySupported { get { return false; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Trigger Daily @ 12:30am TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 30)); @@ -24,9 +24,9 @@ namespace Disco.BI.DocumentTemplateBI.Importer protected override void ExecuteTask() { string dataStoreLocation; - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - dataStoreLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); + dataStoreLocation = DataStore.CreateLocation(database, "Cache\\DocumentDropBox_SessionPages"); } int deleteCount = 0; diff --git a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterJob.cs b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterJob.cs index 85e79fb7..6f7f91b4 100644 --- a/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterJob.cs +++ b/Disco.BI/BI/DocumentTemplateBI/Importer/DocumentImporterJob.cs @@ -40,12 +40,12 @@ namespace Disco.BI.DocumentTemplateBI.Importer try { - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { if (retryCount < 18) { context.JobDetail.JobDataMap["RetryCount"] = (++retryCount); - bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, sessionId, httpCache); + bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, database, sessionId, httpCache); if (processResult) { @@ -60,7 +60,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer { try { - string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); + string folderError = DataStore.CreateLocation(database, "DocumentDropBox_Errors"); string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); int filenameErrorCount = 0; while (File.Exists(filenameError)) @@ -85,7 +85,7 @@ namespace Disco.BI.DocumentTemplateBI.Importer { try { - string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); + string folderError = DataStore.CreateLocation(database, "DocumentDropBox_Errors"); string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); int filenameErrorCount = 0; while (File.Exists(filenameError)) diff --git a/Disco.BI/BI/Expressions/Expression.cs b/Disco.BI/BI/Expressions/Expression.cs index 10b57c98..dbfb1916 100644 --- a/Disco.BI/BI/Expressions/Expression.cs +++ b/Disco.BI/BI/Expressions/Expression.cs @@ -167,14 +167,14 @@ namespace Disco.BI.Expressions return e; } - public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState DocumentState) + public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext Database, User User, System.DateTime TimeStamp, DocumentState DocumentState) { return new Hashtable { { "DataContext", - DataContext + Database }, { diff --git a/Disco.BI/BI/Expressions/ExpressionCachePreloadTask.cs b/Disco.BI/BI/Expressions/ExpressionCachePreloadTask.cs index 9bb5ab55..783ad1c1 100644 --- a/Disco.BI/BI/Expressions/ExpressionCachePreloadTask.cs +++ b/Disco.BI/BI/Expressions/ExpressionCachePreloadTask.cs @@ -17,7 +17,7 @@ namespace Disco.BI.Expressions public override bool SingleInstanceTask { get { return true; } } public override bool CancelInitiallySupported { get { return false; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Run in Background 1 Second after Scheduled (on App Startup) TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(new DateTimeOffset(DateTime.Now).AddSeconds(5)); @@ -28,9 +28,9 @@ namespace Disco.BI.Expressions protected override void ExecuteTask() { // Cache Document Template Filter Expressions - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - foreach (var documentTemplate in dbContext.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty)) + foreach (var documentTemplate in database.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty)) { if (!string.IsNullOrWhiteSpace(documentTemplate.FilterExpression)) documentTemplate.FilterExpressionFromCache(); diff --git a/Disco.BI/BI/Expressions/Extensions/ImageExt.cs b/Disco.BI/BI/Expressions/Extensions/ImageExt.cs index 47c2ece9..45e75bab 100644 --- a/Disco.BI/BI/Expressions/Extensions/ImageExt.cs +++ b/Disco.BI/BI/Expressions/Extensions/ImageExt.cs @@ -26,39 +26,39 @@ namespace Disco.BI.Expressions.Extensions string AbsoluteFilePath = System.IO.Path.Combine(DataStoreLocation, RelativeFilePath); return new FileImageExpressionResult(AbsoluteFilePath); } - public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext dbContext) + public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext Database) { var attachment = Job.JobAttachments.FirstOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); if (attachment != null) { - var filename = attachment.RepositoryFilename(dbContext); + var filename = attachment.RepositoryFilename(Database); return new FileImageExpressionResult(filename); } else return null; } - public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext dbContext) + public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext Database) { var attachment = Job.JobAttachments.LastOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); if (attachment != null) { - var filename = attachment.RepositoryFilename(dbContext); + var filename = attachment.RepositoryFilename(Database); return new FileImageExpressionResult(filename); } else return null; } - public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext dbContext) + public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext Database) { if (JobAttachment == null) throw new ArgumentNullException("JobAttachment"); if (!JobAttachment.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) throw new ArgumentException("Invalid Image MimeType for Attachment"); - var filename = JobAttachment.RepositoryFilename(dbContext); + var filename = JobAttachment.RepositoryFilename(Database); return new FileImageExpressionResult(filename); } - public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext dbContext) + public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext Database) { if (Job == null) throw new ArgumentNullException("Job"); @@ -69,14 +69,14 @@ namespace Disco.BI.Expressions.Extensions if (attachments.Count > 0) { - var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); + var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(Database)).ToList(); return new FileMontageImageExpressionResult(attachmentFilepaths); } else return null; } - public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext dbContext) + public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext Database) { if (JobAttachments == null) throw new ArgumentNullException("JobAttachments"); @@ -85,7 +85,7 @@ namespace Disco.BI.Expressions.Extensions if (attachments.Count > 0) { - var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); + var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(Database)).ToList(); return new FileMontageImageExpressionResult(attachmentFilepaths); } diff --git a/Disco.BI/BI/Extensions/AttachmentActionExtensions.cs b/Disco.BI/BI/Extensions/AttachmentActionExtensions.cs index 7a24383f..2b129a7a 100644 --- a/Disco.BI/BI/Extensions/AttachmentActionExtensions.cs +++ b/Disco.BI/BI/Extensions/AttachmentActionExtensions.cs @@ -4,6 +4,8 @@ using System.Linq; using System.Text; using Disco.Models.Repository; using Disco.Data.Repository; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { @@ -13,39 +15,60 @@ namespace Disco.BI.Extensions #region Delete public static bool CanDelete(this DeviceAttachment da) { - return true; // Placeholder - Currently Can Always Delete; + if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveAnyAttachments)) + return true; + + if (UserService.CurrentAuthorization.Has(Claims.Device.Actions.RemoveOwnAttachments) + && da.TechUserId == UserService.CurrentUserId) + return true; + + return false; } - public static void OnDelete(this DeviceAttachment da, DiscoDataContext dbContext) + public static void OnDelete(this DeviceAttachment da, DiscoDataContext Database) { if (!da.CanDelete()) throw new InvalidOperationException("Deletion of Attachment is Denied"); - da.RepositoryDelete(dbContext); - dbContext.DeviceAttachments.Remove(da); + da.RepositoryDelete(Database); + Database.DeviceAttachments.Remove(da); } public static bool CanDelete(this JobAttachment ja) { - return true; // Placeholder - Currently Can Always Delete; + if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveAnyAttachments)) + return true; + + if (UserService.CurrentAuthorization.Has(Claims.Job.Actions.RemoveOwnAttachments) + && ja.TechUserId == UserService.CurrentUserId) + return true; + + return false; } - public static void OnDelete(this JobAttachment ja, DiscoDataContext dbContext) + public static void OnDelete(this JobAttachment ja, DiscoDataContext Database) { if (!ja.CanDelete()) throw new InvalidOperationException("Deletion of Attachment is Denied"); - ja.RepositoryDelete(dbContext); - dbContext.JobAttachments.Remove(ja); + ja.RepositoryDelete(Database); + Database.JobAttachments.Remove(ja); } public static bool CanDelete(this UserAttachment ua) { - return true; // Placeholder - Currently Can Always Delete; + if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveAnyAttachments)) + return true; + + if (UserService.CurrentAuthorization.Has(Claims.User.Actions.RemoveOwnAttachments) + && ua.TechUserId == UserService.CurrentUserId) + return true; + + return false; } - public static void OnDelete(this UserAttachment ua, DiscoDataContext dbContext) + public static void OnDelete(this UserAttachment ua, DiscoDataContext Database) { if (!ua.CanDelete()) throw new InvalidOperationException("Deletion of Attachment is Denied"); - ua.RepositoryDelete(dbContext); - dbContext.UserAttachments.Remove(ua); + ua.RepositoryDelete(Database); + Database.UserAttachments.Remove(ua); } #endregion diff --git a/Disco.BI/BI/Extensions/AttachmentExtensions.cs b/Disco.BI/BI/Extensions/AttachmentExtensions.cs index f7a5a7c8..3e336c2c 100644 --- a/Disco.BI/BI/Extensions/AttachmentExtensions.cs +++ b/Disco.BI/BI/Extensions/AttachmentExtensions.cs @@ -6,16 +6,17 @@ using Disco.Models.Repository; using Disco.Data.Repository; using System.IO; using Disco.BI.DocumentTemplateBI; +using Disco.Services.Users; namespace Disco.BI.Extensions { public static class AttachmentExtensions { - public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext dbContext, System.IO.Stream PdfContent, byte[] PdfThumbnail) + public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext Database, System.IO.Stream PdfContent, byte[] PdfThumbnail) { - UniqueIdentifier.LoadComponents(dbContext); + UniqueIdentifier.LoadComponents(Database); DocumentTemplate documentTemplate = UniqueIdentifier.DocumentTemplate; string filename; string comments; @@ -31,25 +32,25 @@ namespace Disco.BI.Extensions comments = string.Format("Generated: {0:s}", UniqueIdentifier.TimeStamp); } - User creatorUser = UserBI.UserCache.GetUser(UniqueIdentifier.CreatorId, dbContext); + User creatorUser = UserService.GetUser(UniqueIdentifier.CreatorId, Database); if (creatorUser == null) { // No Creator User (or Username invalid) - creatorUser = UserBI.UserCache.CurrentUser; + creatorUser = UserService.CurrentUser; } switch (UniqueIdentifier.DataScope) { case DocumentTemplate.DocumentTemplateScopes.Device: Device d = (Device)UniqueIdentifier.Data; - d.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); + d.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); return true; case DocumentTemplate.DocumentTemplateScopes.Job: Job j = (Job)UniqueIdentifier.Data; - j.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); + j.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); return true; case DocumentTemplate.DocumentTemplateScopes.User: User u = (User)UniqueIdentifier.Data; - u.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); + u.CreateAttachment(Database, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); return true; default: return false; @@ -57,47 +58,47 @@ namespace Disco.BI.Extensions } - public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext dbContext) + public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext Database) { - return Path.Combine(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id)); + return Path.Combine(DataStore.CreateLocation(Database, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id)); } - public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext dbContext) + public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext Database) { - return Path.Combine(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id)); + return Path.Combine(DataStore.CreateLocation(Database, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id)); } - public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext dbContext) + public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext Database) { - return Path.Combine(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id)); + return Path.Combine(DataStore.CreateLocation(Database, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id)); } private static string RepositoryThumbnailFilenameInternal(string DirectoryPath, string Filename) { return Path.Combine(DirectoryPath, Filename); } - public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext dbContext) + public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext Database) { - return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id)); + return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id)); } - public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext dbContext) + public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext Database) { - return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id)); + return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id)); } - public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext dbContext) + public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext Database) { - return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id)); + return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(Database, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id)); } - public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext dbContext) + public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext Database) { - RepositoryDelete(da.RepositoryFilename(dbContext), da.RepositoryThumbnailFilename(dbContext)); + RepositoryDelete(da.RepositoryFilename(Database), da.RepositoryThumbnailFilename(Database)); } - public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext dbContext) + public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext Database) { - RepositoryDelete(ja.RepositoryFilename(dbContext), ja.RepositoryThumbnailFilename(dbContext)); + RepositoryDelete(ja.RepositoryFilename(Database), ja.RepositoryThumbnailFilename(Database)); } - public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext dbContext) + public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext Database) { - RepositoryDelete(ua.RepositoryFilename(dbContext), ua.RepositoryThumbnailFilename(dbContext)); + RepositoryDelete(ua.RepositoryFilename(Database), ua.RepositoryThumbnailFilename(Database)); } private static void RepositoryDelete(params string[] filePaths) { @@ -108,39 +109,39 @@ namespace Disco.BI.Extensions } } - public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext dbContext, Stream FileContent) + public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext Database, Stream FileContent) { - string filePath = da.RepositoryFilename(dbContext); + string filePath = da.RepositoryFilename(Database); SaveAttachment(filePath, FileContent); return filePath; } - public static string SaveAttachment(this JobAttachment ja, DiscoDataContext dbContext, Stream FileContent) + public static string SaveAttachment(this JobAttachment ja, DiscoDataContext Database, Stream FileContent) { - string filePath = ja.RepositoryFilename(dbContext); + string filePath = ja.RepositoryFilename(Database); SaveAttachment(filePath, FileContent); return filePath; } - public static string SaveAttachment(this UserAttachment ua, DiscoDataContext dbContext, Stream FileContent) + public static string SaveAttachment(this UserAttachment ua, DiscoDataContext Database, Stream FileContent) { - string filePath = ua.RepositoryFilename(dbContext); + string filePath = ua.RepositoryFilename(Database); SaveAttachment(filePath, FileContent); return filePath; } - public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext dbContext, byte[] FileContent) + public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext Database, byte[] FileContent) { - string filePath = da.RepositoryThumbnailFilename(dbContext); + string filePath = da.RepositoryThumbnailFilename(Database); File.WriteAllBytes(filePath, FileContent); return filePath; } - public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext dbContext, byte[] FileContent) + public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext Database, byte[] FileContent) { - string filePath = ja.RepositoryThumbnailFilename(dbContext); + string filePath = ja.RepositoryThumbnailFilename(Database); File.WriteAllBytes(filePath, FileContent); return filePath; } - public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext dbContext, byte[] FileContent) + public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext Database, byte[] FileContent) { - string filePath = ua.RepositoryThumbnailFilename(dbContext); + string filePath = ua.RepositoryThumbnailFilename(Database); File.WriteAllBytes(filePath, FileContent); return filePath; } @@ -154,39 +155,39 @@ namespace Disco.BI.Extensions } } - public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext) + public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext Database) { - string filePath = da.RepositoryThumbnailFilename(dbContext); - AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(dbContext), da.MimeType, filePath); + string filePath = da.RepositoryThumbnailFilename(Database); + AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(Database), da.MimeType, filePath); return filePath; } - public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext) + public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext Database) { - string filePath = ja.RepositoryThumbnailFilename(dbContext); - AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(dbContext), ja.MimeType, filePath); + string filePath = ja.RepositoryThumbnailFilename(Database); + AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(Database), ja.MimeType, filePath); return filePath; } - public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext) + public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext Database) { - string filePath = ua.RepositoryThumbnailFilename(dbContext); - AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(dbContext), ua.MimeType, filePath); + string filePath = ua.RepositoryThumbnailFilename(Database); + AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(Database), ua.MimeType, filePath); return filePath; } - public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext, Stream SourceFile) + public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext Database, Stream SourceFile) { - string filePath = da.RepositoryThumbnailFilename(dbContext); + string filePath = da.RepositoryThumbnailFilename(Database); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, da.MimeType, filePath); return filePath; } - public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext, Stream SourceFile) + public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext Database, Stream SourceFile) { - string filePath = ja.RepositoryThumbnailFilename(dbContext); + string filePath = ja.RepositoryThumbnailFilename(Database); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ja.MimeType, filePath); return filePath; } - public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext, Stream SourceFile) + public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext Database, Stream SourceFile) { - string filePath = ua.RepositoryThumbnailFilename(dbContext); + string filePath = ua.RepositoryThumbnailFilename(Database); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ua.MimeType, filePath); return filePath; } diff --git a/Disco.BI/BI/Extensions/AuthorizationRoleExtensions.cs b/Disco.BI/BI/Extensions/AuthorizationRoleExtensions.cs new file mode 100644 index 00000000..2841ac34 --- /dev/null +++ b/Disco.BI/BI/Extensions/AuthorizationRoleExtensions.cs @@ -0,0 +1,28 @@ +using Disco.Data.Repository; +using Disco.Models.Authorization; +using Disco.Models.Repository; +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.BI.Extensions +{ + public static class AuthorizationRoleExtensions + { + + public static void Delete(this IRoleToken roleToken, DiscoDataContext Database) + { + var role = Database.AuthorizationRoles.Find(roleToken.Role.Id); + UserService.DeleteAuthorizationRole(Database, roleToken.Role); + } + + public static void Delete(this AuthorizationRole role, DiscoDataContext Database) + { + UserService.DeleteAuthorizationRole(Database, role); + } + + } +} diff --git a/Disco.BI/BI/Extensions/ClientServicesExtensions.cs b/Disco.BI/BI/Extensions/ClientServicesExtensions.cs index d13012d7..d7b6321a 100644 --- a/Disco.BI/BI/Extensions/ClientServicesExtensions.cs +++ b/Disco.BI/BI/Extensions/ClientServicesExtensions.cs @@ -6,6 +6,7 @@ using Disco.Models.ClientServices; using System.Web; using Disco.Data.Repository; using Disco.Models.Repository; +using Disco.Services.Users; namespace Disco.BI.Extensions { @@ -20,10 +21,10 @@ namespace Disco.BI.Extensions if (HttpContext.Current.Request.IsAuthenticated) username = HttpContext.Current.User.Identity.Name; - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(dbContext, username, request); - dbContext.SaveChanges(); + EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(database, username, request); + database.SaveChanges(); return response; } } @@ -40,14 +41,14 @@ namespace Disco.BI.Extensions if (username == null) throw new InvalidOperationException("Unauthenticated Http Context"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - User user = UserBI.UserCache.GetUser(username, dbContext, true); + User user = UserService.GetUser(username, database, true); WhoAmIResponse response = new WhoAmIResponse() { Username = user.Id, DisplayName = user.DisplayName, - Type = user.Type + Type = "TODO!" }; return response; } @@ -58,10 +59,10 @@ namespace Disco.BI.Extensions if (HttpContext.Current == null) throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(dbContext, request, false); - dbContext.SaveChanges(); + MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(database, request, false); + database.SaveChanges(); return response; } } diff --git a/Disco.BI/BI/Extensions/DeviceActionExtensions.cs b/Disco.BI/BI/Extensions/DeviceActionExtensions.cs index a20bc5cf..4884d751 100644 --- a/Disco.BI/BI/Extensions/DeviceActionExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceActionExtensions.cs @@ -5,6 +5,8 @@ using System.Text; using Disco.Models.Repository; using Disco.Data.Repository; using Disco.BI.Interop.ActiveDirectory; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { @@ -17,36 +19,57 @@ namespace Disco.BI.Extensions public static bool CanCreateJob(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Create)) + return false; + return !d.IsDecommissioned(); } public static bool CanUpdateAssignment(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AssignUser)) + return false; + return !d.IsDecommissioned(); } public static bool CanUpdateDeviceProfile(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceProfile)) + return false; + return !d.IsDecommissioned(); } public static bool CanUpdateDeviceBatch(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Properties.DeviceBatch)) + return false; + return !d.IsDecommissioned(); } public static bool CanUpdateTrustEnrol(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol)) + return false; + return !d.IsDecommissioned() && !d.AllowUnauthenticatedEnrol; } public static bool CanUpdateUntrustEnrol(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.AllowUnauthenticatedEnrol)) + return false; + return !d.IsDecommissioned() && d.AllowUnauthenticatedEnrol; } #region Decommission public static bool CanDecommission(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Decommission)) + return false; + if (d.DecommissionedDate.HasValue) return false; // Already Decommissioned @@ -80,6 +103,9 @@ namespace Disco.BI.Extensions #region Recommission public static bool CanRecommission(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Recommission)) + return false; + return d.DecommissionedDate.HasValue; } public static void OnRecommission(this Device d) @@ -105,17 +131,20 @@ namespace Disco.BI.Extensions #region Delete public static bool CanDelete(this Device d) { + if (!UserService.CurrentAuthorization.Has(Claims.Device.Actions.Delete)) + return false; + return d.DecommissionedDate.HasValue; } - public static void OnDelete(this Device d, DiscoDataContext dbContext) + public static void OnDelete(this Device d, DiscoDataContext Database) { // Delete Jobs - foreach (Job j in dbContext.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber)) + foreach (Job j in Database.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber)) { if (j.UserId == null) { // No User associated, thus must Delete whole Job if (j.CanDelete()) - j.OnDelete(dbContext); + j.OnDelete(Database); else throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id)); } @@ -128,35 +157,35 @@ namespace Disco.BI.Extensions JobLog jobLog = new JobLog() { JobId = j.Id, - TechUserId = UserBI.UserCache.CurrentUser.Id, + TechUserId = UserService.CurrentUser.Id, Timestamp = DateTime.Now, Comments = string.Format("Device Deleted{0}{0}Serial Number: {1}{0}Computer Name: {2}{0}Model: {3}{0}Profile: {4}", Environment.NewLine, d.SerialNumber, d.ComputerName, d.DeviceModel, d.DeviceProfile) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); } } // Disable Wireless Certificates - foreach (var wc in dbContext.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber)) + foreach (var wc in Database.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber)) { wc.DeviceSerialNumber = null; wc.Enabled = false; } // Delete Device Details - foreach (var dd in dbContext.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber)) - dbContext.DeviceDetails.Remove(dd); + foreach (var dd in Database.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber)) + Database.DeviceDetails.Remove(dd); // Delete Device Attachments - foreach (var da in dbContext.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) + foreach (var da in Database.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) { - da.RepositoryDelete(dbContext); - dbContext.DeviceAttachments.Remove(da); + da.RepositoryDelete(Database); + Database.DeviceAttachments.Remove(da); } // Delete Device User Assignments - foreach (var dua in dbContext.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) - dbContext.DeviceUserAssignments.Remove(dua); + foreach (var dua in Database.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) + Database.DeviceUserAssignments.Remove(dua); - dbContext.Devices.Remove(d); + Database.Devices.Remove(d); } #endregion } diff --git a/Disco.BI/BI/Extensions/DeviceBatchExtensions.cs b/Disco.BI/BI/Extensions/DeviceBatchExtensions.cs index cfc04013..2fe39a4f 100644 --- a/Disco.BI/BI/Extensions/DeviceBatchExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceBatchExtensions.cs @@ -4,28 +4,33 @@ using System.Linq; using System.Text; using Disco.Models.Repository; using Disco.Data.Repository; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { public static class DeviceBatchExtensions { - public static bool CanDelete(this DeviceBatch db, DiscoDataContext dbContext) + public static bool CanDelete(this DeviceBatch db, DiscoDataContext Database) { + if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceBatch.Delete)) + return false; + // Can't Delete if Contains Devices - var deviceCount = dbContext.Devices.Count(d => d.DeviceBatchId == db.Id); + var deviceCount = Database.Devices.Count(d => d.DeviceBatchId == db.Id); if (deviceCount > 0) return false; return true; } - public static void Delete(this DeviceBatch db, DiscoDataContext dbContext) + public static void Delete(this DeviceBatch db, DiscoDataContext Database) { - if (!db.CanDelete(dbContext)) + if (!db.CanDelete(Database)) throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted"); // Delete Batch - dbContext.DeviceBatches.Remove(db); + Database.DeviceBatches.Remove(db); } } } diff --git a/Disco.BI/BI/Extensions/DeviceCertificateExtensions.cs b/Disco.BI/BI/Extensions/DeviceCertificateExtensions.cs index c4889e2a..3e806cd9 100644 --- a/Disco.BI/BI/Extensions/DeviceCertificateExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceCertificateExtensions.cs @@ -11,16 +11,10 @@ namespace Disco.BI.Extensions public static class DeviceCertificateExtensions { - public static Tuple> AllocateCertificate(this Device device, DiscoDataContext dbContext) + public static Tuple> AllocateCertificate(this Device device, DiscoDataContext Database) { if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId)) { - // REMOVED 2012-07-18 G# - Plugin is responsible for checking - //var deviceCertificates = dbContext.DeviceCertificates.Where(c => - // c.DeviceSerialNumber == device.SerialNumber && - // c.ProviderId == device.DeviceProfile.CertificateProviderId && - // c.Enabled == true).ToList(); - // Load Plugin PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature)); @@ -32,7 +26,7 @@ namespace Disco.BI.Extensions // return new Tuple>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames()); //else - return providerFeature.AllocateCertificate(dbContext, device); + return providerFeature.AllocateCertificate(Database, device); } } diff --git a/Disco.BI/BI/Extensions/DeviceExtensions.cs b/Disco.BI/BI/Extensions/DeviceExtensions.cs index d4947778..ae611ca7 100644 --- a/Disco.BI/BI/Extensions/DeviceExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceExtensions.cs @@ -8,13 +8,15 @@ using System.Collections.Generic; using System; using System.IO; using Disco.Models.Interop.ActiveDirectory; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { public static class DeviceExtensions { - public static string ComputerNameRender(this Device device, DiscoDataContext context) + public static string ComputerNameRender(this Device device, DiscoDataContext Database) { DeviceProfile deviceProfile = device.DeviceProfile; Expressions.Expression computerNameTemplateExpression = null; @@ -24,7 +26,7 @@ namespace Disco.BI.Extensions //return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.Configuration(context).ComputerNameTemplate, 0); return Expressions.Expression.TokenizeSingleDynamic(null, deviceProfile.ComputerNameTemplate, 0); }); - System.Collections.IDictionary evaluatorVariables = Expressions.Expression.StandardVariables(null, context, UserBI.UserCache.CurrentUser, System.DateTime.Now, null); + System.Collections.IDictionary evaluatorVariables = Expressions.Expression.StandardVariables(null, Database, UserService.CurrentUser, System.DateTime.Now, null); string rendered; try { @@ -40,12 +42,12 @@ namespace Disco.BI.Extensions } return rendered.ToString(); } - public static System.Collections.Generic.List AvailableDocumentTemplates(this Device d, DiscoDataContext Context, User User, System.DateTime TimeStamp) + public static System.Collections.Generic.List AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, System.DateTime TimeStamp) { - List ats = Context.DocumentTemplates + List ats = Database.DocumentTemplates .Where(at => at.Scope == Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device).ToList(); - return ats.Where(at => at.FilterExpressionMatches(d, Context, User, TimeStamp, DocumentState.DefaultState())).ToList(); + return ats.Where(at => at.FilterExpressionMatches(d, Database, User, TimeStamp, DocumentState.DefaultState())).ToList(); } public static bool UpdateLastNetworkLogonDate(this Device Device) @@ -53,7 +55,7 @@ namespace Disco.BI.Extensions return ActiveDirectoryUpdateLastNetworkLogonDateJob.UpdateLastNetworkLogonDate(Device); } - public static DeviceAttachment CreateAttachment(this Device Device, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) + public static DeviceAttachment CreateAttachment(this Device Device, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) { if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) MimeType = Interop.MimeTypes.ResolveMimeType(Filename); @@ -71,20 +73,20 @@ namespace Disco.BI.Extensions if (DocumentTemplate != null) da.DocumentTemplateId = DocumentTemplate.Id; - dbContext.DeviceAttachments.Add(da); - dbContext.SaveChanges(); + Database.DeviceAttachments.Add(da); + Database.SaveChanges(); - da.SaveAttachment(dbContext, Content); + da.SaveAttachment(Database, Content); Content.Position = 0; if (PdfThumbnail == null) - da.GenerateThumbnail(dbContext, Content); + da.GenerateThumbnail(Database, Content); else - da.SaveThumbnailAttachment(dbContext, PdfThumbnail); + da.SaveThumbnailAttachment(Database, PdfThumbnail); return da; } - public static Device AddOffline(this Device d, DiscoDataContext dbContext) + public static Device AddOffline(this Device d, DiscoDataContext Database) { // Just Include: // - Serial Number @@ -93,17 +95,31 @@ namespace Disco.BI.Extensions // - Assigned User Id // - Batch + // Enforce Authorization + var auth = UserService.CurrentAuthorization; + if (!auth.Has(Claims.Device.Properties.AssetNumber)) + d.AssetNumber = null; + if (!auth.Has(Claims.Device.Properties.Location)) + d.Location = null; + if (!auth.Has(Claims.Device.Properties.DeviceBatch)) + d.DeviceBatchId = null; + if (!auth.Has(Claims.Device.Properties.DeviceProfile)) + d.DeviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId; + if (!auth.Has(Claims.Device.Actions.AssignUser)) + d.AssignedUserId = null; + + // Batch DeviceBatch db = default(DeviceBatch); if (d.DeviceBatchId.HasValue) - db = dbContext.DeviceBatches.Find(d.DeviceBatchId.Value); + db = Database.DeviceBatches.Find(d.DeviceBatchId.Value); // Default Device Model DeviceModel dm = default(DeviceModel); if (db != null && db.DefaultDeviceModelId.HasValue) - dm = dbContext.DeviceModels.Find(db.DefaultDeviceModelId); // From Batch + dm = Database.DeviceModels.Find(db.DefaultDeviceModelId); // From Batch else - dm = dbContext.DeviceModels.Find(1); // Default + dm = Database.DeviceModels.Find(1); // Default Device d2 = new Device() { @@ -112,7 +128,7 @@ namespace Disco.BI.Extensions Location = d.Location, CreatedDate = DateTime.Now, DeviceProfileId = d.DeviceProfileId, - DeviceProfile = dbContext.DeviceProfiles.Find(d.DeviceProfileId), + DeviceProfile = Database.DeviceProfiles.Find(d.DeviceProfileId), AllowUnauthenticatedEnrol = true, DeviceModelId = dm.Id, DeviceModel = dm, @@ -120,22 +136,22 @@ namespace Disco.BI.Extensions DeviceBatch = db }; - dbContext.Devices.Add(d2); + Database.Devices.Add(d2); if (!string.IsNullOrEmpty(d.AssignedUserId)) { - User u = UserBI.UserCache.GetUser(d.AssignedUserId, dbContext, true); - d2.AssignDevice(dbContext, u); + User u = UserService.GetUser(d.AssignedUserId, Database, true); + d2.AssignDevice(Database, u); } return d2; } - public static DeviceUserAssignment AssignDevice(this Device d, DiscoDataContext dbContext, User u) + public static DeviceUserAssignment AssignDevice(this Device d, DiscoDataContext Database, User u) { DeviceUserAssignment newDua = default(DeviceUserAssignment); // Mark existing assignments as Unassigned - foreach (var dua in dbContext.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == d.SerialNumber && !m.UnassignedDate.HasValue)) + foreach (var dua in Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == d.SerialNumber && !m.UnassignedDate.HasValue)) dua.UnassignedDate = DateTime.Now; if (u != null) @@ -147,7 +163,7 @@ namespace Disco.BI.Extensions AssignedUserId = u.Id, AssignedDate = DateTime.Now }; - dbContext.DeviceUserAssignments.Add(newDua); + Database.DeviceUserAssignments.Add(newDua); d.AssignedUserId = u.Id; d.AssignedUser = u; diff --git a/Disco.BI/BI/Extensions/DeviceModelExtensions.cs b/Disco.BI/BI/Extensions/DeviceModelExtensions.cs index a885c70d..a1b46923 100644 --- a/Disco.BI/BI/Extensions/DeviceModelExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceModelExtensions.cs @@ -6,6 +6,8 @@ using Disco.Models.Repository; using System.IO; using System.Drawing; using Disco.Data.Repository; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { @@ -73,22 +75,24 @@ namespace Disco.BI.Extensions } #region Actions - // Added 2012-11-26 G# - Need ability to delete Device Models - public static bool CanDelete(this DeviceModel dm, DiscoDataContext dbContext) + public static bool CanDelete(this DeviceModel dm, DiscoDataContext Database) { + if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceModel.Delete)) + return false; + // Can't Delete Default Model (Id: 1) if (dm.Id == 1) return false; // Can't Delete if Contains Devices - if (dbContext.Devices.Count(d => d.DeviceModelId == dm.Id) > 0) + if (Database.Devices.Count(d => d.DeviceModelId == dm.Id) > 0) return false; return true; } - public static void Delete(this DeviceModel dm, DiscoDataContext dbContext) + public static void Delete(this DeviceModel dm, DiscoDataContext Database) { - if (!dm.CanDelete(dbContext)) + if (!dm.CanDelete(Database)) throw new InvalidOperationException("The state of this Device Model doesn't allow it to be deleted"); // Delete Image @@ -97,13 +101,13 @@ namespace Disco.BI.Extensions File.Delete(deviceModelImagePath); // Delete any Device Model Components - foreach (var deviceModelComponent in dbContext.DeviceComponents.Where(dc => dc.DeviceModelId == dm.Id).ToList()) + foreach (var deviceModelComponent in Database.DeviceComponents.Where(dc => dc.DeviceModelId == dm.Id).ToList()) { - dbContext.DeviceComponents.Remove(deviceModelComponent); + Database.DeviceComponents.Remove(deviceModelComponent); } // Delete Model - dbContext.DeviceModels.Remove(dm); + Database.DeviceModels.Remove(dm); } // End Added 2012-11-26 G# #endregion diff --git a/Disco.BI/BI/Extensions/DeviceProfileExtensions.cs b/Disco.BI/BI/Extensions/DeviceProfileExtensions.cs index 20537ffe..c339317c 100644 --- a/Disco.BI/BI/Extensions/DeviceProfileExtensions.cs +++ b/Disco.BI/BI/Extensions/DeviceProfileExtensions.cs @@ -6,6 +6,8 @@ using Disco.Models.Repository; using Disco.Data.Repository; using Disco.Data.Configuration.Modules; using Disco.Models.BI.Config; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { @@ -18,11 +20,11 @@ namespace Disco.BI.Extensions Expressions.ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString()); } - public static OrganisationAddress DefaultOrganisationAddressDetails(this DeviceProfile deviceProfile, DiscoDataContext dbContext) + public static OrganisationAddress DefaultOrganisationAddressDetails(this DeviceProfile deviceProfile, DiscoDataContext Database) { if (deviceProfile.DefaultOrganisationAddress.HasValue) { - return dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(deviceProfile.DefaultOrganisationAddress.Value); + return Database.DiscoConfiguration.OrganisationAddresses.GetAddress(deviceProfile.DefaultOrganisationAddress.Value); } else { @@ -30,38 +32,35 @@ namespace Disco.BI.Extensions } } - public static bool CanDelete(this DeviceProfile dp, DiscoDataContext dbContext) + public static bool CanDelete(this DeviceProfile dp, DiscoDataContext Database) { + if (!UserService.CurrentAuthorization.Has(Claims.Config.DeviceProfile.Delete)) + return false; + // Can't Delete Default Profile (Id: 1) if (dp.Id == 1) return false; // Can't Delete if Contains Devices - if (dbContext.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0) + if (Database.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0) return false; return true; } - public static void Delete(this DeviceProfile dp, DiscoDataContext dbContext) + public static void Delete(this DeviceProfile dp, DiscoDataContext Database) { - if (!dp.CanDelete(dbContext)) + if (!dp.CanDelete(Database)) throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted"); // Update Defaults - if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id) - dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1; - if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id) - dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1; + if (Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id) + Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1; + if (Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id) + Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1; // Delete Profile - dbContext.DeviceProfiles.Remove(dp); + Database.DeviceProfiles.Remove(dp); } - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //public static DeviceProfileConfiguration Configuration(this DeviceProfile dp, DiscoDataContext dbContext) - //{ - // return dbContext.DiscoConfiguration.DeviceProfiles.DeviceProfile(dp); - //} - } } diff --git a/Disco.BI/BI/Extensions/DocumentTemplateExtensions.cs b/Disco.BI/BI/Extensions/DocumentTemplateExtensions.cs index 2318dc25..1fafd3e0 100644 --- a/Disco.BI/BI/Extensions/DocumentTemplateExtensions.cs +++ b/Disco.BI/BI/Extensions/DocumentTemplateExtensions.cs @@ -19,13 +19,13 @@ namespace Disco.BI.Extensions { private const string DocumentTemplateExpressionCacheTemplate = "DocumentTemplate_{0}"; - public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext dbContext) + public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext Database) { - return System.IO.Path.Combine(DataStore.CreateLocation(dbContext, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id)); + return System.IO.Path.Combine(DataStore.CreateLocation(Database, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id)); } - public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext dbContext, Stream TemplateFile) + public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext Database, Stream TemplateFile) { - string filePath = dt.RepositoryFilename(dbContext); + string filePath = dt.RepositoryFilename(Database); using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { TemplateFile.CopyTo(fs); @@ -39,14 +39,14 @@ namespace Disco.BI.Extensions return Interop.Pdf.PdfImporter.GetPageImages(pdfReader, PageNumber); } - public static ConcurrentDictionary PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext dbContext) + public static ConcurrentDictionary PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext Database) { string cacheModuleKey = string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id); var module = Expressions.ExpressionCache.GetModule(cacheModuleKey); if (module == null) { // Cache - string templateFilename = dt.RepositoryFilename(dbContext); + string templateFilename = dt.RepositoryFilename(Database); PdfReader pdfReader = new PdfReader(templateFilename); int pdfFieldOrdinal = 0; foreach (string pdfFieldKey in pdfReader.AcroFields.Fields.Keys) @@ -61,21 +61,21 @@ namespace Disco.BI.Extensions return module; } - public static List ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext dbContext) + public static List ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext Database) { - return dt.PdfExpressionsFromCache(dbContext).Values.OrderBy(e => e.Ordinal).ToList(); + return dt.PdfExpressionsFromCache(Database).Values.OrderBy(e => e.Ordinal).ToList(); } - public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) + public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) { - return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjectsIds); + return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjectsIds); } - public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) + public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) { - return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); + return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjects); } - public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) + public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext Database, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) { - return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, dbContext, Data, CreatorUser, TimeStamp, State, FlattenFields); + return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, Database, Data, CreatorUser, TimeStamp, State, FlattenFields); } public static Expression FilterExpressionFromCache(this DocumentTemplate dt) @@ -86,12 +86,12 @@ namespace Disco.BI.Extensions { ExpressionCache.InvalidateKey("DocumentTemplateFilterExpression", dt.Id); } - public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState State) + public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext Database, User User, System.DateTime TimeStamp, DocumentState State) { if (!string.IsNullOrEmpty(dt.FilterExpression)) { Expression compiledExpression = dt.FilterExpressionFromCache(); - System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, DataContext, User, TimeStamp, State); + System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, Database, User, TimeStamp, State); try { object er = compiledExpression.EvaluateFirst(Data, evaluatorVariables); @@ -170,14 +170,14 @@ namespace Disco.BI.Extensions Page ); } - public static List QRCodeLocations(this DocumentTemplate dt, DiscoDataContext dbContext) + public static List QRCodeLocations(this DocumentTemplate dt, DiscoDataContext Database) { - return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, dbContext); + return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, Database); } - public static void Delete(this DocumentTemplate dt, DiscoDataContext Context) + public static void Delete(this DocumentTemplate dt, DiscoDataContext Database) { // Find & Rename all references - foreach (DeviceAttachment a in Context.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id)) + foreach (DeviceAttachment a in Database.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id)) { a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); if (a.Comments.Length > 500) @@ -185,7 +185,7 @@ namespace Disco.BI.Extensions a.DocumentTemplateId = null; a.DocumentTemplate = null; } - foreach (JobAttachment a in Context.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id)) + foreach (JobAttachment a in Database.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id)) { a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); if (a.Comments.Length > 500) @@ -193,7 +193,7 @@ namespace Disco.BI.Extensions a.DocumentTemplateId = null; a.DocumentTemplate = null; } - foreach (UserAttachment a in Context.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id)) + foreach (UserAttachment a in Database.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id)) { a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); if (a.Comments.Length > 500) @@ -206,7 +206,7 @@ namespace Disco.BI.Extensions dt.JobSubTypes.Clear(); // Delete Template - string templateRepositoryFilename = dt.RepositoryFilename(Context); + string templateRepositoryFilename = dt.RepositoryFilename(Database); if (System.IO.File.Exists(templateRepositoryFilename)) System.IO.File.Delete(templateRepositoryFilename); @@ -214,7 +214,7 @@ namespace Disco.BI.Extensions dt.FilterExpressionInvalidateCache(); // Delete Document Template from Repository - Context.DocumentTemplates.Remove(dt); + Database.DocumentTemplates.Remove(dt); } } } diff --git a/Disco.BI/BI/Extensions/JobActionExtensions.cs b/Disco.BI/BI/Extensions/JobActionExtensions.cs index bd75644d..14b3be1e 100644 --- a/Disco.BI/BI/Extensions/JobActionExtensions.cs +++ b/Disco.BI/BI/Extensions/JobActionExtensions.cs @@ -6,6 +6,8 @@ using Disco.Models.BI.Config; using Disco.Models.Repository; using Disco.Services.Plugins; using Disco.Services.Plugins.Features.WarrantyProvider; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { @@ -15,6 +17,9 @@ namespace Disco.BI.Extensions #region Device Held public static bool CanDeviceHeld(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceHeld)) + return false; + return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) && (!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue); } @@ -35,6 +40,9 @@ namespace Disco.BI.Extensions #region Device Ready for Return public static bool CanDeviceReadyForReturn(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReadyForReturn)) + return false; + return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && !j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue; } @@ -51,6 +59,9 @@ namespace Disco.BI.Extensions #region Device Returned public static bool CanDeviceReturned(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.DeviceReturned)) + return false; + return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && !j.DeviceReturnedDate.HasValue; } @@ -67,9 +78,12 @@ namespace Disco.BI.Extensions #region Waiting For User Action public static bool CanWaitingForUserAction(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.WaitingForUserAction)) + return false; + return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue; } - public static void OnWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Reason) + public static void OnWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Reason) { if (!j.CanWaitingForUserAction()) throw new InvalidOperationException("Waiting for User Action was Denied"); @@ -84,16 +98,19 @@ namespace Disco.BI.Extensions Timestamp = DateTime.Now, Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); } #endregion #region Not Waiting For User Action public static bool CanNotWaitingForUserAction(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NotWaitingForUserAction)) + return false; + return j.WaitingForUserAction.HasValue; } - public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Resolution) + public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext Database, User Technician, string Resolution) { if (!j.CanNotWaitingForUserAction()) throw new InvalidOperationException("Not Waiting for User Action was Denied"); @@ -108,31 +125,34 @@ namespace Disco.BI.Extensions Timestamp = DateTime.Now, Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); } #endregion #region Log Warranty public static bool CanLogWarranty(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogWarranty)) + return false; + return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) && j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); } - public static void OnLogWarranty(this Job j, DiscoDataContext dbContext, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary WarrantyProviderProperties) + public static void OnLogWarranty(this Job j, DiscoDataContext Database, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary WarrantyProviderProperties) { if (!j.CanLogWarranty()) throw new InvalidOperationException("Log Warranty was Denied"); if (string.IsNullOrWhiteSpace(FaultDescription)) - FaultDescription = j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition); + FaultDescription = j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition); else - FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition)); + FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(Database, WarrantyProviderDefinition)); using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance()) { - string providerRef = WarrantyProvider.SubmitJob(dbContext, j, Address, TechUser, FaultDescription, WarrantyProviderProperties); + string providerRef = WarrantyProvider.SubmitJob(Database, j, Address, TechUser, FaultDescription, WarrantyProviderProperties); j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now; j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId; @@ -150,7 +170,7 @@ namespace Disco.BI.Extensions Timestamp = DateTime.Now, Comments = string.Format("Warranty Claim Submitted{0}{0}Provider: {1}{0}Repair Address: {2}{0}Provider Reference: {3}{0}{0}{4}", Environment.NewLine, WarrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); } } #endregion @@ -158,32 +178,35 @@ namespace Disco.BI.Extensions #region Convert HWar to HNWar public static bool CanConvertHWarToHNWar(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ConvertHWarToHNWar)) + return false; + return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) && j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); } - public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext dbContext) + public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext Database) { if (!j.CanConvertHWarToHNWar()) throw new InvalidOperationException("Convert HWar to HNWar was Denied"); - var techUser = UserBI.UserCache.CurrentUser; + var techUser = UserService.CurrentUser; // Remove JobMetaWarranty if (j.JobMetaWarranty != null) - dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); + Database.JobMetaWarranties.Remove(j.JobMetaWarranty); // Add JobMetaNonWarranty var metaHNWar = new JobMetaNonWarranty() { Job = j }; - dbContext.JobMetaNonWarranties.Add(metaHNWar); + Database.JobMetaNonWarranties.Add(metaHNWar); // Swap Job Sub Types List jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList(); j.JobSubTypes.Clear(); - foreach (var jst in dbContext.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id))) + foreach (var jst in Database.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id))) j.JobSubTypes.Add(jst); // Add Components - var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); + var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var jobComponents = new List(); foreach (var component in components) { @@ -210,7 +233,7 @@ namespace Disco.BI.Extensions } foreach (var component in jobComponents) { - dbContext.JobComponents.Add(new JobComponent() + Database.JobComponents.Add(new JobComponent() { Job = j, TechUserId = techUser.Id, @@ -225,9 +248,9 @@ namespace Disco.BI.Extensions JobId = j.Id, TechUserId = techUser.Id, Timestamp = DateTime.Now, - Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, dbContext.JobTypes.Find(JobType.JobTypeIds.HWar), dbContext.JobTypes.Find(JobType.JobTypeIds.HNWar)) + Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, Database.JobTypes.Find(JobType.JobTypeIds.HWar), Database.JobTypes.Find(JobType.JobTypeIds.HNWar)) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); j.JobTypeId = JobType.JobTypeIds.HNWar; } @@ -252,6 +275,9 @@ namespace Disco.BI.Extensions #region Insurance Claim Form Sent public static bool CanInsuranceClaimFormSent(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent)) + return false; + return (j.JobTypeId == JobType.JobTypeIds.HNWar) && j.JobMetaNonWarranty.IsInsuranceClaim && !j.JobMetaInsurance.ClaimFormSentDate.HasValue; @@ -261,7 +287,7 @@ namespace Disco.BI.Extensions if (!j.CanInsuranceClaimFormSent()) throw new InvalidOperationException("Insurance Claim Form Sent was Denied"); - var techUser = UserBI.UserCache.CurrentUser; + var techUser = UserService.CurrentUser; j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now; j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id; @@ -271,6 +297,9 @@ namespace Disco.BI.Extensions #region Log Repair public static bool CanLogRepair(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.LogRepair)) + return false; + return (j.JobTypeId == JobType.JobTypeIds.HNWar) && (j.DeviceSerialNumber != null) && !j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && @@ -292,6 +321,9 @@ namespace Disco.BI.Extensions #region Repair Complete public static bool CanRepairComplete(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate)) + return false; + return (j.JobTypeId == JobType.JobTypeIds.HNWar) && j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue; @@ -308,6 +340,9 @@ namespace Disco.BI.Extensions #region Close public static bool CanClose(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Close)) + return false; + if (j.ClosedDate.HasValue) return false; // Job already Closed @@ -352,6 +387,9 @@ namespace Disco.BI.Extensions #region Force Close public static bool CanForceClose(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.ForceClose)) + return false; + var canCloseNormally = j.CanClose(); if (canCloseNormally) @@ -389,7 +427,7 @@ namespace Disco.BI.Extensions return false; } - public static void OnForceClose(this Job j, DiscoDataContext dbContext, User Technician, string Reason) + public static void OnForceClose(this Job j, DiscoDataContext Database, User Technician, string Reason) { if (!j.CanForceClose()) throw new InvalidOperationException("Force Close was Denied"); @@ -402,7 +440,7 @@ namespace Disco.BI.Extensions Timestamp = DateTime.Now, Comments = string.Format("Job Forcibly Closed{0}Reason: {1}", Environment.NewLine, Reason) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); j.ClosedDate = DateTime.Now; j.ClosedTechUserId = Technician.Id; @@ -412,6 +450,9 @@ namespace Disco.BI.Extensions #region Reopen public static bool CanReopen(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Reopen)) + return false; + return j.ClosedDate.HasValue; } public static void OnReopen(this Job j) @@ -427,47 +468,50 @@ namespace Disco.BI.Extensions #region Delete public static bool CanDelete(this Job j) { + if (!UserService.CurrentAuthorization.Has(Claims.Job.Actions.Delete)) + return false; + return j.ClosedDate.HasValue; } - public static void OnDelete(this Job j, DiscoDataContext dbContext) + public static void OnDelete(this Job j, DiscoDataContext Database) { // Job Sub Types j.JobSubTypes.Clear(); // Job Attachments foreach (var ja in j.JobAttachments.ToArray()) - ja.OnDelete(dbContext); + ja.OnDelete(Database); j.JobAttachments.Clear(); // Job Components foreach (var jc in j.JobComponents.ToArray()) - dbContext.JobComponents.Remove(jc); + Database.JobComponents.Remove(jc); j.JobComponents.Clear(); // Job Logs foreach (var jl in j.JobLogs.ToArray()) - dbContext.JobLogs.Remove(jl); + Database.JobLogs.Remove(jl); j.JobLogs.Clear(); // Job Meta if (j.JobMetaInsurance != null) { - dbContext.JobMetaInsurances.Remove(j.JobMetaInsurance); + Database.JobMetaInsurances.Remove(j.JobMetaInsurance); j.JobMetaInsurance = null; } if (j.JobMetaNonWarranty != null) { - dbContext.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty); + Database.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty); j.JobMetaNonWarranty = null; } if (j.JobMetaWarranty != null) { - dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); + Database.JobMetaWarranties.Remove(j.JobMetaWarranty); j.JobMetaWarranty = null; } // Job - dbContext.Jobs.Remove(j); + Database.Jobs.Remove(j); } #endregion } diff --git a/Disco.BI/BI/Extensions/JobExtensions.cs b/Disco.BI/BI/Extensions/JobExtensions.cs index f9c6d219..edb4513b 100644 --- a/Disco.BI/BI/Extensions/JobExtensions.cs +++ b/Disco.BI/BI/Extensions/JobExtensions.cs @@ -13,7 +13,7 @@ namespace Disco.BI.Extensions { public static class JobExtensions { - public static JobAttachment CreateAttachment(this Job Job, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) + public static JobAttachment CreateAttachment(this Job Job, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) { if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) MimeType = Interop.MimeTypes.ResolveMimeType(Filename); @@ -31,15 +31,15 @@ namespace Disco.BI.Extensions if (DocumentTemplate != null) ja.DocumentTemplateId = DocumentTemplate.Id; - dbContext.JobAttachments.Add(ja); - dbContext.SaveChanges(); + Database.JobAttachments.Add(ja); + Database.SaveChanges(); - ja.SaveAttachment(dbContext, Content); + ja.SaveAttachment(Database, Content); Content.Position = 0; if (PdfThumbnail == null) - ja.GenerateThumbnail(dbContext, Content); + ja.GenerateThumbnail(Database, Content); else - ja.SaveThumbnailAttachment(dbContext, PdfThumbnail); + ja.SaveThumbnailAttachment(Database, PdfThumbnail); return ja; } @@ -146,9 +146,9 @@ namespace Disco.BI.Extensions return Job.JobStatusIds.Open; } - public static List AvailableDocumentTemplates(this Job j, DiscoDataContext dbContext, User User, DateTime TimeStamp) + public static List AvailableDocumentTemplates(this Job j, DiscoDataContext Database, User User, DateTime TimeStamp) { - var dts = dbContext.DocumentTemplates.Include("JobSubTypes") + var dts = Database.DocumentTemplates.Include("JobSubTypes") .Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job) .ToList(); @@ -171,7 +171,7 @@ namespace Disco.BI.Extensions } // Evaluate Filters - dts = dts.Where(dt => dt.FilterExpressionMatches(j, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList(); + dts = dts.Where(dt => dt.FilterExpressionMatches(j, Database, User, TimeStamp, DocumentState.DefaultState())).ToList(); return dts; } @@ -188,7 +188,7 @@ namespace Disco.BI.Extensions return d; } - public static string GenerateFaultDescription(this Job j, DiscoDataContext dbContext) + public static string GenerateFaultDescription(this Job j, DiscoDataContext Database) { StringBuilder sb = new StringBuilder(); @@ -199,14 +199,14 @@ namespace Disco.BI.Extensions return sb.ToString(); } - public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext dbContext, PluginFeatureManifest WarrantyProviderDefinition) + public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition) { var versionDisco = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; return string.Format("Automation by Disco v{0}.{1}.{2:0000}.{3:0000} (Provider: {4} v{5})", versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4)); } - public static void UpdateSubTypes(this Job j, DiscoDataContext dbContext, List SubTypes, bool AddComponents, User TechUser) + public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List SubTypes, bool AddComponents, User TechUser) { if (SubTypes == null || SubTypes.Count == 0) throw new ArgumentException("The Job must contain at least one Sub Type"); @@ -246,7 +246,7 @@ namespace Disco.BI.Extensions foreach (var t in addedSubTypes) logBuilder.Append("- ").AppendLine(t.ToString()); } - dbContext.JobLogs.Add(new JobLog() + Database.JobLogs.Add(new JobLog() { JobId = j.Id, TechUserId = TechUser.Id, @@ -258,7 +258,7 @@ namespace Disco.BI.Extensions // Add Components if (AddComponents && addedSubTypes.Count > 0 && j.DeviceSerialNumber != null) { - var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); + var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var addedComponents = new List(); foreach (var c in components) { @@ -280,7 +280,7 @@ namespace Disco.BI.Extensions { if (!j.JobComponents.Any(jc => jc.Description.Equals(c.Description, StringComparison.InvariantCultureIgnoreCase))) { // Job Component with matching Description doesn't exist. - dbContext.JobComponents.Add(new JobComponent() + Database.JobComponents.Add(new JobComponent() { Job = j, TechUserId = TechUser.Id, diff --git a/Disco.BI/BI/Extensions/JobTableExtensions.cs b/Disco.BI/BI/Extensions/JobTableExtensions.cs index f7981f63..381daa56 100644 --- a/Disco.BI/BI/Extensions/JobTableExtensions.cs +++ b/Disco.BI/BI/Extensions/JobTableExtensions.cs @@ -5,16 +5,94 @@ using System.Text; using Disco.Models.BI.Job; using Disco.Models.Repository; using Disco.Data.Repository; +using Disco.Services.Users; +using Disco.Services.Authorization; namespace Disco.BI.Extensions { public static class JobTableExtensions { + private static List FilterAllowedTypes(AuthorizationToken Authorization) + { + if (!Authorization.HasAll(Claims.Job.Types.ShowHMisc, Claims.Job.Types.ShowHNWar, Claims.Job.Types.ShowHWar, Claims.Job.Types.ShowSApp, Claims.Job.Types.ShowSImg, Claims.Job.Types.ShowSOS, Claims.Job.Types.ShowUMgmt)) + { + // Must Filter + List allowedTypes = new List(6); + if (Authorization.Has(Claims.Job.Types.ShowHMisc)) + allowedTypes.Add(JobType.JobTypeIds.HMisc); + if (Authorization.Has(Claims.Job.Types.ShowHNWar)) + allowedTypes.Add(JobType.JobTypeIds.HNWar); + if (Authorization.Has(Claims.Job.Types.ShowHWar)) + allowedTypes.Add(JobType.JobTypeIds.HWar); + if (Authorization.Has(Claims.Job.Types.ShowSApp)) + allowedTypes.Add(JobType.JobTypeIds.SApp); + if (Authorization.Has(Claims.Job.Types.ShowSImg)) + allowedTypes.Add(JobType.JobTypeIds.SImg); + if (Authorization.Has(Claims.Job.Types.ShowSOS)) + allowedTypes.Add(JobType.JobTypeIds.SOS); + if (Authorization.Has(Claims.Job.Types.ShowUMgmt)) + allowedTypes.Add(JobType.JobTypeIds.UMgmt); - public static List DetermineItems(this JobTableModel model, DiscoDataContext dbContext, IQueryable Jobs) + return allowedTypes; + } + return null; + } + + public static IQueryable FilterPermissions(this JobTableModel model, IQueryable Jobs, AuthorizationToken Authorization) + { + var allowedTypes = FilterAllowedTypes(Authorization); + + if (allowedTypes != null) + { + return Jobs.Where(j => allowedTypes.Contains(j.JobTypeId)); + } + + return Jobs; + } + + public static List PermissionsFiltered(this List Items, AuthorizationToken Authorization) + { + if (Items != null && Items.Count > 0) + { + var allowedTypes = FilterAllowedTypes(Authorization); + + if (allowedTypes != null) + { + return Items.Where(j => allowedTypes.Contains(j.TypeId)).ToList(); + } + } + + return Items; + } + + public static List DetermineItems(this JobTableModel model, DiscoDataContext Database, IQueryable Jobs) { List items; + // Permissions + var auth = UserService.CurrentAuthorization; + if (!auth.HasAll(Claims.Job.Types.ShowHMisc, Claims.Job.Types.ShowHNWar, Claims.Job.Types.ShowHWar, Claims.Job.Types.ShowSApp, Claims.Job.Types.ShowSImg, Claims.Job.Types.ShowSOS, Claims.Job.Types.ShowUMgmt)) + { + // Must Filter + List allowedTypes = new List(6); + if (auth.Has(Claims.Job.Types.ShowHMisc)) + allowedTypes.Add(JobType.JobTypeIds.HMisc); + if (auth.Has(Claims.Job.Types.ShowHNWar)) + allowedTypes.Add(JobType.JobTypeIds.HNWar); + if (auth.Has(Claims.Job.Types.ShowHWar)) + allowedTypes.Add(JobType.JobTypeIds.HWar); + if (auth.Has(Claims.Job.Types.ShowSApp)) + allowedTypes.Add(JobType.JobTypeIds.SApp); + if (auth.Has(Claims.Job.Types.ShowSImg)) + allowedTypes.Add(JobType.JobTypeIds.SImg); + if (auth.Has(Claims.Job.Types.ShowSOS)) + allowedTypes.Add(JobType.JobTypeIds.SOS); + if (auth.Has(Claims.Job.Types.ShowUMgmt)) + allowedTypes.Add(JobType.JobTypeIds.UMgmt); + + Jobs = Jobs.Where(j => allowedTypes.Contains(j.JobTypeId)); + } + if (model.ShowStatus) { @@ -86,18 +164,18 @@ namespace Disco.BI.Extensions } if (!model.ShowDeviceAddress.HasValue) - model.ShowDeviceAddress = dbContext.DiscoConfiguration.MultiSiteMode; + model.ShowDeviceAddress = Database.DiscoConfiguration.MultiSiteMode; foreach (var j in items) if (j.DeviceAddressId.HasValue) - j.DeviceAddress = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name; + j.DeviceAddress = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name; return items; } - public static void Fill(this JobTableModel model, DiscoDataContext dbContext, IQueryable Jobs) + public static void Fill(this JobTableModel model, DiscoDataContext Database, IQueryable Jobs) { - model.Items = model.DetermineItems(dbContext, Jobs); + model.Items = model.DetermineItems(Database, Jobs); } } } diff --git a/Disco.BI/BI/Extensions/UserExtensions.cs b/Disco.BI/BI/Extensions/UserExtensions.cs index 37cc30df..8fd01e00 100644 --- a/Disco.BI/BI/Extensions/UserExtensions.cs +++ b/Disco.BI/BI/Extensions/UserExtensions.cs @@ -12,7 +12,7 @@ namespace Disco.BI.Extensions { public static class UserExtensions { - public static UserAttachment CreateAttachment(this User User, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) + public static UserAttachment CreateAttachment(this User User, DiscoDataContext Database, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) { if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) MimeType = Interop.MimeTypes.ResolveMimeType(Filename); @@ -30,25 +30,25 @@ namespace Disco.BI.Extensions if (DocumentTemplate != null) ua.DocumentTemplateId = DocumentTemplate.Id; - dbContext.UserAttachments.Add(ua); - dbContext.SaveChanges(); + Database.UserAttachments.Add(ua); + Database.SaveChanges(); - ua.SaveAttachment(dbContext, Content); + ua.SaveAttachment(Database, Content); Content.Position = 0; if (PdfThumbnail == null) - ua.GenerateThumbnail(dbContext, Content); + ua.GenerateThumbnail(Database, Content); else - ua.SaveThumbnailAttachment(dbContext, PdfThumbnail); + ua.SaveThumbnailAttachment(Database, PdfThumbnail); return ua; } - public static List AvailableDocumentTemplates(this User u, DiscoDataContext dbContext, User User, DateTime TimeStamp) + public static List AvailableDocumentTemplates(this User u, DiscoDataContext Database, User User, DateTime TimeStamp) { - var dts = dbContext.DocumentTemplates.Include("JobSubTypes") + var dts = Database.DocumentTemplates.Include("JobSubTypes") .Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User) .ToArray() - .Where(dt => dt.FilterExpressionMatches(u, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList(); + .Where(dt => dt.FilterExpressionMatches(u, Database, User, TimeStamp, DocumentState.DefaultState())).ToList(); return dts; } diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectory.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectory.cs index c91df41f..d9cccfec 100644 --- a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectory.cs +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectory.cs @@ -12,6 +12,17 @@ namespace Disco.BI.Interop.ActiveDirectory { public static class ActiveDirectory { + #region Machine Accounts + + private static readonly string[] MachineLoadProperties = { + "name", + "distinguishedName", + "sAMAccountName", + "objectSid", + "dNSHostName", + "netbootGUID", + "isCriticalSystemObject" + }; public static ActiveDirectoryMachineAccount GetMachineAccount(string ComputerName, System.Guid? UUIDNetbootGUID = null, System.Guid? MacAddressNetbootGUID = null, params string[] AdditionalProperties) { if (string.IsNullOrWhiteSpace(ComputerName)) @@ -26,36 +37,36 @@ namespace Disco.BI.Interop.ActiveDirectory using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) { - var loadProperties = new List { "name", "distinguishedName", "sAMAccountName", "objectSid", "dNSHostName", "netbootGUID", "isCriticalSystemObject" }; - loadProperties.AddRange(AdditionalProperties); - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree)) + var loadProperties = AdditionalProperties == null ? MachineLoadProperties : MachineLoadProperties.Concat(AdditionalProperties).ToArray(); + + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties, SearchScope.Subtree)) { SearchResult dResult = dSearcher.FindOne(); if (dResult != null) { - return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); + return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties); } } if (UUIDNetbootGUID.HasValue) { - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties, SearchScope.Subtree)) { SearchResult dResult = dSearcher.FindOne(); if (dResult != null) { - return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); + return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties); } } } if (MacAddressNetbootGUID.HasValue) { - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties, SearchScope.Subtree)) { SearchResult dResult = dSearcher.FindOne(); if (dResult != null) { - return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); + return ActiveDirectory.ActiveDirectoryMachineAccountFromSearchResult(dResult, AdditionalProperties); } } } @@ -64,7 +75,7 @@ namespace Disco.BI.Interop.ActiveDirectory return null; } - private static ActiveDirectoryMachineAccount DirectorySearchResultToMachineAccount(SearchResult result, params string[] AdditionalProperties) + private static ActiveDirectoryMachineAccount ActiveDirectoryMachineAccountFromSearchResult(SearchResult result, params string[] AdditionalProperties) { string name = result.Properties["name"][0].ToString(); string sAMAccountName = result.Properties["sAMAccountName"][0].ToString(); @@ -89,21 +100,22 @@ namespace Disco.BI.Interop.ActiveDirectory // Additional Properties Dictionary additionalProperties = new Dictionary(); - foreach (string propertyName in AdditionalProperties) - { - var property = result.Properties[propertyName]; - var propertyValues = new List(); - for (int index = 0; index < property.Count; index++) - propertyValues.Add(property[index]); - additionalProperties.Add(propertyName, propertyValues.ToArray()); - } + if (AdditionalProperties != null) + foreach (string propertyName in AdditionalProperties) + { + var property = result.Properties[propertyName]; + var propertyValues = new List(); + for (int index = 0; index < property.Count; index++) + propertyValues.Add(property[index]); + additionalProperties.Add(propertyName, propertyValues.ToArray()); + } return new ActiveDirectoryMachineAccount { Name = name, DistinguishedName = distinguishedName, - sAMAccountName = sAMAccountName, - ObjectSid = objectSid, + SamAccountName = sAMAccountName, + SecurityIdentifier = objectSid, NetbootGUID = netbootGUIDResult, Path = result.Path, Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, @@ -112,132 +124,9 @@ namespace Disco.BI.Interop.ActiveDirectory LoadedProperties = additionalProperties }; } - private static ActiveDirectoryUserAccount SearchResultToActiveDirectoryUserAccount(SearchResult result, params string[] AdditionalProperties) - { - string name = result.Properties["name"][0].ToString(); - string username = result.Properties["sAMAccountName"][0].ToString(); - string distinguishedName = result.Properties["distinguishedName"][0].ToString(); - byte[] objectSid = (byte[])result.Properties["objectSid"][0]; - string objectSidSDDL = ActiveDirectoryHelpers.ConvertBytesToSDDLString(objectSid); - ResultPropertyValueCollection displayNameProp = result.Properties["displayName"]; - string displayName = username; - if (displayNameProp.Count > 0) - displayName = displayNameProp[0].ToString(); - string surname = null; - ResultPropertyValueCollection surnameProp = result.Properties["sn"]; - if (surnameProp.Count > 0) - surname = surnameProp[0].ToString(); - string givenName = null; - ResultPropertyValueCollection givenNameProp = result.Properties["givenName"]; - if (givenNameProp.Count > 0) - givenName = givenNameProp[0].ToString(); - string email = null; - ResultPropertyValueCollection emailProp = result.Properties["mail"]; - if (emailProp.Count > 0) - email = emailProp[0].ToString(); - string phone = null; - ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"]; - if (phoneProp.Count > 0) - phone = phoneProp[0].ToString(); + #endregion - int primaryGroupID = (int)result.Properties["primaryGroupID"][0]; - string primaryGroupSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString(ActiveDirectoryHelpers.BuildPrimaryGroupSid(objectSid, primaryGroupID)); - var groupCNs = result.Properties["memberOf"].Cast().ToList(); - groupCNs.Add(ActiveDirectoryCachedGroups.GetGroupsCnForSid(primaryGroupSid)); - List groups = ActiveDirectoryCachedGroups.GetGroups(groupCNs).Select(g => g.ToLower()).ToList(); - - //foreach (string groupCN in result.Properties["memberOf"]) - //{ - // Removed 2012-11-30 G# - Moved to Recursive Cache - //var groupCNlower = groupCN.ToLower(); - //if (groupCNlower.StartsWith("cn=")) - // groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3)); - // End Removed 2012-11-30 G# - //} - - string type = null; - if (groups.Contains("domain admins") || groups.Contains("disco admins")) - { - type = "Admin"; - } - else - { - if (groups.Contains("staff")) - { - type = "Staff"; - } - else - { - if (groups.Contains("students")) - { - type = "Student"; - } - } - } - - // Additional Properties - Dictionary additionalProperties = new Dictionary(); - foreach (string propertyName in AdditionalProperties) - { - var property = result.Properties[propertyName]; - var propertyValues = new List(); - for (int index = 0; index < property.Count; index++) - propertyValues.Add(property[index]); - additionalProperties.Add(propertyName, propertyValues.ToArray()); - } - - return new ActiveDirectoryUserAccount - { - Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, - Name = name, - Surname = surname, - GivenName = givenName, - Email = email, - Phone = phone, - DistinguishedName = distinguishedName, - sAMAccountName = username, - DisplayName = displayName, - ObjectSid = objectSidSDDL, - Type = type, - Path = result.Path, - LoadedProperties = additionalProperties - }; - } - public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties) - { - if (string.IsNullOrWhiteSpace(Username)) - throw new System.ArgumentException("Invalid User Account", "Username"); - string sAMAccountName = Username; - if (sAMAccountName.Contains("\\")) - sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1)); - - using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) - { - var loadProperties = new List { - "name", - "distinguishedName", - "sAMAccountName", - "objectSid", - "displayName", - "sn", - "givenName", - "memberOf", - "primaryGroupID", - "mail", - "telephoneNumber" - }; - loadProperties.AddRange(AdditionalProperties); - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=user)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree)) - { - SearchResult dResult = dSearcher.FindOne(); - if (dResult != null) - return ActiveDirectory.SearchResultToActiveDirectoryUserAccount(dResult, AdditionalProperties); - else - return null; - } - } - } public static string OfflineDomainJoinProvision(ref ActiveDirectoryMachineAccount ExistingAccount, string ComputerName, string OrganisationalUnit = null, string EnrolSessionId = null) { if (ExistingAccount != null && ExistingAccount.IsCriticalSystemObject) @@ -323,6 +212,21 @@ namespace Disco.BI.Interop.ActiveDirectory return DJoinResult; } + #region Users + + private static readonly string[] UserLoadProperties = { + "name", + "distinguishedName", + "sAMAccountName", + "objectSid", + "displayName", + "sn", + "givenName", + "memberOf", + "primaryGroupID", + "mail", + "telephoneNumber" + }; public static List SearchUsers(string term) { List users = new List(); @@ -331,31 +235,118 @@ namespace Disco.BI.Interop.ActiveDirectory term = ActiveDirectoryHelpers.EscapeLdapQuery(term); using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName))) { - using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectClass=User)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), new string[] - { - "name", - "distinguishedName", - "sAMAccountName", - "objectSid", - "displayName", - "sn", - "givenName", - "memberOf", - "primaryGroupID", - "mail", - "telephoneNumber" - }, SearchScope.Subtree)) + using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectCategory=Person)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), UserLoadProperties, SearchScope.Subtree)) { searcher.SizeLimit = 30; SearchResultCollection results = searcher.FindAll(); foreach (SearchResult result in results) { - users.Add(ActiveDirectory.SearchResultToActiveDirectoryUserAccount(result)); + users.Add(ActiveDirectory.ActiveDirectoryUserAccountFromSearchResult(result)); } } } return users; } + private static ActiveDirectoryUserAccount ActiveDirectoryUserAccountFromSearchResult(SearchResult result, params string[] AdditionalProperties) + { + string name = result.Properties["name"][0].ToString(); + string username = result.Properties["sAMAccountName"][0].ToString(); + string distinguishedName = result.Properties["distinguishedName"][0].ToString(); + byte[] objectSid = (byte[])result.Properties["objectSid"][0]; + string objectSidSDDL = ActiveDirectoryHelpers.ConvertBytesToSDDLString(objectSid); + + ResultPropertyValueCollection displayNameProp = result.Properties["displayName"]; + string displayName = username; + if (displayNameProp.Count > 0) + displayName = displayNameProp[0].ToString(); + string surname = null; + ResultPropertyValueCollection surnameProp = result.Properties["sn"]; + if (surnameProp.Count > 0) + surname = surnameProp[0].ToString(); + string givenName = null; + ResultPropertyValueCollection givenNameProp = result.Properties["givenName"]; + if (givenNameProp.Count > 0) + givenName = givenNameProp[0].ToString(); + string email = null; + ResultPropertyValueCollection emailProp = result.Properties["mail"]; + if (emailProp.Count > 0) + email = emailProp[0].ToString(); + string phone = null; + ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"]; + if (phoneProp.Count > 0) + phone = phoneProp[0].ToString(); + + int primaryGroupID = (int)result.Properties["primaryGroupID"][0]; + string primaryGroupSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString(ActiveDirectoryHelpers.BuildPrimaryGroupSid(objectSid, primaryGroupID)); + var groupDistinguishedNames = result.Properties["memberOf"].Cast().ToList(); + groupDistinguishedNames.Add(ActiveDirectoryCachedGroups.GetGroupsDistinguishedNameForSecurityIdentifier(primaryGroupSid)); + List groups = ActiveDirectoryCachedGroups.GetGroups(groupDistinguishedNames).ToList(); + + //foreach (string groupCN in result.Properties["memberOf"]) + //{ + // Removed 2012-11-30 G# - Moved to Recursive Cache + //var groupCNlower = groupCN.ToLower(); + //if (groupCNlower.StartsWith("cn=")) + // groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3)); + // End Removed 2012-11-30 G# + //} + + // Additional Properties + Dictionary additionalProperties = new Dictionary(); + if (AdditionalProperties != null) + foreach (string propertyName in AdditionalProperties) + { + var property = result.Properties[propertyName]; + var propertyValues = new List(); + for (int index = 0; index < property.Count; index++) + propertyValues.Add(property[index]); + additionalProperties.Add(propertyName, propertyValues.ToArray()); + } + + return new ActiveDirectoryUserAccount + { + Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, + Name = name, + Surname = surname, + GivenName = givenName, + Email = email, + Phone = phone, + DistinguishedName = distinguishedName, + SamAccountName = username, + DisplayName = displayName, + SecurityIdentifier = objectSidSDDL, + Groups = groups, + Path = result.Path, + LoadedProperties = additionalProperties + }; + } + public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties) + { + if (string.IsNullOrWhiteSpace(Username)) + throw new System.ArgumentException("Invalid User Account", "Username"); + string sAMAccountName = Username; + if (sAMAccountName.Contains("\\")) + sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1)); + + using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) + { + var loadProperties = AdditionalProperties == null ? UserLoadProperties : UserLoadProperties.Concat(AdditionalProperties).ToArray(); + + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Person)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties, SearchScope.Subtree)) + { + SearchResult dResult = dSearcher.FindOne(); + if (dResult != null) + return ActiveDirectory.ActiveDirectoryUserAccountFromSearchResult(dResult, AdditionalProperties); + else + return null; + } + } + } + + #endregion + + #region Organisation Units + public static List GetOrganisationalUnitStructure() { ActiveDirectoryOrganisationalUnit DomainOUs = new ActiveDirectoryOrganisationalUnit @@ -399,5 +390,173 @@ namespace Disco.BI.Interop.ActiveDirectory } } + + #endregion + + #region Groups + + private static readonly string[] GroupLoadProperties = { + "name", + "distinguishedName", + "cn", + "sAMAccountName", + "objectSid", + "memberOf" + }; + public static ActiveDirectoryGroup GetGroup(string SamAccountName) + { + if (string.IsNullOrWhiteSpace(SamAccountName)) + throw new System.ArgumentException("Invalid Group Account", "SamAccountName"); + string sAMAccountName = SamAccountName; + if (sAMAccountName.Contains("\\")) + sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1)); + + using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) + { + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Group)(objectSid={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), GroupLoadProperties, SearchScope.Subtree)) + { + SearchResult dResult = dSearcher.FindOne(); + if (dResult != null) + { + return ActiveDirectoryGroupFromSearchResult(dResult); + } + else + return null; + } + } + } + public static ActiveDirectoryGroup GetGroupFromDistinguishedName(string DistinguishedName) + { + ActiveDirectoryGroup group = null; + + using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, DistinguishedName))) + { + if (groupDE != null) + { + return ActiveDirectoryGroupFromDirectoryEntry(groupDE); + } + } + + return group; + } + public static ActiveDirectoryGroup GetGroupFromSecurityIdentifier(string SecurityIdentifier) + { + using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) + { + var sidBytes = ActiveDirectoryHelpers.ConvertSDDLStringToBytes(SecurityIdentifier); + var sidBinaryString = ActiveDirectoryHelpers.ConvertBytesToBinarySidString(sidBytes); + + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Group)(objectSid={0}))", sidBinaryString), GroupLoadProperties, SearchScope.Subtree)) + { + SearchResult dResult = dSearcher.FindOne(); + if (dResult != null) + { + return ActiveDirectoryGroupFromSearchResult(dResult); + } + else + return null; + } + } + } + + public static List SearchGroups(string term) + { + List results = new List(); + string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName; + string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName; + term = ActiveDirectoryHelpers.EscapeLdapQuery(term); + using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName))) + { + using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectCategory=Group)(|(sAMAccountName=*{0}*)(name=*{0}*)(cn=*{0}*)))", term), GroupLoadProperties, SearchScope.Subtree)) + { + searcher.SizeLimit = 30; + SearchResultCollection searchResults = searcher.FindAll(); + foreach (SearchResult result in searchResults) + { + results.Add(ActiveDirectory.ActiveDirectoryGroupFromSearchResult(result)); + } + } + } + return results; + } + + private static ActiveDirectoryGroup ActiveDirectoryGroupFromDirectoryEntry(DirectoryEntry entry) + { + var name = (string)entry.Properties["name"].Value; + var distinguishedName = (string)entry.Properties["distinguishedName"].Value; + var cn = (string)entry.Properties["cn"].Value; + var sAMAccountName = (string)entry.Properties["sAMAccountName"].Value; + var objectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])entry.Properties["objectSid"].Value); + var memberOf = entry.Properties["memberOf"].Cast().ToList(); + + return new ActiveDirectoryGroup() + { + Name = name, + DistinguishedName = distinguishedName, + CommonName = cn, + SamAccountName = sAMAccountName, + SecurityIdentifier = objectSid, + MemberOf = memberOf + }; + } + private static ActiveDirectoryGroup ActiveDirectoryGroupFromSearchResult(SearchResult result) + { + var name = (string)result.Properties["name"][0]; + var distinguishedName = (string)result.Properties["distinguishedName"][0]; + var cn = (string)result.Properties["cn"][0]; + var sAMAccountName = (string)result.Properties["sAMAccountName"][0]; + var objectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])result.Properties["objectSid"][0]); + var memberOf = result.Properties["memberOf"].Cast().ToList(); + + return new ActiveDirectoryGroup() + { + Name = name, + DistinguishedName = distinguishedName, + CommonName = cn, + SamAccountName = sAMAccountName, + SecurityIdentifier = objectSid, + MemberOf = memberOf + }; + } + + #endregion + + private static readonly string[] ObjectLoadProperties = { "objectCategory" }; + private static readonly string[] ObjectLoadPropertiesAll = ObjectLoadProperties.Concat(UserLoadProperties).Concat(MachineLoadProperties).Concat(GroupLoadProperties).Distinct().ToArray(); + + public static IActiveDirectoryObject GetObject(string SamAccountName) + { + if (string.IsNullOrWhiteSpace(SamAccountName)) + throw new System.ArgumentException("Invalid Object Account Name", "SamAccountName"); + string sAMAccountName = SamAccountName; + if (sAMAccountName.Contains("\\")) + sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1)); + + using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) + { + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(|(objectCategory=Person)(objectCategory=Computer)(objectCategory=Group))(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), ObjectLoadPropertiesAll, SearchScope.Subtree)) + { + SearchResult dResult = dSearcher.FindOne(); + if (dResult != null) + { + var objectCategory = (string)dResult.Properties["objectCategory"][0]; + objectCategory = objectCategory.Substring(0, objectCategory.IndexOf(',')).ToLower(); + switch (objectCategory) + { + case "cn=person": + return ActiveDirectoryUserAccountFromSearchResult(dResult); + case "cn=computer": + return ActiveDirectoryMachineAccountFromSearchResult(dResult); + case "cn=group": + return ActiveDirectoryGroupFromSearchResult(dResult); + default: + throw new InvalidOperationException("Unexpected objectCategory"); + } + } + else + return null; + } + } + } } } diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryCachedGroups.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryCachedGroups.cs index e1e2892b..abbb510a 100644 --- a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryCachedGroups.cs +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryCachedGroups.cs @@ -8,43 +8,44 @@ using System.Threading.Tasks; using Disco.Data.Repository; using Disco.Services.Tasks; using Quartz; +using Disco.Models.Interop.ActiveDirectory; namespace Disco.BI.Interop.ActiveDirectory { public class ActiveDirectoryCachedGroups : ScheduledTask { - private static ConcurrentDictionary> _SidCache = new ConcurrentDictionary>(); - private static ConcurrentDictionary> _Cache = new ConcurrentDictionary>(); + private static ConcurrentDictionary> _SecurityIdentifierCache = new ConcurrentDictionary>(); + private static ConcurrentDictionary> _DistinguishedNameCache = new ConcurrentDictionary>(); private const long CacheTimeoutTicks = 6000000000; // 10 Minutes - public static IEnumerable GetGroups(IEnumerable GroupCNs) + public static IEnumerable GetGroups(IEnumerable DistinguishedNames) { - List groups = new List(); + List groups = new List(); - foreach (var groupCN in GroupCNs) - foreach (var group in GetGroupsRecursive(groupCN, new Stack())) + foreach (var distinguishedName in DistinguishedNames) + foreach (var group in GetGroupsRecursive(distinguishedName, new Stack())) if (!groups.Contains(group)) { groups.Add(group); - yield return group.FriendlyName; + yield return group.SamAccountName; } } - public static IEnumerable GetGroups(string GroupCN) + public static IEnumerable GetGroups(string DistinguishedName) { - foreach (var group in GetGroupsRecursive(GroupCN, new Stack())) - yield return group.FriendlyName; + foreach (var group in GetGroupsRecursive(DistinguishedName, new Stack())) + yield return group.SamAccountName; } - public static string GetGroupsCnForSid(string GroupSid) + public static string GetGroupsDistinguishedNameForSecurityIdentifier(string SecurityIdentifier) { - var sidGroup = GetGroupBySid(GroupSid); - if (sidGroup == null) + var group = GetGroupBySecurityIdentifier(SecurityIdentifier); + if (group == null) return null; else - return sidGroup.CN; + return group.DistinguishedName; } - private static IEnumerable GetGroupsRecursive(string GroupCN, Stack RecursiveTree) + private static IEnumerable GetGroupsRecursive(string DistinguishedName, Stack RecursiveTree) { - var group = GetGroup(GroupCN); + var group = GetGroup(DistinguishedName); if (group != null && !RecursiveTree.Contains(group)) { @@ -54,24 +55,24 @@ namespace Disco.BI.Interop.ActiveDirectory { RecursiveTree.Push(group); - foreach (var memberOfGroupCN in group.MemberOf) - foreach (var memberOfGroup in GetGroupsRecursive(memberOfGroupCN, RecursiveTree)) - yield return memberOfGroup; + foreach (var parentDistinguishedName in group.MemberOf) + foreach (var parentGroup in GetGroupsRecursive(parentDistinguishedName, RecursiveTree)) + yield return parentGroup; RecursiveTree.Pop(); } } } - private static ADCachedGroup GetGroup(string GroupCN) + private static ActiveDirectoryGroup GetGroup(string DistinguishedName) { // Check Cache - Tuple groupRecord = TryCache(GroupCN); + Tuple groupRecord = TryCache(DistinguishedName); if (groupRecord == null) { // Load from AD - var group = ADCachedGroup.LoadWithCN(GroupCN); + var group = ActiveDirectory.GetGroupFromDistinguishedName(DistinguishedName); SetValue(group); return group; @@ -82,15 +83,15 @@ namespace Disco.BI.Interop.ActiveDirectory return groupRecord.Item1; } } - private static ADCachedGroup GetGroupBySid(string GroupSid) + private static ActiveDirectoryGroup GetGroupBySecurityIdentifier(string SecurityIdentifier) { // Check Cache - Tuple groupRecord = TrySidCache(GroupSid); + Tuple groupRecord = TrySecurityIdentifierCache(SecurityIdentifier); if (groupRecord == null) { // Load from AD - var group = ADCachedGroup.LoadWithSid(GroupSid); + var group = ActiveDirectory.GetGroupFromSecurityIdentifier(SecurityIdentifier); SetValue(group); return group; @@ -102,177 +103,96 @@ namespace Disco.BI.Interop.ActiveDirectory } } - private static Tuple TryCache(string GroupCN) + private static Tuple TryCache(string DistinguishedName) { - string groupCN = GroupCN.ToLower(); - Tuple groupRecord; - if (_Cache.TryGetValue(groupCN, out groupRecord)) + string distinguishedName = DistinguishedName.ToLower(); + Tuple groupRecord; + if (_DistinguishedNameCache.TryGetValue(distinguishedName, out groupRecord)) { if (groupRecord.Item2 > DateTime.Now) return groupRecord; else { - if (_Cache.TryRemove(groupCN, out groupRecord)) - _SidCache.TryRemove(groupRecord.Item1.ObjectSid, out groupRecord); + if (_DistinguishedNameCache.TryRemove(distinguishedName, out groupRecord)) + _SecurityIdentifierCache.TryRemove(groupRecord.Item1.SecurityIdentifier, out groupRecord); } } return null; } - private static Tuple TrySidCache(string GroupSid) + private static Tuple TrySecurityIdentifierCache(string SecurityIdentifier) { - Tuple groupRecord; - if (_SidCache.TryGetValue(GroupSid, out groupRecord)) + Tuple groupRecord; + if (_SecurityIdentifierCache.TryGetValue(SecurityIdentifier, out groupRecord)) { if (groupRecord.Item2 > DateTime.Now) return groupRecord; else { - if (_SidCache.TryRemove(GroupSid, out groupRecord)) - _Cache.TryRemove(groupRecord.Item1.CN.ToLower(), out groupRecord); + if (_SecurityIdentifierCache.TryRemove(SecurityIdentifier, out groupRecord)) + _DistinguishedNameCache.TryRemove(groupRecord.Item1.DistinguishedName.ToLower(), out groupRecord); } } return null; } - private static bool SetValue(ADCachedGroup GroupRecord) + private static bool SetValue(ActiveDirectoryGroup Group) { - Tuple groupRecord = new Tuple(GroupRecord, DateTime.Now.AddTicks(CacheTimeoutTicks)); - Tuple oldGroupRecord; + Tuple groupRecord = new Tuple(Group, DateTime.Now.AddTicks(CacheTimeoutTicks)); + Tuple oldGroupRecord; - string key = GroupRecord.CN.ToLower(); - if (_Cache.ContainsKey(key)) + string key = Group.DistinguishedName.ToLower(); + if (_DistinguishedNameCache.ContainsKey(key)) { - if (_Cache.TryGetValue(key, out oldGroupRecord)) + if (_DistinguishedNameCache.TryGetValue(key, out oldGroupRecord)) { - _Cache.TryUpdate(key, groupRecord, oldGroupRecord); + _DistinguishedNameCache.TryUpdate(key, groupRecord, oldGroupRecord); } } else { - _Cache.TryAdd(key, groupRecord); + _DistinguishedNameCache.TryAdd(key, groupRecord); } - string sid = GroupRecord.ObjectSid; - if (_SidCache.ContainsKey(sid)) + string securityIdentifier = Group.SecurityIdentifier; + if (_SecurityIdentifierCache.ContainsKey(securityIdentifier)) { - if (_SidCache.TryGetValue(sid, out oldGroupRecord)) + if (_SecurityIdentifierCache.TryGetValue(securityIdentifier, out oldGroupRecord)) { - _SidCache.TryUpdate(sid, groupRecord, oldGroupRecord); + _SecurityIdentifierCache.TryUpdate(securityIdentifier, groupRecord, oldGroupRecord); } } else { - _SidCache.TryAdd(sid, groupRecord); + _SecurityIdentifierCache.TryAdd(securityIdentifier, groupRecord); } return true; } - private class ADCachedGroup - { - public string ObjectSid { get; set; } - public string CN { get; private set; } - public string FriendlyName { get; private set; } - - public List MemberOf { get; private set; } - - public static ADCachedGroup LoadWithCN(string CN) - { - ADCachedGroup group = null; - - using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, CN))) - { - if (groupDE != null) - { - group = new ADCachedGroup() - { - CN = CN - }; - - group.ObjectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])groupDE.Properties["objectSid"].Value); - group.FriendlyName = (string)groupDE.Properties["sAMAccountName"].Value; - - var groupMemberOf = groupDE.Properties["memberOf"]; - if (groupMemberOf != null && groupMemberOf.Count > 0) - { - group.MemberOf = groupMemberOf.Cast().ToList(); - } - } - } - - return group; - } - - public static ADCachedGroup LoadWithSid(string Sid) - { - using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) - { - var loadProperties = new List { - "distinguishedName", - "objectSid", - "sAMAccountName", - "memberOf" - }; - - var sidBytes = ActiveDirectoryHelpers.ConvertSDDLStringToBytes(Sid); - var sidBinaryString = ActiveDirectoryHelpers.ConvertBytesToBinarySidString(sidBytes); - - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=group)(objectSid={0}))", sidBinaryString), loadProperties.ToArray(), SearchScope.Subtree)) - { - SearchResult dResult = dSearcher.FindOne(); - if (dResult != null) - { - var group = new ADCachedGroup() - { - CN = (string)dResult.Properties["distinguishedName"][0], - ObjectSid = ActiveDirectoryHelpers.ConvertBytesToSDDLString((byte[])dResult.Properties["objectSid"][0]), - FriendlyName = (string)dResult.Properties["sAMAccountName"][0] - }; - - var groupMemberOf = dResult.Properties["memberOf"]; - if (groupMemberOf != null && groupMemberOf.Count > 0) - { - group.MemberOf = groupMemberOf.Cast().ToList(); - } - - return group; - } - else - return null; - } - } - } - - private ADCachedGroup() - { - // Private Constructor - } - } - private static void CleanStaleCache() { // Clean Cache - var groupKeys = _Cache.Keys.ToArray(); + var groupKeys = _DistinguishedNameCache.Keys.ToArray(); foreach (string groupKey in groupKeys) { - Tuple groupRecord; - if (_Cache.TryGetValue(groupKey, out groupRecord)) + Tuple groupRecord; + if (_DistinguishedNameCache.TryGetValue(groupKey, out groupRecord)) { if (groupRecord.Item2 <= DateTime.Now) { - _Cache.TryRemove(groupKey, out groupRecord); + _DistinguishedNameCache.TryRemove(groupKey, out groupRecord); } } } // Clean SID Cache - groupKeys = _SidCache.Keys.ToArray(); + groupKeys = _SecurityIdentifierCache.Keys.ToArray(); foreach (string groupKey in groupKeys) { - Tuple groupRecord; - if (_SidCache.TryGetValue(groupKey, out groupRecord)) + Tuple groupRecord; + if (_SecurityIdentifierCache.TryGetValue(groupKey, out groupRecord)) { if (groupRecord.Item2 <= DateTime.Now) { - _SidCache.TryRemove(groupKey, out groupRecord); + _SecurityIdentifierCache.TryRemove(groupKey, out groupRecord); } } } @@ -284,7 +204,7 @@ namespace Disco.BI.Interop.ActiveDirectory public override bool CancelInitiallySupported { get { return false; } } public override bool LogExceptionsOnly { get { return true; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Run @ every 15mins diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryGroupExtensions.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryGroupExtensions.cs new file mode 100644 index 00000000..8de7ad15 --- /dev/null +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryGroupExtensions.cs @@ -0,0 +1,19 @@ +using Disco.Models.Interop.ActiveDirectory; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.BI.Interop.ActiveDirectory +{ + public static class ActiveDirectoryGroupExtensions + { + + public static IEnumerable> GetMembers(ActiveDirectoryGroup group) + { + throw new NotImplementedException(); + } + + } +} diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryMachineAccountExtensions.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryMachineAccountExtensions.cs index ffcd85a1..d3c7e404 100644 --- a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryMachineAccountExtensions.cs +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryMachineAccountExtensions.cs @@ -191,11 +191,11 @@ namespace Disco.BI.Interop.ActiveDirectory case "name": return account.Name; case "samaccountname": - return account.sAMAccountName; + return account.SamAccountName; case "distinguishedname": return account.DistinguishedName; case "objectsid": - return account.ObjectSid; + return account.SecurityIdentifier; case "netbootguid": return account.NetbootGUID; default: @@ -268,7 +268,9 @@ namespace Disco.BI.Interop.ActiveDirectory if (account.IsCriticalSystemObject) throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); - if (!account.ParentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase)) + var parentDistinguishedName = account.ParentDistinguishedName(); + + if (parentDistinguishedName != null && !parentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase)) { string ouPath; if (string.IsNullOrWhiteSpace(NewOrganisationUnit)) @@ -286,5 +288,14 @@ namespace Disco.BI.Interop.ActiveDirectory } } + public static string ParentDistinguishedName(this ActiveDirectoryMachineAccount account) + { + // Determine Parent + if (!string.IsNullOrWhiteSpace(account.DistinguishedName)) + return account.DistinguishedName.Substring(0, account.DistinguishedName.IndexOf(",DC=")).Substring(account.DistinguishedName.IndexOf(",") + 1); + else + return null; + } + } } diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUpdateLastNetworkLogonDateJob.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUpdateLastNetworkLogonDateJob.cs index 1c5c9e4e..63ca1fe4 100644 --- a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUpdateLastNetworkLogonDateJob.cs +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUpdateLastNetworkLogonDateJob.cs @@ -21,7 +21,7 @@ namespace Disco.BI.Interop.ActiveDirectory public override bool SingleInstanceTask { get { return true; } } public override bool CancelInitiallySupported { get { return false; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm TriggerBuilder triggerBuilder = TriggerBuilder.Create(). @@ -35,11 +35,11 @@ namespace Disco.BI.Interop.ActiveDirectory int changeCount; this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - UpdateLastNetworkLogonDates(dbContext, this.Status); + UpdateLastNetworkLogonDates(database, this.Status); this.Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database"); - changeCount = dbContext.SaveChanges(); + changeCount = database.SaveChanges(); this.Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig"); } @@ -86,7 +86,7 @@ namespace Disco.BI.Interop.ActiveDirectory { using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultDCLdapRoot(dcName)) { - DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[] + DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectCategory=Computer)(sAMAccountName={0}$))", ActiveDirectoryHelpers.EscapeLdapQuery(Device.ComputerName)), new string[] { "lastLogon" }, SearchScope.Subtree); @@ -150,7 +150,7 @@ namespace Disco.BI.Interop.ActiveDirectory UpdateLastNetworkLogonDate = false; return UpdateLastNetworkLogonDate; } - private static void UpdateLastNetworkLogonDates(DiscoDataContext context, ScheduledTaskStatus status) + private static void UpdateLastNetworkLogonDates(DiscoDataContext Database, ScheduledTaskStatus status) { System.Collections.Generic.Dictionary computerLastLogonDates = new System.Collections.Generic.Dictionary(); @@ -176,7 +176,7 @@ namespace Disco.BI.Interop.ActiveDirectory double progressDCStart = 5 + (progressDCCount * progressDCProgress); status.UpdateStatus(progressDCStart, string.Format("Querying Domain Controller: {0}", dcName), "Searching..."); - using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectClass=computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree)) + using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, "(objectCategory=Computer)", new string[] { "sAMAccountName", "lastLogon" }, SearchScope.Subtree)) { using (SearchResultCollection dResults = dSearcher.FindAll()) { @@ -238,7 +238,7 @@ namespace Disco.BI.Interop.ActiveDirectory } - foreach (Device d in context.Devices.Where(device => device.ComputerName != null)) + foreach (Device d in Database.Devices.Where(device => device.ComputerName != null)) { DateTime computerLastLogonDate; if (computerLastLogonDates.TryGetValue(d.ComputerName.ToUpper(), out computerLastLogonDate)) diff --git a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUserAccountExtensions.cs b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUserAccountExtensions.cs index 4b0bc303..d34e897c 100644 --- a/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUserAccountExtensions.cs +++ b/Disco.BI/BI/Interop/ActiveDirectory/ActiveDirectoryUserAccountExtensions.cs @@ -5,11 +5,6 @@ namespace Disco.BI.Interop.ActiveDirectory { internal static class ActiveDirectoryUserAccountExtensions { - public static bool HasRole(this ActiveDirectoryUserAccount account, string Role) - { - return account.Groups != null && account.Groups.Contains(Role.ToLower()); - } - public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0) { switch (PropertyName.ToLower()) @@ -17,11 +12,11 @@ namespace Disco.BI.Interop.ActiveDirectory case "name": return account.Name; case "samaccountname": - return account.sAMAccountName; + return account.SamAccountName; case "distinguishedname": return account.DistinguishedName; case "objectsid": - return account.ObjectSid; + return account.SecurityIdentifier; case "sn": return account.Surname; case "givenname": diff --git a/Disco.BI/BI/Interop/Community/UpdateCheck.cs b/Disco.BI/BI/Interop/Community/UpdateCheck.cs index 129adcad..6393006d 100644 --- a/Disco.BI/BI/Interop/Community/UpdateCheck.cs +++ b/Disco.BI/BI/Interop/Community/UpdateCheck.cs @@ -31,12 +31,12 @@ namespace Disco.BI.Interop.Community return string.Format("{0}.{1}.{2:0000}.{3:0000}", v.Major, v.Minor, v.Build, v.Revision); } - public static UpdateResponse Check(DiscoDataContext db, bool UseProxy, ScheduledTaskStatus status = null) + public static UpdateResponse Check(DiscoDataContext Database, bool UseProxy, ScheduledTaskStatus status = null) { if (status != null) status.UpdateStatus(10, "Building Update Request"); - var request = BuildRequest(db); + var request = BuildRequest(Database); //var requestJson = JsonConvert.SerializeObject(request); if (status != null) @@ -78,8 +78,8 @@ namespace Disco.BI.Interop.Community result = (UpdateResponse)xml.Deserialize(wResStream); } //var result = JsonConvert.DeserializeObject(responseContent); - db.DiscoConfiguration.UpdateLastCheck = result; - db.SaveChanges(); + Database.DiscoConfiguration.UpdateLastCheck = result; + Database.SaveChanges(); status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", result.Version)); @@ -94,23 +94,28 @@ namespace Disco.BI.Interop.Community } } - private static UpdateRequestV1 BuildRequest(DiscoDataContext db) + private static UpdateRequestV1 BuildRequest(DiscoDataContext Database) { var m = new UpdateRequestV1(); - m.DeploymentId = db.DiscoConfiguration.DeploymentId; + m.DeploymentId = Database.DiscoConfiguration.DeploymentId; m.CurrentDiscoVersion = CurrentDiscoVersionFormatted(); - m.OrganisationName = db.DiscoConfiguration.OrganisationName; + m.OrganisationName = Database.DiscoConfiguration.OrganisationName; m.BroadbandDoeWanId = GetBroadbandDoeWanId(); - m.BetaDeployment = db.DiscoConfiguration.UpdateBetaDeployment; + m.BetaDeployment = Database.DiscoConfiguration.UpdateBetaDeployment; - m.Stat_JobCounts = db.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); - m.Stat_OpenJobCounts = db.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + m.Stat_JobCounts = Database.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + m.Stat_OpenJobCounts = Database.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); var activeThreshold = DateTime.Now.AddDays(-60); - m.Stat_ActiveDeviceModelCounts = db.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList(); - m.Stat_UserCounts = db.Users.GroupBy(u => u.Type).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + m.Stat_ActiveDeviceModelCounts = Database.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList(); + m.Stat_UserCounts = new List() { + new UpdateRequestV1.Stat(){ + Key = "All Users", + Count = Database.Users.Count() + } + }; m.InstalledPlugins = Disco.Services.Plugins.Plugins.GetPlugins().Select(manifest => new Disco.Models.BI.Interop.Community.UpdateRequestV1.PluginRef { Id = manifest.Id, Version = manifest.VersionFormatted }).ToList(); diff --git a/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs b/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs index f5ba475c..e80035d3 100644 --- a/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs +++ b/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs @@ -53,7 +53,7 @@ namespace Disco.BI.Interop.Community } } - public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext dbContext) + public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext Database) { // Random time between midday and midnight. var rnd = new Random(); @@ -69,17 +69,17 @@ namespace Disco.BI.Interop.Community protected override void ExecuteTask() { - using (DiscoDataContext db = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { try { - UpdateCheck.Check(db, true, this.Status); + UpdateCheck.Check(database, true, this.Status); } catch (Exception ex) { ScheduledTasksLog.LogScheduledTaskException(this.Status.TaskName, this.Status.SessionId, this.Status.TaskType, ex); // Could be proxy error - try again without proxy: - UpdateCheck.Check(db, false, this.Status); + UpdateCheck.Check(database, false, this.Status); } } } diff --git a/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs b/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs index f2368369..7669e45b 100644 --- a/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs +++ b/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs @@ -12,13 +12,14 @@ using Disco.BI.Expressions; using System.Collections; using Disco.BI.Extensions; using Disco.Models.BI.Expressions; +using Disco.Services.Users; namespace Disco.BI.Interop.Pdf { public static class PdfGenerator { - public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) + public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) { if (DataObjects.Length > 0) { @@ -27,7 +28,7 @@ namespace Disco.BI.Interop.Pdf { foreach (object d in DataObjects) { - generatedPdfs.Add(dt.GeneratePdf(dbContext, d, CreatorUser, Timestamp, state, true)); + generatedPdfs.Add(dt.GeneratePdf(Database, d, CreatorUser, Timestamp, state, true)); state.SequenceNumber++; state.FlushScopeCache(); } @@ -47,24 +48,24 @@ namespace Disco.BI.Interop.Pdf return null; } - public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) + public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext Database, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) { object[] DataObjects; switch (dt.Scope) { case DocumentTemplate.DocumentTemplateScopes.Device: - DataObjects = dbContext.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray(); + DataObjects = Database.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray(); break; case DocumentTemplate.DocumentTemplateScopes.Job: int[] intDataObjectsIds = DataObjectsIds.Select(i => int.Parse(i)).ToArray(); - DataObjects = dbContext.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray(); + DataObjects = Database.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray(); break; case DocumentTemplate.DocumentTemplateScopes.User: DataObjects = new object[DataObjectsIds.Length]; for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++) { - DataObjects[idIndex] = UserBI.UserCache.GetUser(DataObjectsIds[idIndex], dbContext, true); + DataObjects[idIndex] = UserService.GetUser(DataObjectsIds[idIndex], Database, true); if (DataObjects[idIndex] == null) throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex])); } @@ -73,10 +74,10 @@ namespace Disco.BI.Interop.Pdf throw new InvalidOperationException("Invalid DocumentType Scope"); } - return GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); + return GenerateBulkFromTemplate(dt, Database, CreatorUser, Timestamp, DataObjects); } - public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) + public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext Database, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) { // Validate Data switch (dt.Scope) @@ -97,15 +98,15 @@ namespace Disco.BI.Interop.Pdf throw new InvalidOperationException("Invalid AttachmentType Scope"); } - dbContext.Configuration.LazyLoadingEnabled = true; + Database.Configuration.LazyLoadingEnabled = true; // Override FlattenFields if Document Template instructs. if (dt.FlattenForm) FlattenFields = true; - ConcurrentDictionary expressionCache = dt.PdfExpressionsFromCache(dbContext); + ConcurrentDictionary expressionCache = dt.PdfExpressionsFromCache(Database); - string templateFilename = dt.RepositoryFilename(dbContext); + string templateFilename = dt.RepositoryFilename(Database); PdfReader pdfReader = new PdfReader(templateFilename); MemoryStream pdfGeneratedStream = new MemoryStream(); @@ -114,7 +115,7 @@ namespace Disco.BI.Interop.Pdf pdfStamper.FormFlattening = FlattenFields; pdfStamper.Writer.CloseStream = false; - IDictionary expressionVariables = Expression.StandardVariables(dt, dbContext, CreatorUser, TimeStamp, State); + IDictionary expressionVariables = Expression.StandardVariables(dt, Database, CreatorUser, TimeStamp, State); foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys) { @@ -240,7 +241,7 @@ namespace Disco.BI.Interop.Pdf Timestamp = DateTime.Now }; jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id); - dbContext.JobLogs.Add(jl); + Database.JobLogs.Add(jl); } pdfGeneratedStream.Position = 0; diff --git a/Disco.BI/BI/Interop/Pdf/PdfImporter.cs b/Disco.BI/BI/Interop/Pdf/PdfImporter.cs index ca9ea4cd..6f196766 100644 --- a/Disco.BI/BI/Interop/Pdf/PdfImporter.cs +++ b/Disco.BI/BI/Interop/Pdf/PdfImporter.cs @@ -205,7 +205,7 @@ namespace Disco.BI.Interop.Pdf return null; } - private static DetectImageResult DetectImage(DiscoDataContext dbContext, Bitmap pageImageOriginal, string SessionId, IEnumerable detectDocumentTemplates, DetectStateHints StateHints) + private static DetectImageResult DetectImage(DiscoDataContext Database, Bitmap pageImageOriginal, string SessionId, IEnumerable detectDocumentTemplates, DetectStateHints StateHints) { Bitmap pageImage = pageImageOriginal; double pageImageModifiedScale = 1; @@ -270,7 +270,7 @@ namespace Disco.BI.Interop.Pdf { foreach (DocumentTemplate dt in detectDocumentTemplates) { - var locationBag = dt.QRCodeLocations(dbContext); + var locationBag = dt.QRCodeLocations(Database); foreach (var location in locationBag) { result = DetectImageFromSegment(pageImage, zxingMfr, zxingMfrHints, @@ -303,7 +303,7 @@ namespace Disco.BI.Interop.Pdf } } - private static DetectPageResult DetectPage(DiscoDataContext dbContext, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable detectDocumentTemplates, DetectStateHints StateHints) + private static DetectPageResult DetectPage(DiscoDataContext Database, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable detectDocumentTemplates, DetectStateHints StateHints) { DetectPageResult result = new DetectPageResult() { PageNumber = PageNumber }; @@ -325,7 +325,7 @@ namespace Disco.BI.Interop.Pdf { DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, (int)(10 + (pageProgressInterval * pageImages.IndexOf(pageImageOriginal))), String.Format("Processing Page Image {0} of {1}", pageImages.IndexOf(pageImageOriginal) + 1, pageImages.Count)); - using (var zxingResult = DetectImage(dbContext, pageImageOriginal, SessionId, detectDocumentTemplates, StateHints)) + using (var zxingResult = DetectImage(Database, pageImageOriginal, SessionId, detectDocumentTemplates, StateHints)) { if (zxingResult != null) { @@ -377,9 +377,9 @@ namespace Disco.BI.Interop.Pdf } } - public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string SessionId, Cache HttpCache) + public static bool ProcessPdfAttachment(string Filename, DiscoDataContext Database, string SessionId, Cache HttpCache) { - var dataStoreUnassignedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); + var dataStoreUnassignedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned"); DocumentImporterLog.LogImportProgress(SessionId, 0, "Reading File"); @@ -389,8 +389,8 @@ namespace Disco.BI.Interop.Pdf var pdfPagesAssigned = new Dictionary>(); - var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); - var detectDocumentTemplates = dbContext.DocumentTemplates.ToArray(); + var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages"); + var detectDocumentTemplates = Database.DocumentTemplates.ToArray(); double progressInterval = 70 / pdfReader.NumberOfPages; @@ -401,14 +401,14 @@ namespace Disco.BI.Interop.Pdf DocumentImporterLog.LogImportProgress(SessionId, (int)(PageNumber * progressInterval), string.Format("Processing Page {0} of {1}", PageNumber, pdfReader.NumberOfPages)); DocumentImporterLog.LogImportPageStarting(SessionId, PageNumber); - using (var pageResult = DetectPage(dbContext, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates, detectStateHints)) + using (var pageResult = DetectPage(Database, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates, detectStateHints)) { if (pageResult.DetectedIdentifier != null) { var docId = pageResult.DetectedIdentifier; pdfPagesAssigned.Add(PageNumber, new Tuple(docId, pageResult.AttachmentThumbnailImage.ToArray())); - docId.LoadComponents(dbContext); + docId.LoadComponents(Database); DocumentImporterLog.LogImportPageDetected(SessionId, PageNumber, docId.DocumentUniqueId, docId.DocumentTemplate.Description, docId.DocumentTemplate.Scope, docId.DataId, docId.DataDescription); } else @@ -441,7 +441,7 @@ namespace Disco.BI.Interop.Pdf var documentPortionIdentifier = documentPortionInfo.Item1; var documentPortionThumbnail = documentPortionInfo.Item2; - if (!documentPortionIdentifier.LoadComponents(dbContext)) + if (!documentPortionIdentifier.LoadComponents(Database)) { // Unknown Document Unique Id foreach (var dp in documentPortion) @@ -477,7 +477,7 @@ namespace Disco.BI.Interop.Pdf msBuilder.Position = 0; - var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(dbContext, msBuilder, documentPortionThumbnail); + var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(Database, msBuilder, documentPortionThumbnail); if (!attachmentSuccess) { // Unable to add Attachment @@ -538,13 +538,13 @@ namespace Disco.BI.Interop.Pdf return true; } - public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp) + public static bool ProcessPdfAttachment(string Filename, DiscoDataContext Database, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp) { using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { DocumentUniqueIdentifier identifier = new DocumentUniqueIdentifier(DocumentTemplateId, DataId, UserId, Timestamp); - identifier.LoadComponents(dbContext); - return identifier.ImportPdfAttachment(dbContext, fs, null); + identifier.LoadComponents(Database); + return identifier.ImportPdfAttachment(Database, fs, null); } } diff --git a/Disco.BI/BI/Interop/PluginServices/IDiscoScheduledTask.cs b/Disco.BI/BI/Interop/PluginServices/IDiscoScheduledTask.cs deleted file mode 100644 index 0f5916c3..00000000 --- a/Disco.BI/BI/Interop/PluginServices/IDiscoScheduledTask.cs +++ /dev/null @@ -1,14 +0,0 @@ -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Text; -//using Disco.Data.Repository; -//using Quartz; - -//namespace Disco.BI.Interop.PluginServices -//{ -// interface IDiscoScheduledTask -// { -// void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler); -// } -//} diff --git a/Disco.BI/BI/Interop/PluginServices/Utilities.cs b/Disco.BI/BI/Interop/PluginServices/Utilities.cs deleted file mode 100644 index 14a8d9b4..00000000 --- a/Disco.BI/BI/Interop/PluginServices/Utilities.cs +++ /dev/null @@ -1,45 +0,0 @@ -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Text; -//using Disco.Data.Repository; -//using Quartz; - -//namespace Disco.BI.Interop.PluginServices -//{ -// public static class Utilities -// { - -// public static void InitalizeScheduledTasks(DiscoDataContext dbContext, ISchedulerFactory SchedulerFactory) -// { - -// var scheduler = SchedulerFactory.GetScheduler(); - -// // Discover IDiscoScheduledTasks (Only from Disco Assemblies) -// var appDomain = AppDomain.CurrentDomain; - -// var scheduledTaskTypes = (from a in appDomain.GetAssemblies() -// where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase) -// from type in a.GetTypes() -// where typeof(IDiscoScheduledTask).IsAssignableFrom(type) && !type.IsAbstract -// select type); -// foreach (Type scheduledTaskType in scheduledTaskTypes) -// { -// IDiscoScheduledTask instance = (IDiscoScheduledTask)Activator.CreateInstance(scheduledTaskType); -// try -// { -// instance.InitalizeScheduledTask(dbContext, scheduler); -// } -// catch (Exception ex) -// { -// if (instance == null) -// Logging.SystemLog.LogException("Initializing Scheduled Task; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", ex); -// else -// Logging.SystemLog.LogException(string.Format("Initializing Scheduled Task: '{0}'; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", instance.GetType().Name), ex); -// } -// } - -// } - -// } -//} diff --git a/Disco.BI/BI/Interop/SignalRHandlers/AdminAuthorizedPersistentConnection.cs b/Disco.BI/BI/Interop/SignalRHandlers/AdminAuthorizedPersistentConnection.cs deleted file mode 100644 index 85c082f9..00000000 --- a/Disco.BI/BI/Interop/SignalRHandlers/AdminAuthorizedPersistentConnection.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Disco.Models.Repository; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Disco.BI.Interop.SignalRHandlers -{ - public class AdminAuthorizedPersistentConnection : AuthorizedPersistentConnection - { - private string[] authorizedUserTypes = { User.Types.Admin }; - - protected override string[] AuthorizedUserTypes { get { return authorizedUserTypes; } } - } -} \ No newline at end of file diff --git a/Disco.BI/BI/Interop/SignalRHandlers/AuthorizedPersistentConnection.cs b/Disco.BI/BI/Interop/SignalRHandlers/AuthorizedPersistentConnection.cs index 6d32d41f..4ced4fba 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/AuthorizedPersistentConnection.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/AuthorizedPersistentConnection.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNet.SignalR; +using Disco.Services.Users; +using Microsoft.AspNet.SignalR; using System; using System.Collections.Generic; using System.Linq; @@ -9,9 +10,9 @@ namespace Disco.BI.Interop.SignalRHandlers { public class AuthorizedPersistentConnection : PersistentConnection { - private string[] authorizedUserTypes = null; + private string authorizedClaim = null; - protected virtual string[] AuthorizedUserTypes { get { return authorizedUserTypes; } } + protected virtual string AuthorizedClaim { get { return authorizedClaim; } } protected override bool AuthorizeRequest(IRequest request) { @@ -19,17 +20,15 @@ namespace Disco.BI.Interop.SignalRHandlers return false; else { - var user = UserBI.UserCache.CurrentUser; - if (user == null) - return false; + var authToken = UserService.CurrentAuthorization; + + if (authToken == null) + return false; // No Current User - if (AuthorizedUserTypes == null || AuthorizedUserTypes.Length == 0) - return true; - - if (AuthorizedUserTypes.Contains(user.Type)) - return true; - - return false; + if (authorizedClaim == null) + return true; // Just Authenticate - no Authorization + else + return authToken.Has(authorizedClaim); } } } diff --git a/Disco.BI/BI/Interop/SignalRHandlers/HeldDeviceNotifications.cs b/Disco.BI/BI/Interop/SignalRHandlers/HeldDeviceNotifications.cs index 566a2ce8..31233dbb 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/HeldDeviceNotifications.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/HeldDeviceNotifications.cs @@ -61,7 +61,7 @@ namespace Disco.BI.Interop.SignalRHandlers { User u = (User)e.Entity; - var userDevices = e.dbContext.Devices.Where(d => d.AssignedUserId == u.Id); + var userDevices = e.Database.Devices.Where(d => d.AssignedUserId == u.Id); foreach (var userDevice in userDevices) { diff --git a/Disco.BI/BI/Interop/SignalRHandlers/LogNotifications.cs b/Disco.BI/BI/Interop/SignalRHandlers/LogNotifications.cs index 2c297851..29f1dc50 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/LogNotifications.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/LogNotifications.cs @@ -1,4 +1,5 @@ -using Disco.Services.Logging; +using Disco.Services.Authorization; +using Disco.Services.Logging; using Disco.Services.Logging.Models; using Microsoft.AspNet.SignalR; using System; @@ -9,10 +10,12 @@ using System.Threading.Tasks; namespace Disco.BI.Interop.SignalRHandlers { - public class LogNotifications : AdminAuthorizedPersistentConnection + public class LogNotifications : AuthorizedPersistentConnection { public static bool initialized = false; + protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } } + public LogNotifications() { if (!initialized) diff --git a/Disco.BI/BI/Interop/SignalRHandlers/RepositoryMonitorNotifications.cs b/Disco.BI/BI/Interop/SignalRHandlers/RepositoryMonitorNotifications.cs index e50742d9..57635705 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/RepositoryMonitorNotifications.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/RepositoryMonitorNotifications.cs @@ -1,4 +1,5 @@ using Disco.Data.Repository.Monitor; +using Disco.Services.Authorization; using Microsoft.AspNet.SignalR; using System; using System.Collections.Generic; @@ -8,8 +9,10 @@ using System.Threading.Tasks; namespace Disco.BI.Interop.SignalRHandlers { - public class RepositoryMonitorNotifications : AdminAuthorizedPersistentConnection + public class RepositoryMonitorNotifications : AuthorizedPersistentConnection { + protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } } + public static void Initialize() { RepositoryMonitor.StreamAfterCommit.Subscribe(AfterCommit); diff --git a/Disco.BI/BI/Interop/SignalRHandlers/ScheduledTasksStatusNotifications.cs b/Disco.BI/BI/Interop/SignalRHandlers/ScheduledTasksStatusNotifications.cs index 45389d75..9de3b197 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/ScheduledTasksStatusNotifications.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/ScheduledTasksStatusNotifications.cs @@ -1,4 +1,5 @@ -using Disco.Services.Tasks; +using Disco.Services.Authorization; +using Disco.Services.Tasks; using Microsoft.AspNet.SignalR; using System; using System.Collections.Generic; @@ -8,10 +9,12 @@ using System.Threading.Tasks; namespace Disco.BI.Interop.SignalRHandlers { - public class ScheduledTasksStatusNotifications : AdminAuthorizedPersistentConnection + public class ScheduledTasksStatusNotifications : AuthorizedPersistentConnection { public static bool initialized = false; + protected override string AuthorizedClaim { get { return Claims.DiscoAdminAccount; } } + public ScheduledTasksStatusNotifications() { if (!initialized) diff --git a/Disco.BI/BI/Interop/SignalRHandlers/UserHeldDeviceNotifications.cs b/Disco.BI/BI/Interop/SignalRHandlers/UserHeldDeviceNotifications.cs index a45d036f..6fd9a990 100644 --- a/Disco.BI/BI/Interop/SignalRHandlers/UserHeldDeviceNotifications.cs +++ b/Disco.BI/BI/Interop/SignalRHandlers/UserHeldDeviceNotifications.cs @@ -48,7 +48,7 @@ namespace Disco.BI.Interop.SignalRHandlers if (j.DeviceSerialNumber != null) { - var jobDevice = e.dbContext.Devices.Where(d => d.SerialNumber == j.DeviceSerialNumber).FirstOrDefault(); + var jobDevice = e.Database.Devices.Where(d => d.SerialNumber == j.DeviceSerialNumber).FirstOrDefault(); if (jobDevice.AssignedUserId != null) notificationContext.Connection.Broadcast(jobDevice.AssignedUserId); diff --git a/Disco.BI/BI/JobBI/ManagedJobList.cs b/Disco.BI/BI/JobBI/ManagedJobList.cs index 606b2fac..aed5e35f 100644 --- a/Disco.BI/BI/JobBI/ManagedJobList.cs +++ b/Disco.BI/BI/JobBI/ManagedJobList.cs @@ -9,6 +9,7 @@ using System.Text; using System.Threading.Tasks; using Disco.BI.Extensions; using System.Reactive.Linq; +using Disco.Services.Users; namespace Disco.BI.JobBI { @@ -20,10 +21,22 @@ namespace Disco.BI.JobBI private IDisposable unsubscribeToken; private object updateLock = new object(); - public ManagedJobList Initialize(DiscoDataContext dbContext) + public override List Items + { + get + { + return base.Items.PermissionsFiltered(UserService.CurrentAuthorization); + } + set + { + throw new InvalidOperationException("Items cannot be manually set in a Managed Job List"); + } + } + + public ManagedJobList Initialize(DiscoDataContext Database) { // Initially fill table - this.Items = this.SortFunction(this.DetermineItems(dbContext, this.FilterFunction(dbContext.Jobs))).ToList(); + base.Items = this.SortFunction(this.DetermineItems(Database, this.FilterFunction(Database.Jobs))).ToList(); // Subscribe for Changes // - Job (or Job Meta) Changes @@ -65,19 +78,19 @@ namespace Disco.BI.JobBI if (e.EntityType == typeof(DeviceProfile)) { int deviceProfileId = ((DeviceProfile)e.Entity).Id; - existingItems = this.Items.Where(i => i.DeviceProfileId == deviceProfileId).ToArray(); + existingItems = base.Items.Where(i => i.DeviceProfileId == deviceProfileId).ToArray(); } else if (e.EntityType == typeof(DeviceModel)) { int deviceModelId = ((DeviceModel)e.Entity).Id; - existingItems = this.Items.Where(i => i.DeviceModelId == deviceModelId).ToArray(); + existingItems = base.Items.Where(i => i.DeviceModelId == deviceModelId).ToArray(); } else if (e.EntityType == typeof(Device)) { string deviceSerialNumber = ((Device)e.Entity).SerialNumber; - existingItems = this.Items.Where(i => i.DeviceSerialNumber == deviceSerialNumber).ToArray(); + existingItems = base.Items.Where(i => i.DeviceSerialNumber == deviceSerialNumber).ToArray(); } else return; // Subscription should never reach @@ -93,20 +106,20 @@ namespace Disco.BI.JobBI if (jobIds.Count == 0) return; else - UpdateJobs(e.dbContext, jobIds, existingItems); + UpdateJobs(e.Database, jobIds, existingItems); } - private void UpdateJobs(DiscoDataContext dbContext, List jobIds, JobTableItemModel[] existingItems = null) + private void UpdateJobs(DiscoDataContext Database, List jobIds, JobTableItemModel[] existingItems = null) { lock (updateLock) { // Check for existing items, if not handed them if (existingItems == null) - existingItems = this.Items.Where(i => jobIds.Contains(i.Id)).ToArray(); + existingItems = base.Items.Where(i => jobIds.Contains(i.Id)).ToArray(); + + var updatedItems = this.DetermineItems(Database, this.FilterFunction(Database.Jobs.Where(j => jobIds.Contains(j.Id)))); - var updatedItems = this.DetermineItems(dbContext, this.FilterFunction(dbContext.Jobs.Where(j => jobIds.Contains(j.Id)))); - - var refreshedList = this.Items.ToList(); + var refreshedList = base.Items.ToList(); // Remove Existing if (existingItems.Length > 0) @@ -119,7 +132,7 @@ namespace Disco.BI.JobBI refreshedList.Add(updatedItem); // Reorder - this.Items = this.SortFunction(refreshedList).ToList(); + base.Items = this.SortFunction(refreshedList).ToList(); } } diff --git a/Disco.BI/BI/JobBI/Searching.cs b/Disco.BI/BI/JobBI/Searching.cs index 85cfc78f..6b6ecf9c 100644 --- a/Disco.BI/BI/JobBI/Searching.cs +++ b/Disco.BI/BI/JobBI/Searching.cs @@ -11,7 +11,7 @@ namespace Disco.BI.JobBI { public static class Searching { - public static JobTableModel Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false) + public static JobTableModel Search(DiscoDataContext Database, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false) { int termInt = default(int); @@ -22,7 +22,7 @@ namespace Disco.BI.JobBI // Term is a Number (int) if (SearchDetails) { - query = BuildJobTableModel(dbContext).Where(j => + query = BuildJobTableModel(Database).Where(j => j.Id == termInt || j.DeviceHeldLocation.Contains(Term) || j.Device.SerialNumber.Contains(Term) || @@ -36,7 +36,7 @@ namespace Disco.BI.JobBI } else { - query = BuildJobTableModel(dbContext).Where(j => + query = BuildJobTableModel(Database).Where(j => j.Id == termInt || j.DeviceHeldLocation.Contains(Term) || j.Device.SerialNumber.Contains(Term) || @@ -51,7 +51,7 @@ namespace Disco.BI.JobBI { if (SearchDetails) { - query = BuildJobTableModel(dbContext).Where(j => + query = BuildJobTableModel(Database).Where(j => j.DeviceHeldLocation.Contains(Term) || j.Device.SerialNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) || @@ -64,7 +64,7 @@ namespace Disco.BI.JobBI } else { - query = BuildJobTableModel(dbContext).Where(j => + query = BuildJobTableModel(Database).Where(j => j.DeviceHeldLocation.Contains(Term) || j.Device.SerialNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) || @@ -79,14 +79,14 @@ namespace Disco.BI.JobBI query = query.Take(LimitCount.Value); JobTableModel model = new JobTableModel() { ShowStatus = IncludeJobStatus }; - model.Fill(dbContext, query); + model.Fill(Database, query); return model; } - public static IQueryable BuildJobTableModel(DiscoDataContext dbContext) + public static IQueryable BuildJobTableModel(DiscoDataContext Database) { - return dbContext.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser"); + return Database.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser"); } } diff --git a/Disco.BI/BI/JobBI/Statistics/DailyOpenedClosed.cs b/Disco.BI/BI/JobBI/Statistics/DailyOpenedClosed.cs index 7c37a845..1a90d4b2 100644 --- a/Disco.BI/BI/JobBI/Statistics/DailyOpenedClosed.cs +++ b/Disco.BI/BI/JobBI/Statistics/DailyOpenedClosed.cs @@ -25,7 +25,7 @@ namespace Disco.BI.JobBI.Statistics public override bool SingleInstanceTask { get { return true; } } public override bool CancelInitiallySupported { get { return false; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Trigger Daily @ 12:29am TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)); @@ -34,40 +34,13 @@ namespace Disco.BI.JobBI.Statistics } protected override void ExecuteTask() { - using (var dbContext = new DiscoDataContext()) + using (var database = new DiscoDataContext()) { - UpdateDataHistory(dbContext, true); + UpdateDataHistory(database, true); } } - //public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler) - //{ - // // Run @ 12:29am - // IJobDetail jobDetail = new JobDetailImpl("JobStatisticsDailyOpenedClosed", typeof(DailyOpenedClosed)); - // ITrigger trigger = TriggerBuilder.Create(). - // WithIdentity("JobStatisticsDailyOpenedClosedTrigger"). - // StartNow(). - // WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)). - // Build(); - // Scheduler.ScheduleJob(jobDetail, trigger); - //} - - //public void Execute(IJobExecutionContext context) - //{ - // try - // { - // using (var dbContext = new DiscoDataContext()) - // { - // UpdateDataHistory(dbContext, true); - // } - // } - // catch (Exception ex) - // { - // Logging.SystemLog.LogException("Disco.BI.JobBI.Statistics.DailyOpenedClosed", ex); - // } - //} - - private static void UpdateDataHistory(DiscoDataContext dbContext, bool Refresh = false) + private static void UpdateDataHistory(DiscoDataContext Database, bool Refresh = false) { DateTime historyEnd = DateTime.Now.Date; @@ -98,7 +71,7 @@ namespace Disco.BI.JobBI.Statistics // Cache Data while (processDate <= historyEnd) { - resultData.Add(Data(dbContext, processDate)); + resultData.Add(Data(Database, processDate)); processDate = processDate.AddDays(1); } _data = resultData; @@ -162,14 +135,14 @@ namespace Disco.BI.JobBI.Statistics } } - private static DailyOpenedClosedItem Data(DiscoDataContext dbContext, DateTime ProcessDate) + private static DailyOpenedClosedItem Data(DiscoDataContext Database, DateTime ProcessDate) { DateTime processDateStart = ProcessDate; DateTime processDateEnd = ProcessDate.AddDays(1); - int totalJobs = dbContext.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count(); - int openedJobs = dbContext.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count(); - int closedJobs = dbContext.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count(); + int totalJobs = Database.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count(); + int openedJobs = Database.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count(); + int closedJobs = Database.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count(); return new DailyOpenedClosedItem() { @@ -180,11 +153,11 @@ namespace Disco.BI.JobBI.Statistics }; } - public static List Data(DiscoDataContext dbContext, bool FilterUnimportantWeekends = false) + public static List Data(DiscoDataContext Database, bool FilterUnimportantWeekends = false) { List resultData; - UpdateDataHistory(dbContext); + UpdateDataHistory(Database); if (FilterUnimportantWeekends) resultData = _data.Where(i => (i.Timestamp.DayOfWeek != DayOfWeek.Saturday && i.Timestamp.DayOfWeek != DayOfWeek.Sunday) || @@ -192,9 +165,6 @@ namespace Disco.BI.JobBI.Statistics else resultData = _data.ToList(); - // Removed - Live Updated via Repository Monitor; See: RepositoryEvent_JobChange - //resultData.Add(Data(dbContext, DateTime.Today)); - return resultData; } } diff --git a/Disco.BI/BI/JobBI/Utilities.cs b/Disco.BI/BI/JobBI/Utilities.cs index 52cb983d..f043e825 100644 --- a/Disco.BI/BI/JobBI/Utilities.cs +++ b/Disco.BI/BI/JobBI/Utilities.cs @@ -10,7 +10,7 @@ namespace Disco.BI.JobBI { public static class Utilities { - public static Job Create(DiscoDataContext dbContext, Device device, User user, JobType type, List subTypes, User initialTech) + public static Job Create(DiscoDataContext Database, Device device, User user, JobType type, List subTypes, User initialTech) { Job j = new Job() { @@ -38,19 +38,19 @@ namespace Disco.BI.JobBI List jobSubTypes = subTypes.ToList(); j.JobSubTypes = jobSubTypes; - dbContext.Jobs.Add(j); + Database.Jobs.Add(j); switch (type.Id) { case JobType.JobTypeIds.HWar: - dbContext.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j }); + Database.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j }); break; case JobType.JobTypeIds.HNWar: - dbContext.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j }); + Database.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j }); if (device != null) { // Add Job Components - var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); + var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var addedComponents = new List(); foreach (var c in components) { @@ -76,7 +76,7 @@ namespace Disco.BI.JobBI } } foreach (var c in addedComponents) - dbContext.JobComponents.Add(new JobComponent() + Database.JobComponents.Add(new JobComponent() { Job = j, TechUserId = initialTech.Id, diff --git a/Disco.BI/BI/UserBI/Searching.cs b/Disco.BI/BI/UserBI/Searching.cs index 096792d5..e4d80794 100644 --- a/Disco.BI/BI/UserBI/Searching.cs +++ b/Disco.BI/BI/UserBI/Searching.cs @@ -5,6 +5,7 @@ using System.Text; using Disco.Models.BI.Search; using Disco.Models.Repository; using Disco.Data.Repository; +using Disco.Services.Users; namespace Disco.BI.UserBI { @@ -32,7 +33,7 @@ namespace Disco.BI.UserBI }).ToList(); } - public static List Search(DiscoDataContext dbContext, string Term, int? LimitCount = null) + public static List Search(DiscoDataContext Database, string Term, int? LimitCount = null) { if (string.IsNullOrWhiteSpace(Term) || Term.Length < 2) throw new ArgumentException("Search Term must contain at least two characters", "Term"); @@ -41,16 +42,16 @@ namespace Disco.BI.UserBI var adImportedUsers = Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser()); foreach (var adU in adImportedUsers) { - var existingUser = dbContext.Users.Find(adU.Id); + var existingUser = Database.Users.Find(adU.Id); if (existingUser != null) existingUser.UpdateSelf(adU); else - dbContext.Users.Add(adU); - dbContext.SaveChanges(); - UserCache.InvalidateValue(adU.Id); + Database.Users.Add(adU); + Database.SaveChanges(); + UserService.InvalidateCachedUser(adU.Id); } - return Search_SelectUserSearchResultItems(dbContext.Users.Where(u => + return Search_SelectUserSearchResultItems(Database.Users.Where(u => u.Id.Contains(Term) || u.Surname.Contains(Term) || u.GivenName.Contains(Term) || diff --git a/Disco.BI/BI/UserBI/UserCache.cs b/Disco.BI/BI/UserBI/UserCache.cs deleted file mode 100644 index 2339ef81..00000000 --- a/Disco.BI/BI/UserBI/UserCache.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Collections.Concurrent; -using Disco.Models.Repository; -using Disco.Data.Repository; -using System.Web; -using Quartz; -using Quartz.Impl; -using Disco.Services.Tasks; - -namespace Disco.BI.UserBI -{ - public class UserCache - { - private static ConcurrentDictionary> _Cache = new ConcurrentDictionary>(); - private const long CacheTimeoutTicks = 6000000000; // 10 Minutes - private const string CacheHttpRequestKey = "Disco_CurrentUser"; - - public static User CurrentUser - { - get - { - string username = null; - User user; - - // Check for ASP.NET - if (HttpContext.Current != null) - { - if (HttpContext.Current.Request.IsAuthenticated) - { - user = (User)HttpContext.Current.Items[CacheHttpRequestKey]; - if (user != null) - return user; - - username = HttpContext.Current.User.Identity.Name; - } - else - { - return null; - //throw new PlatformNotSupportedException("ASP.NET Authentication is not correctly configured"); - } - } - - // User default User - if (username == null) - { - username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; - } - - user = GetUser(username); - - if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) - { - // Cache in current request - HttpContext.Current.Items[CacheHttpRequestKey] = user; - } - - return user; - } - } - - public static User GetUser(string Username) - { - // Check Cache - User u = TryUserCache(Username); - - if (u == null) - { - // Load from Repository - using (DiscoDataContext dbContext = new DiscoDataContext()) - { - u = GetUser(Username, dbContext, true); - } - } - return u; - } - - public static User GetUser(string Username, DiscoDataContext dbContext, bool ForceRefresh = false) - { - User u = null; - - // Check Cache - if (!ForceRefresh) - u = TryUserCache(Username); - - if (u == null) - { - string username = Username.ToLower(); - u = UserBI.Utilities.LoadUser(dbContext, username); - SetValue(username, u); - } - return u; - } - - private static User TryUserCache(string Username) - { - string username = Username.ToLower(); - Tuple userRecord; - if (_Cache.TryGetValue(username, out userRecord)) - { - if (userRecord.Item2 > DateTime.Now) - return userRecord.Item1; - else - _Cache.TryRemove(username, out userRecord); - } - return null; - } - - public static bool InvalidateValue(string Key) - { - Tuple userRecord; - return _Cache.TryRemove(Key.ToLower(), out userRecord); - } - - private static bool SetValue(string Key, User User) - { - string key = Key.ToLower(); - Tuple userRecord = new Tuple(User, DateTime.Now.AddTicks(CacheTimeoutTicks)); - if (_Cache.ContainsKey(key)) - { - Tuple oldUser; - if (_Cache.TryGetValue(key, out oldUser)) - { - return _Cache.TryUpdate(key, userRecord, oldUser); - } - } - return _Cache.TryAdd(key, userRecord); - } - - internal static void CleanStaleCache() - { - var usernames = _Cache.Keys.ToArray(); - foreach (string username in usernames) - { - Tuple userRecord; - if (_Cache.TryGetValue(username, out userRecord)) - { - if (userRecord.Item2 <= DateTime.Now) - _Cache.TryRemove(username, out userRecord); - } - } - } - } -} diff --git a/Disco.BI/BI/UserBI/Utilities.cs b/Disco.BI/BI/UserBI/Utilities.cs deleted file mode 100644 index a5ba7e15..00000000 --- a/Disco.BI/BI/UserBI/Utilities.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Disco.Models.Repository; -using Disco.Data.Repository; -using Disco.Models.BI.Search; -using System.Runtime.InteropServices; -using System.DirectoryServices.ActiveDirectory; -using Disco.Services.Logging; - -namespace Disco.BI.UserBI -{ - public static class Utilities - { - - public static User LoadUser(DiscoDataContext dbContext, string Username) - { - // Machine Account ? - if (Username.EndsWith("$")) - { - return Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(Username).ToRepositoryUser(); - } - - // User Account - User user = null; - try - { - var ADUser = Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(Username); - if (ADUser == null) - throw new ArgumentException(string.Format("Invalid Username: '{0}'", Username), "Username"); - user = ADUser.ToRepositoryUser(); - } - catch (COMException ex) - { - // If "Server is not operational" then Try Cache - if (ex.ErrorCode != -2147016646) - { - throw ex; - } - SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex); - } - catch (ActiveDirectoryOperationException ex) - { - // Try From Cache... - SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex); - } - - // Update Repository - User existingUser; - if (user == null) - { - string username = Username.Contains(@"\") ? Username.Substring(Username.IndexOf(@"\") + 1) : Username; - existingUser = dbContext.Users.Find(username); - if (existingUser == null) - throw new ArgumentException(string.Format("Invalid User - Not In Disco DB: '{0}'", Username), "Username"); - else - return existingUser; - } - existingUser = dbContext.Users.Find(user.Id); - if (existingUser == null) - { - dbContext.Users.Add(user); - } - else - { - existingUser.UpdateSelf(user); - user = existingUser; - } - dbContext.SaveChanges(); - - return user; - } - - } -} diff --git a/Disco.BI/Disco.BI.csproj b/Disco.BI/Disco.BI.csproj index 374e9ee2..c654d758 100644 --- a/Disco.BI/Disco.BI.csproj +++ b/Disco.BI/Disco.BI.csproj @@ -143,6 +143,7 @@ + @@ -175,6 +176,7 @@ + @@ -186,9 +188,6 @@ - - - @@ -201,9 +200,6 @@ - - - diff --git a/Disco.BI/Properties/AssemblyInfo.cs b/Disco.BI/Properties/AssemblyInfo.cs index f5598df3..949b9e72 100644 --- a/Disco.BI/Properties/AssemblyInfo.cs +++ b/Disco.BI/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2249")] -[assembly: AssemblyFileVersion("1.2.0725.2249")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1541")] +[assembly: AssemblyFileVersion("1.2.1001.1541")] \ No newline at end of file diff --git a/Disco.Client/Program.cs b/Disco.Client/Program.cs index 8bb62bab..05908f6c 100644 --- a/Disco.Client/Program.cs +++ b/Disco.Client/Program.cs @@ -44,7 +44,7 @@ namespace Disco.Client // Ignore Local Proxies WebRequest.DefaultWebProxy = new WebProxy(); - // Override Http 100 Continue Behavour + // Override Http 100 Continue Behaviour ServicePointManager.Expect100Continue = false; // Assume success unless otherwise notified diff --git a/Disco.Client/Properties/AssemblyInfo.cs b/Disco.Client/Properties/AssemblyInfo.cs index 75379e8e..69efccad 100644 --- a/Disco.Client/Properties/AssemblyInfo.cs +++ b/Disco.Client/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2102")] -[assembly: AssemblyFileVersion("1.2.0725.2102")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1300")] +[assembly: AssemblyFileVersion("1.2.1001.1300")] \ No newline at end of file diff --git a/Disco.ClientBootstrapper/Properties/AssemblyInfo.cs b/Disco.ClientBootstrapper/Properties/AssemblyInfo.cs index fb6252c0..dc237ce2 100644 --- a/Disco.ClientBootstrapper/Properties/AssemblyInfo.cs +++ b/Disco.ClientBootstrapper/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2102")] -[assembly: AssemblyFileVersion("1.2.0725.2102")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1300")] +[assembly: AssemblyFileVersion("1.2.1001.1300")] \ No newline at end of file diff --git a/Disco.Data/Configuration/ConfigurationBase.cs b/Disco.Data/Configuration/ConfigurationBase.cs index 03aed9af..3e42cc49 100644 --- a/Disco.Data/Configuration/ConfigurationBase.cs +++ b/Disco.Data/Configuration/ConfigurationBase.cs @@ -11,30 +11,30 @@ namespace Disco.Data.Configuration { public abstract class ConfigurationBase { - private DiscoDataContext dbContext; + private DiscoDataContext Database; public abstract string Scope { get; } - public ConfigurationBase(DiscoDataContext dbContext) + public ConfigurationBase(DiscoDataContext Database) { - this.dbContext = dbContext; + this.Database = Database; } protected List Items { get { - return ConfigurationCache.GetConfigurationItems(dbContext, this.Scope); + return ConfigurationCache.GetConfigurationItems(Database, this.Scope); } } private void SetValue(string Key, ValueType Value) { - ConfigurationCache.SetConfigurationValue(dbContext, this.Scope, Key, Value); + ConfigurationCache.SetConfigurationValue(Database, this.Scope, Key, Value); } private ValueType GetValue(string Key, ValueType Default) { - return ConfigurationCache.GetConfigurationValue(dbContext, this.Scope, Key, Default); + return ConfigurationCache.GetConfigurationValue(Database, this.Scope, Key, Default); } protected void Set(ValueType Value, [CallerMemberName] string Key = null) diff --git a/Disco.Data/Configuration/ConfigurationCache.cs b/Disco.Data/Configuration/ConfigurationCache.cs index 29dcf782..0810b086 100644 --- a/Disco.Data/Configuration/ConfigurationCache.cs +++ b/Disco.Data/Configuration/ConfigurationCache.cs @@ -16,7 +16,7 @@ namespace Disco.Data.Configuration private static List configurationItems = new List(); private static object configurationItemsLock = new object(); - private static void LoadConfigurationItems(DiscoDataContext dbContext, string Scope, bool Reload) + private static void LoadConfigurationItems(DiscoDataContext Database, string Scope, bool Reload) { if (Reload || !configDictionary.ContainsKey(Scope)) { @@ -24,10 +24,10 @@ namespace Disco.Data.Configuration { if (Reload || !configDictionary.ContainsKey(Scope)) { - if (dbContext == null) + if (Database == null) throw new InvalidOperationException("Cache-miss where Configuration Item requested from Cache-Only Configuration Context"); - var newItems = dbContext.ConfigurationItems.Where(ci => ci.Scope == Scope).ToArray(); + var newItems = Database.ConfigurationItems.Where(ci => ci.Scope == Scope).ToArray(); if (configDictionary.ContainsKey(Scope)) { @@ -43,15 +43,15 @@ namespace Disco.Data.Configuration } } } - private static Dictionary> ConfigurationDictionary(DiscoDataContext dbContext, string IncludingScope) + private static Dictionary> ConfigurationDictionary(DiscoDataContext Database, string IncludingScope) { - LoadConfigurationItems(dbContext, IncludingScope, false); + LoadConfigurationItems(Database, IncludingScope, false); return configDictionary; } - private static ConfigurationItem ConfigurationItem(DiscoDataContext dbContext, string Scope, string Key) + private static ConfigurationItem ConfigurationItem(DiscoDataContext Database, string Scope, string Key) { Dictionary scopeDict = default(Dictionary); - if (ConfigurationDictionary(dbContext, Scope).TryGetValue(Scope, out scopeDict)) + if (ConfigurationDictionary(Database, Scope).TryGetValue(Scope, out scopeDict)) { ConfigurationItem item = default(ConfigurationItem); if (scopeDict.TryGetValue(Key, out item)) @@ -59,42 +59,42 @@ namespace Disco.Data.Configuration } return null; } - private static List ConfigurationItems(DiscoDataContext dbContext, string IncludingScope) + private static List ConfigurationItems(DiscoDataContext Database, string IncludingScope) { - LoadConfigurationItems(dbContext, IncludingScope, false); + LoadConfigurationItems(Database, IncludingScope, false); return configurationItems; } #endregion #region Public Helpers - internal static ValueType GetConfigurationValue(DiscoDataContext dbContext, string Scope, string Key, ValueType Default) + internal static ValueType GetConfigurationValue(DiscoDataContext Database, string Scope, string Key, ValueType Default) { - var ci = ConfigurationItem(dbContext, Scope, Key); + var ci = ConfigurationItem(Database, Scope, Key); if (ci == null) return Default; else return (ValueType)Convert.ChangeType(ci.Value, typeof(ValueType)); } - internal static void SetConfigurationValue(DiscoDataContext dbContext, string Scope, string Key, ValueType Value) + internal static void SetConfigurationValue(DiscoDataContext Database, string Scope, string Key, ValueType Value) { - if (dbContext == null) + if (Database == null) throw new InvalidOperationException("Cannot save changes with a CacheOnly Context"); - var ci = ConfigurationItem(dbContext, Scope, Key); + var ci = ConfigurationItem(Database, Scope, Key); if (ci == null && Value != null) { lock (configurationItemsLock) { - ci = ConfigurationItem(dbContext, Scope, Key); + ci = ConfigurationItem(Database, Scope, Key); if (ci == null) { // Create Configuration Item ci = new ConfigurationItem() { Scope = Scope, Key = Key, Value = Value.ToString() }; // Add Item to DB & Internal Collections - dbContext.ConfigurationItems.Add(ci); - ConfigurationItems(dbContext, Scope).Add(ci); - ConfigurationDictionary(dbContext, Scope)[Scope].Add(Key, ci); + Database.ConfigurationItems.Add(ci); + ConfigurationItems(Database, Scope).Add(ci); + ConfigurationDictionary(Database, Scope)[Scope].Add(Key, ci); ci = null; } } @@ -103,17 +103,17 @@ namespace Disco.Data.Configuration { lock (configurationItemsLock) { - var entityInfo = dbContext.Entry(ci); + var entityInfo = Database.Entry(ci); if (entityInfo.State == System.Data.EntityState.Detached) { // Reload Scope from DB - LoadConfigurationItems(dbContext, Scope, true); - ci = ConfigurationItem(dbContext, Scope, Key); + LoadConfigurationItems(Database, Scope, true); + ci = ConfigurationItem(Database, Scope, Key); } if (Value == null) { - dbContext.ConfigurationItems.Remove(ci); + Database.ConfigurationItems.Remove(ci); configurationItems.Remove(ci); configDictionary[Scope].Remove(Key); } @@ -125,9 +125,9 @@ namespace Disco.Data.Configuration } } - internal static List GetConfigurationItems(DiscoDataContext dbContext, string Scope) + internal static List GetConfigurationItems(DiscoDataContext Database, string Scope) { - return ConfigurationDictionary(dbContext, Scope)[Scope].Values.ToList(); + return ConfigurationDictionary(Database, Scope)[Scope].Values.ToList(); } internal static string ObsfucateValue(string Value) diff --git a/Disco.Data/Configuration/Modules/BootstrapperConfiguration.cs b/Disco.Data/Configuration/Modules/BootstrapperConfiguration.cs index 1eba4020..c9f754bd 100644 --- a/Disco.Data/Configuration/Modules/BootstrapperConfiguration.cs +++ b/Disco.Data/Configuration/Modules/BootstrapperConfiguration.cs @@ -8,7 +8,7 @@ namespace Disco.Data.Configuration.Modules { public class BootstrapperConfiguration : ConfigurationBase { - public BootstrapperConfiguration(DiscoDataContext dbContext) : base(dbContext) { } + public BootstrapperConfiguration(DiscoDataContext Database) : base(Database) { } public override string Scope { diff --git a/Disco.Data/Configuration/Modules/DeviceProfilesConfiguration.cs b/Disco.Data/Configuration/Modules/DeviceProfilesConfiguration.cs index 942ac218..f54f079e 100644 --- a/Disco.Data/Configuration/Modules/DeviceProfilesConfiguration.cs +++ b/Disco.Data/Configuration/Modules/DeviceProfilesConfiguration.cs @@ -9,7 +9,7 @@ namespace Disco.Data.Configuration.Modules { public class DeviceProfilesConfiguration : ConfigurationBase { - public DeviceProfilesConfiguration(DiscoDataContext dbContext) : base(dbContext) { } + public DeviceProfilesConfiguration(DiscoDataContext Database) : base(Database) { } public override string Scope { get { return "DeviceProfiles"; } } diff --git a/Disco.Data/Configuration/Modules/OrganisationAddressesConfiguration.cs b/Disco.Data/Configuration/Modules/OrganisationAddressesConfiguration.cs index f35d94db..e15a0275 100644 --- a/Disco.Data/Configuration/Modules/OrganisationAddressesConfiguration.cs +++ b/Disco.Data/Configuration/Modules/OrganisationAddressesConfiguration.cs @@ -11,7 +11,7 @@ namespace Disco.Data.Configuration.Modules { public class OrganisationAddressesConfiguration : ConfigurationBase { - public OrganisationAddressesConfiguration(DiscoDataContext dbContext) : base(dbContext) { } + public OrganisationAddressesConfiguration(DiscoDataContext Database) : base(Database) { } public override string Scope { get { return "OrganisationAddresses"; } } diff --git a/Disco.Data/Configuration/SystemConfiguration.cs b/Disco.Data/Configuration/SystemConfiguration.cs index 3ec1fe24..40a3a3fc 100644 --- a/Disco.Data/Configuration/SystemConfiguration.cs +++ b/Disco.Data/Configuration/SystemConfiguration.cs @@ -13,13 +13,13 @@ namespace Disco.Data.Configuration { public class SystemConfiguration : ConfigurationBase { - public SystemConfiguration(DiscoDataContext dbContext) - : base(dbContext) + public SystemConfiguration(DiscoDataContext Database) + : base(Database) { // Init Modules - this.moduleBootstrapperConfiguration = new Lazy(() => new Modules.BootstrapperConfiguration(dbContext)); - this.moduleDeviceProfilesConfiguration = new Lazy(() => new Modules.DeviceProfilesConfiguration(dbContext)); - this.moduleOrganisationAddressesConfiguration = new Lazy(() => new Modules.OrganisationAddressesConfiguration(dbContext)); + this.moduleBootstrapperConfiguration = new Lazy(() => new Modules.BootstrapperConfiguration(Database)); + this.moduleDeviceProfilesConfiguration = new Lazy(() => new Modules.DeviceProfilesConfiguration(Database)); + this.moduleOrganisationAddressesConfiguration = new Lazy(() => new Modules.OrganisationAddressesConfiguration(Database)); } #region Configuration Modules diff --git a/Disco.Data/Disco.Data.csproj b/Disco.Data/Disco.Data.csproj index e35c82ed..67914316 100644 --- a/Disco.Data/Disco.Data.csproj +++ b/Disco.Data/Disco.Data.csproj @@ -113,6 +113,10 @@ 201309050648129_DBv8.cs + + + 201310010352238_DBv9.cs + @@ -123,7 +127,6 @@ - @@ -153,6 +156,9 @@ 201309050648129_DBv8.cs + + 201310010352238_DBv9.cs + ResXFileCodeGenerator Resources.Designer.cs @@ -166,7 +172,7 @@ - + diff --git a/Disco.Data/Migrations/201310010352238_DBv9.Designer.cs b/Disco.Data/Migrations/201310010352238_DBv9.Designer.cs new file mode 100644 index 00000000..6a802a3b --- /dev/null +++ b/Disco.Data/Migrations/201310010352238_DBv9.Designer.cs @@ -0,0 +1,27 @@ +// +namespace Disco.Data.Migrations +{ + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + public sealed partial class DBv9 : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(DBv9)); + + string IMigrationMetadata.Id + { + get { return "201310010352238_DBv9"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Disco.Data/Migrations/201310010352238_DBv9.cs b/Disco.Data/Migrations/201310010352238_DBv9.cs new file mode 100644 index 00000000..ee895e09 --- /dev/null +++ b/Disco.Data/Migrations/201310010352238_DBv9.cs @@ -0,0 +1,30 @@ +namespace Disco.Data.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class DBv9 : DbMigration + { + public override void Up() + { + CreateTable( + "dbo.AuthorizationRoles", + c => new + { + Id = c.Int(nullable: false, identity: true), + Name = c.String(nullable: false, maxLength: 100), + SubjectIds = c.String(), + ClaimsJson = c.String(), + }) + .PrimaryKey(t => t.Id); + + DropColumn("dbo.Users", "Type"); + } + + public override void Down() + { + AddColumn("dbo.Users", "Type", c => c.String(maxLength: 8)); + DropTable("dbo.AuthorizationRoles"); + } + } +} diff --git a/Disco.Data/Migrations/201310010352238_DBv9.resx b/Disco.Data/Migrations/201310010352238_DBv9.resx new file mode 100644 index 00000000..5da5f53c --- /dev/null +++ b/Disco.Data/Migrations/201310010352238_DBv9.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + H4sIAAAAAAAEAO19WXPcuJLu+0Tc/6DQ052JGMt72yfkmVBLco90bEsj2d2PDroKquIcFllDsnyk89fmYX7S/QsX3LFkYiO4lFov3VYBTGQmPiQSW+b/+5//Pf73+0108JOkWZjEHw5fPHt+eEDiRbIM49WHw11+96/vDv/93/7PPx2fLzf3B7839V4V9eiXcfbhcJ3n278cHWWLNdkE2bNNuEiTLLnLny2SzVGwTI5ePn/+/ujFiyNCSRxSWgcHxze7OA83pPyD/nmaxAuyzXdB9DlZkiirf6cltyXVgy/BhmTbYEE+HJ6F2SJ5dhbkwbMbsk2yME/Sh8ODkygMKDO3JLo7PNi+/su3jNzmaRKvbrdBHgbR14ctoeV3QZSRmvW/bF+bcv/8ZcH9URDHSU7JJbGT9IetXFSyc6qB/KFgq5TuwyFVwl242qUl/YuccNXpB38lD9wP9KfrNNmSNH+4IXc1kdsF/eXw4Ehfk5IT6x0fiW203/HkC67pH3lKUXJ48DG8J8tPJF7l61bBn4P75pd3FCrf4pBiin6Tpzta+mUXRcGPiLTVj5StlqyO3ObvQbSzlZT+U9Fs9Tfb6vFRBwIlNM6SxW5D4vwr2WyjICcuyLhY2nd38Y2VBl711vsZyRZpuK3GmFXbL9/0btwF3m/7NvoxjHKSnt9vU5JlvsWWQQcwQCGVk/hjkm6atn9NkogEsV6WL8HPcFVaLIHoZfLjdvejtLqHBzckKutk63Bb2ehnIqS/cx98TJPNTRIB0Gfrfb9Ndumi6LDEoPLXIF2R3HEEdoT8jD2wGm2kaGGUkfqy92BhuLVq+c10JuLFc3upUYSf5HmwWJdwGxblDXCNUN4MCVMpzsjPcEFOk802iSlNRAy+EioFXk0WQlHXVoYaiSDrdRnGMlAssQrVcWARVi0tUPCm40vLk7mLwffH+B7GRZy/egkMR+rL31IXn/xGYkJ9Y7K8LmarNC6+JaUUentRiFauLBTNmcyUQ1kek7ZPkyxvGj0ji3ATRIcH1yn9V710e3d4cLsICnKQGu3sQakshSkoy7/LtkO0BXA9xBgglR2Gmtrz6G/MJL/DwPD1GJVVbzyqEek6jt70Hkefg3h3FyzyXUpSa5+pd+PVuJqi1WqGtGr5dd+Gz8hdsIvyazpa1kFGzoqla2PC6L+/hhsHktVQczOGFkz/EaRpEOcPtPRnuLTGir3ufLhoPe0ybNc0RtxODBX337nJR+SZLUVmEK6KB3fIaQeOpGEQfdltfhSYsd5g476224jovaI7yTKSO7Xd21J8ShaB9z0fc3vixzksKNEf78KI6GdRE2K/Bvli3ZOtYsTu6PRc/GWr3dc9lUsBFa5isvyWkdR+n6A3poIs/0Lyvyfp3z4lqyT2Mf2cRFHy929xsMvXhauzKNyf8zhN2kndeOdM7KaUFLR0PBrRKhmK9MRMlVjS8zN5L5LNJiy3Of2wx1K8IUHGWJBqXhGLs77zsG5pZDGJwdMtOM/Z8VgbIQWXdY3v7aQsMipUQCZcsZbb7lNp5hTMluU4q1wxwihfx5ZN1o6pup6vJ/U9W4x1PlfHrfeLTysyG427yNes1SMzDlZDFA3XdcPFGcmDMFIJUNVAGeeKEYb5Om6MdlvBKma7WijDUhWEabmetw3Jml5VLkG4+BmDblnmYbujsV6PaMPDwflyOasQFxPrJM2dmp7uiKb/Bk+9fr9KV0EcZiW8T5bL4nDVmx/dnsP7vB9gptgwo2392BVScTs65dAVCjNr8qzSgoiymnsV0UTP5/FdklYbDY26T5P4ZzHOOjC5etk1cVxMV8LlLlHhZZ6cnSwWyS7uTfGU/ju8K1cYzRaU9RLqrfUCrsfujbVLCU8jmOPZY0Kp/Ms/93TS366a7uKaTU277TYKJ9iBb6VofMuRtVgYmyF3rwv6/7kLahj12s4qp1F/+2PNhvrvQRQuv1EGo76L/4aiW1/2n6ou4myX+tnHKEkF8YJMNjBqYbx0TCvNVD1DvYd6NTZ0w4oJUxw/Bjsc8ifYZodYE5lN0er+T2+sdmnU3HqY+cstmLlek+1/U5W6+nQF8uCyqd/bUtzu0niKdn8L6SpgEomv10lMnA7G+t/7Od9QCyosYE0btz9CQcd/MZ5U+3Fd+Xdx91Mokra0xHLbraxyy1GzA8fXAVkUikE2xTpu24XOG7Tq/WVFZbPNWnB/uveGYklN3E5sf5Rmgq6kt/2vQOUyCzQHlgaXtgd+ceP/6HSwlxAediztX/p4aHSMpz46+9XXpkKjCLK5zmOps3yPaSNlmosJX8liPdG4/hhGxMF5U+97GLX8ma4jHe4gemi5WMFmebDZ9t61clxWepBBfPPh92WeR3tl6WRBdgtzxEz5a4aXCY9dXZTPpoqO17ae9dJafN1pwLf8Dcq/9FxII4dU38MOPO9ouswgFR3V5Urws8alrfbobKcgqNHx72QyAvS0X9Pex/sWB4bC2Nkjw9s53tZS8N6VyerLbpk41MUdI/6F6yeuj2Yfk7M44YPXIc2Q0dCdxGBcbWlfLSf0lisG/NzJvd+SBUXdaZRkfo6MKkrDaMe8fR+SfIyCVedTN97O5yAOVqQwRnW5y3X8/yDRsi97HaXplN3x4PhSov9GdMXCDQmWDx+T9IbkuzT2o1qe5tRKrrjwdT2dpTidZH8EYU4bojoup/kFC6D+Dpjm/f33tlx62178LPkjbJmt56R7/Gvx3B5hS/mwt5dTp7xzizx447bQvSzgFVv10ImIGwf8zI72lFiN7yy+FOwvoYptl/FTLMqmWI1nky8F2RSquCGLnaBQVqGqPLtyDZBloJob27Dx1wiAfQSJAtdVCIV84Coeb/u1gonVYZH4WkphhKoOFlV3uMpVKQyCwDVfCMUxEWo4nD1qnkezNQAOuTKIQb6CA3+fkhXKGS0DeKp/hbhpihz4+EzyoL2ehTHEVQJYk8ohJuVKjuw21/xU3DZ1EGbZYoxXro4jq1+S2IRbphrCsFAD41ms1uvNe+OmzfbW1FwDh1l7yzoXtXR9LSJWAeZfqtN3J+9xHgBTwfo+1X86zR215afTXL+nueX809+pA0wQ4vZ5OcblySPesskhLlJtkDNcvi3VEa66pkYIvwe4rPP7ZPnnYvmnfGA7UiRChWEyX8oBIwVe6/mySh11xCjJFdRMKk2SzSimi8an8TuX8Tu5F+PyFt1lqKr3NgDki9sevgZmQRcZkmwRxpK3YchvwDgMyBr4tmPSw3j5lGTZVXoWbIKVl1iO58WrftfIbx7OM12n0P7vE7+uw5SaPPrDabDLSNsvrsECRHqTvJISmfhjbXuZ/21vHv4I85hkGcmKP7P62RSxfjjVXxm/7tJVFKQPX9fkLqdjfp0sr+6oPUhtdeLh9Vr9ZxHK7ZYQL3HwrpMoXJAvSRGioj98eWq3+TQGgefCv5ZOU0qiyFmU5l8SS+le95buhiySnyS9IcvdgvA3AIyT6vS+0JWvqbcVU0ePOj+ktBWh9eD0ECGIdufVXRMJov89rCDcFMlTbuls5udiF0NwpPsiLq6d/SkR4FvhR0nmh/SCusz4BT5TcC/V1ssif+LDdWyPl/bKczy/LxZ3QeTgl3h4QV03Tt34lR+73lCkqqWmrDxInUimYp8gIgaBY72OepvTVmScgKebfQYGe/S6V2PjImttRmky+jpTdfwxisPTdaHXG/Lfu9BTmBqM9jS3GkVuqLs/jJgl4XnIeB2Eg4hY0J1GwsYPu0qX1D0NQk+XygGyc5DPccZQpmuz5sKXpyoRnUbDF/HPpLzqtiDhT1/xuDiS08hF14oBta4uofv7exhN4/68pobidF5Tw8FAXpNqdjS9DqamobwnpvoUc8OMv7ddlaFTqKsiGAJWWmi/c1FB93Ff+Zv51VX87nsr6ZvPXIRvv7WVHZl6TUVHP1dKjnxlIjj2aS+5TXYjUCYUexLab6wlVu5PqOQFJklTacFPlbICX5hICn3mcAXe721eA757L4vZ7AYjBlwYOBzWDCIyPIXGGjOIqubNnFUCEDjwAZwkpMeYe5w3pacPQvB00XrUlie/ovTILlprbZlTfiDYpuF5hLxcp5IagS5WoZX0PA97DVtWkeImtrayQQ94vY99ssvXSRr+o5SqaPExTTLed7oMk1H8+C+yyC+WEwSqL058ssts8Dtolj4Mk33mMeHrepBMOmZ3nJqm4yW573di6HK7713vS/9xTpisRmEcFFfZdIPz7at3r63PtuOibu9LZef32zAtraSvxK8Lkwyt5mFhRvWl3d0SxhSgfolcB5kWgYp2s+Fuw9kqIL3rRVbGi2rV9o0OuDR6oGplxxyvnc+k6IQWf8uru0/hHf22XP9+OHwuqZP74DYpgkzVdV/oKudUHXFb/aWm+qfysU1d+ZWmcnU1u+Plta5+EheQbuu/eS53Q6VwVSfIWed6d8FVTL4mn4P4wbQLyg/of7pucJAEjDrWylINK0AUOjcoOLuI74ohXZL8XlvR34rLyRirJgQuooisimdXDYrsSfweFjhcdBp7bU/jOknjZJUG23XXUe8syPxHsPhbae4aTby1+JjasfuHXx+2Qdap8pWNIn5NSVCsM2h/n6xSUv7YUnpro46K0kc6J8YLatJlai9eatRSKDRYUKGKTCNdl7x8//r9219evtfopfm6zBXS9cSbd+/fv3r95r1GKc3XF/E1SUtPtOH6lxe/vH/39v2LdxplNBRuP992XfH61Zv3v7x69+qtoeifWd7fvvvlxfvXv7z95dVbk4F8kmUJ1Xxhgrhprcp1VE89XYQYnhtq7w/YOQr+qJvQHtowhVymps+7KA+3Ubig8xa1V8+eyePasKU22IfYUvcQV2jtX6Sm6kP2PCzuCMbUQgdhnMuOe0gBuw0iC/kFGobuf9FxbWtiyRnZkrjw4C2UY8KGkLtO5qhtWFiq6JR3fMQAzgSHXFJ4NSbgDPEiEvQAUNJFEWaO5R4Ag1gZDVaQfvcLTNdColV1v19jWVfFrq8rip2vt2JiCyi4BrVaiJyj4QrRgjm0agITgwvNRKjGgD4toQiGKimvtRnTJjScxqTp2BoNhrqOMMMjlPp1BqA0sXdInkkj+Bk5bXCSynGNHSjk6BhzNHTl55MhSsiMhaJJzKAFIKmrYmPHRMIAgqqjNN087IQfpPURsIMo1KTl5tR/MsCIWY1UfYumOOL7l7klYgkeNFGlGkD+pjwFEyPhCNHxvmGpPTY37G75BH0ATEmH7+MZJgUX4wNLVLYJB+wVpTkATLrZYIgB/JLDAIBD70ewPpV0RWMk44YxNz4esT4xcryAe1AT+vOlZEgqLrXzrfgS9/X5j+zXnKpGR598jVkabTlg0CcmvIjJ6eaDz3pBZwUS8RR8YEwKZ+na1eiQYOR5Mel6zSuDnoDku8J8narjagQ4QrHAMVwoA4N3eGiivFts86rCifOU6+KB9j4UEo5g7BRaMGn9ssseOBWU2kRMio6WszJxHWxjqFhqMFzMgOiKFbHxcTAiKnCPsGFiYgzMiwNGvJgVS4Gv+ORSKg6vkExTvcS+gnNTjbPaxhkYaZTAKjVpnP9y0jEjJP5S9TaWBawXhJC8YaOtRXAeRkIRrFWTxuXsqZOhSE6lpkQSkHnND5oAwpMgCudjJFThGjZfPIjpYidGF5IwTw8HXfY8D4jT5NubAHtqjkZFoVr/5njEc+xOjkwh46EJYLD0h17QiCRMnASHMC8jIxDWtg325PzHU6FOyGmkwAOW4IjDmNsBiEwdXvcM5/zDzY+DK1ixhuvkmWDHxFoZHtx6QtF0C8lpT23VijZhYGZmyfjMVv3ZgFCb14GtGW+jI/FRHNdeirm2FABBEm9x6LN4wKKgPfZkCbY+DqBApe7BVAmkQTPqXs1E2R8/002TOA9jQ2lfJ8kml5iio6XEYhx8ihR4dsCRkrCPZHKEdsdBiKC8PTAzXFI3TTdqTIsbNqYzJ1Dr48FkX02InLNG0cGKBDYcdPiUfnZvSsBmxrY2KAfjAArV8x5YIF1SIeN+V2QYMgebxmKZJigac6vTkKcpkIh2iQkzYBavKVHKxSjWgASOVizhsE2442TzwFjHY5o8iIHxcAbpeE8MnnHCAg0C7LMXSBBk0z7ZG0Pr9AdjW0ZbBseDr23fmXCmSy81V8x3uSl64A1IVDEi2uVMF3OCusTdPHAudZkLyLnkYnNFeJt+pAfE5FwkI+JbSmYyJ3iLzM0D3WJ/uYCbTSs3F2xj+WUs0KVNNjMgsnXZaqYEtoa3aXCt6SwTphTJBGeJatPtB4tkQmMhevLNCGPOZoBml40JNGnjXJAM5YayQJMyUdSAKFZlmpoSwwq+pkGwooOMGIJTc84FvQa7a2g6MBt0mu2xYSnFxtxmQ3iYBnx7tNlWDgzKAP4er62BxeewBE1Hzwwnnt71SmKMAA1JVJM2ZxCawCZYhmF4DIdYsnMIgTFt0IvHEOaCT56n7nIkk56IJftweBD5acJYgDyYdKnn8BWgqk34mE3YiooROZ+ZGgOK5GYiDtxuMWPNGMPNtwlDWZkAdaj29xt52tth6BeDo2+iu2NaPkabQ/f93YY8cEyfbmi/HN70zeoNhzF7U2DzUbzkqG26cjnJ1DFfLRjFzJ5gUQkIM8Gsar3EnNlMyr0/0cYHUnyDA8rpTYeqpZFiCElmwUhDio9AFWlMsFJHqrbGUlLVT3IKQU3HKvIJSvhhUpXaIwjPRzj6agDnZQLDhffAjK3YeZk0skwoFsZdlsMwWyRnQR6UWevucwl7xUe3JG8u7ibxXbjaValDL3KyyQ4PzttslDUipEoA0niy4miEqMqjXUOUNTkyOXZA67jj7SnInGitjUiW6UNwcnVyFiNSOBVDAnWGHZxOmwLJiFyZx0JBrU4xoqFVrGAgGtUK0ODjarsII9FsyBkQ6lxejBi79jBSUflRG4kVVxVfzwT2CN5NPlUMF6Oxcsm+80YIWWjqknmaiVAzH3TV8yyETPnETU+AewSBkBJeoZgRrQ/hQhXR7rjTjGZ3tqckyx2kGkEXH1b8TrcRMTVe5IW9hujJLl8nafiPcvYpZm2IqlTJdBLoZn7FNMA6XQJZZnIGZwM5H+cB84k8PWjydwJenSaDZyu3OElJLooh4cZllAizMgpaOuLVZKxCLpUkqjg84SS0OmeFQ5Vkoh8wyaShup01IuZDRJWiTJwISIOlTpQE6hwLrYawZIl6dTvrB03phyrKLAkgIJ02DaAkZutEaTWnzfw3NM74LHRa5ZlhDE5X50FNI8Cr8y+rrFiASsQqOPdCTUgVnLerUIRIClBC7XV7UYGYHAxRgzKHmMQ/lkVMkIFzLDQqwfKGDa+W9hBOrxr4vE4li3Re50dF0unc8GqSl/9adalPnFTyoSdOftSHni+xlkjeEvFkqvn1JH9nCjXcqo90VlfxLW7UpdWx1rirmhkQp2DjzdaLoTqhfV+9hMLmr38VCpu+g8yTl0AWF0BtUDVcGqA2pKZuv0OhGYgWoBGOfx9aaROSwNqA85WInEsZS3iOtZJLOUoMtOcurgYA5p1v0PFGoo/b4ULSDUQJqtQckgxIcg5bVSDpOAawppdy5ghED6r8EpIASIYJWz0gOSUG0kNlZLncB4gugJpqQeQPnHUCkBpFL0jUfqWGTCL9IwJqYv27aU0T3X9g/Qmx5TWaU0WiR8VDYtG7aguJPj+MnoRo6LB6VCHTRTGQoOm8MkyXFDI9eI7yrwwNYOzWq/AHXnUzPlxM1qqaL0yFM1mpOmtuqnXqpRhZGdafIvqyKBQcf5nXEX4eoaY26LgDYgXrlGE26hRhhfurZaQh18S8hTUCRsQVeRZj4vKyV8fFaqnFKLiDwICL5YqLa9b1YMBXN8FH6mg5MimsA00EU1ECPIYprw3x0F+tFzxk6SDQ0AXZNNGUJjSnWkI8OKc/LeLhOIcDHPdqHdci/rgdEgl82y7rib22odcT+Ip9MLAZBzjEdeYWIxES3TpKoqxr4ZaMXt3WgRGHw6hZ4D23jkAC99lqRA7dN3AXyNH6ptF/GxbOTf1wVDlbZUhx5QZWvhRKbhzdY2HLzFRvFPRMpwld2DPPitdFOptA7wYuh2VQLislGLgf/jQ+oh+iC/9kpm1t4Cid+KrQUZ41rYoWNY6e1S6fMqSRTji149dLb8O6f2U3VLTgqxfAA0rpFgT/gFLXmcjnw8lYn3ib3YmwuwVheO/B6CbpuHcb+FAoqDoUEVMAGeCYKZI6TK60QQRHuDoqh/BAVaOJ9gFIg8f7kCQy3dvFCI+rKtUuFl7ZQirVzlZPhY2x2yX3ksFhgv4jG1gYHCn0Rd6kF+DQSYwt1tpgbCKzMOOjTGbwK3VUeoNH7YAo6mftknYMzxRUtAe/kaN8wg6pz/jJOy+jyaN3m2FhTn14FYrPobQTpe4xPAQP/Dm8jDvu+ZYeefgD+F6T5fFR9Xn7GLstOz66XazJJqh/OD6iVRZkm++CqHqw0RR8DrbbMF5l3Zf1Lwe322BBJTj919vDg/tNFGcfDtd5vv3L0VFWks6ebcJFmmTJXf5skWyOgmVy9PL58/dHL14cbSoaRwsOseLT8balPEmDFRFKi0fiS/IxTLO8eFf+g66YDw9OlxupmunT86Y59AW63I3Ns7zm0+LfzHv3Z0Wrz27INslCKsMD8GJdoNnp9yMVuRhRpfSEgYEBDUrldhFEQdoEBWjCEyyS4p7naRLtNjH3kwhRnMZfyQNPofzB/Pvfg2gn8FD/JNM4PhKUIfbAkdQFwtAQO9eo62XT17/ndY6SQcfrSWA6LwIesQqHAiDhX5+RbJGG2wJuPBmuwJyeDxR+DKOcpOf325TQJarImFxqQZmqNidxcQYoEGULZoNV9eRvi9KOmgM+VR8Pg8zL6ma4SIT5eXiUT2WjRP/Wg4niSbpYKB2FoQxU+9BUJCQUTWf0TpMs5wlVv8wMUPVrXV9gAh8sGwMJ+Xo/ZrnPQby7Cxb5Li32oFiCfIkFxeq9OEcKityjpVG99pHoQHFX1BorX4E3x1Vn5Z4Rrzmggu2wlgcO+7s1t80ZBi39GS7FrkErzWyY+huhzoPTYtXBRSDj3D5lbDKcIl3wkhwiyBWY0/uULAJ54He/Tj0VMTErYKpMoS3dMlQBTLUtspnmNtsd9b2Lv8Tpji2x6msuVL/Q3cow/ooeD7L8C8n/nqR/+5Ssklg2XnANC76jKPn7tzjY5Ws6iMq9neV5nCaCBVdUs9B6SorvZCG4AnN6JQMRRJAvsdN3+S2saKbIBr+LZLMJyxUexCtU7kb9hgSZ7BbI5TObJdqIOL4miyY0n+ucgX4/jEsnGyFb43O7TtJcJsP8PJ2DWfsqV+kqiMOsnKlOlstixwP0acB6boa9OyHEDDwWO1MpT5jlafhjVzAoe6hyqTllVvQg+haHgkMJldsYy7skrVa9jfinSfyzsOZiT2uqWrepE0xRzbyt0gkurNzJWX0Jk28EKrfAVXf00Xjb4qBHqszM2DbBoXzZ2ipwqaulRb6eq53F15Cui8fb3XYbhdKCo/3VgbfmhhDIHnZ9CKdbjEN5cdv9akfpP3dBiQGZWldiPbcoVzNQDfMWmiX270EULr9RBgW/GCq3pw72mVRoTrd8KAT5mlyBJb3i4REMV6DYmldAt3yJA7egWuVSK++ivt0jeBTInZ/JbH11+6q/jYcumxkYd/izgTZEw4z6cA+ycecKbCxyGsuedPOjOZ3fQuowyVwxP1vY9jVdGkIbSVyBhV+2ocgHvXC+ZFZ4bsarH1TXIZndsI19jM58wKaQ/WbQ07UIY6ywNzH94IWJuO2GGRWBYSyjH9SxmdNYSqqMaji1j2FEZPPa/WpxRBTS9bt8QtT+aiEh/SbLg81WELD7eUgPAZ3XgGxg3PRmkC1s4rWmGHDR15qTp+u8+NSRUR9I4MdFULn9QYLsvPMlUx9NfIsDlFOxbDa4RK6yO9w/crt4tJ83joaEu59Jig/IKNKTS20pyxBnf7dwvO+3ZJGTZRU4ETi3AsotJh8uHKO0PymV2lIGDu6c+PwYBSthhqx/skVlEWYRQmP1uws1THtwDZcW4FN8qNyWOh8+EaIv1ujXglpXeF37VqtAh9DZqVzuSl0njVzLZqMvLGJCUG2UTsdC7n+4xpwmTo+Xd91v7o55bXfPrtpe8mENvXRUr1Wv5vvBPB/A63la8j4tebvyoYaf12vuLD23wTf6Bff5jb0/3fX4JlalF/wVOSCdkAd++GfB3LS2dTrcCfEsvSCQTx3qhEUNiSFx9SnJsqv0LNgEK+DKiFxqsY9QXMaCF5JC0XS28us6TJfXAf3hNNhlRBxbUqk75S+SdwXXcG/hj/WDuoGygsV6MMxjkmUkK/7M6vNWIl4AwSqZt/PrLl3RXx++rsldTkfCOlle3dHxkQriqOpZXcEr/yyuSt8SAtxWh2tYtJBEdC3+JSku2omIEstcqd7mwKhCqri2AWgGKHelfprSuaYwpGn+JVE1I1Q0b++GLJKfJL0hy92CQNsZYAWLXdd8TafdOCcU8jkpB1ooDg+sjoXFo1q+umvuxglGTyiz2StlYjNDW6ZSsSNteJMXqDA3L4GJ6OfNS2gzdjs7CTiFIX2E83sK4DiI5DmML7GnSJ3wFXzGIJfbU78hd3TglQndIeJMsT3tYuEaEfClEFJlbgjnw1Z6Azmbmd4Z50oiQ0L9Imv98NJMCcs+qdTihBuJOg6coStr9m8RPGPX1HVvtQztrReSqdazLRPxuIru7RWRs/WidbX6tWQiGFvP/l4+E5gafz4gVerVDiSUopprW/BMgNVxbAV2ppAqPdrQ6kztWKG2jw/hDN3MByo404ekQKrYOP3bgNot4NE0X2JPEXNVoHJ76ghAgWJ72gpXBakyG1eFDyjc30dh6TnfybO9WT3s5aSnG9cWSPJ7+CzSdEbU+EfQw2Ly6XD66XDaeoSe7PJ1kob/KLcti5CuPoaoRNRhjBrQGGaQyk6MrfNyu/vxX2SRXywFcLG/W+7sZZdS/A7299nACYge7MviM0TdI/upaAwDp2skKMC1MhKAllq8JPcIwapoTMCXcYnFsArtjxbbfHHwIxJPb9ofrS5Th1V4YfAiNVdmsTsQRckCDlMkFI3tEQw92Pn43NK+Jh/w3WDHkv8A2I3EI7EWocflHUgoFrysJaPRXVCDxmSho7Zle6bqcOjuTNWUQN4Ue7PIY4+GmuLdBy6wGLDdGjPKfAuWUV7VWBIqW+HKIGGDY3eKlD3gzSADxBP2IG/cEnzKr3UBz+3gZ5DvwhV/ImkfADRIoPEnQaCUtUKs0s7X9S/t323WijpjBJfKopSzSExRypfV2SvEFBJVlcODxh2ky46HLCebCsq3/x2dRmHpljUVPgdxeEfXz1+Tv5H4w+HL58/fHR6cRGGQVQlH7JNjkOXmKMuW3GYd4/Z3TqMqDcTxX4mEuqY/bsgdvw8n9Z5cE9hcOz4S2zgWIFSTL7j+cBj/DIrdfuqBfQ7uP5F4la8/HL57fnjwZRdFhY/64fAuiOQrISLRkhO/JOt9P57o/90E9//MkspTcXOQdQyVnaVO3WDWV/Iw03dA8Y1CVa/sVcXdWVSQfvnGnrYeLm+tacqpIMyZljscoM9mhahI/yji6ynZNMYNNuO5Igashprx3vh6aY8BhhkF4TeD4fbFcx3P5oNelQ1hjDEfFvNU6VT9Rug0GpSX+fLink9Ri9RR4awVyUV8Y1qyGziOHWJCuno6UtFckkW4CaJivqb/yso8YC/oDF24PLT4pd/OBjIW7HFHm3XQG/sO4jMgKA2IPe0qJcIARKvjFgXh19Z0wQwJNXDpv/Ow2Ei0JdllR7AfAhZMy0kSeqjGcpw5+bqKXUADV5b7WuWi2M95XNYCr/jqnqv49Xr8TQJC9gKQksW81KYscGaJz1OgUttrW9JiTCClUbXuajBfQT9bokhOYOrqAgpmcxLg/BnR4tMR9BNWyEPQ1wrLuQf8UWzyDRiC3NK4XkNR+vfWjdGOY73HD8wGXQIAJeU5OV2qPABerGUX9F+zkWKmCSngv/vcAAXAt97sgayPMpy/u4lUxO13J3oNxOnvYcUJGJRf5Rhp5ktLKwVEuH+8NsphuJuuKczsXRt/3O+6Sgqf71cHXTD9YVZCfHj9Hl4wFEvfmRwUOr+f7yFFzPdgPLmI+f3YA8Lk+4UpHzDfE7M+ldnduxzuDEOOPT/ZuYXD2QIXtN4vOtoY9n7JMgHtPRtdNra9351XPsq9irZugWsFS+hxgxk4sYvd45+VWm8KeDpSc1n+6I5gXWgOfgarihW/t57jIFtJ7IsHv3Ds3j+YO3pGhLvnEJ4JM48jevrQ2Bzdm0XogYTxoX/vdZgq2LvZsDK5pAt8porarh+XUKPed/UZ/nqCZ9CtYzGqvI2Da3OV4ZHY3OGuKPSApFE/DwGeKykGvN8p44qJB9/3tAAIAt9vMSeHfveqW3+M1mHgm/2+lfNZXRUA3scRtRjy3avmoKjvfpc6cNx3H4rB47sPoCI+xLsf9uWA7l4ZhyO6DzVp+bt813/bY6xbb/009ugWWXVAJvfzp6cF1dOCymzsPLbbojMeOgMetU9xARWKDv4EG/+wGd5+mdyXsIGFIlC3GUDAgIR6jPTuRDmQdz//VIjg7fdURWFOnI705Dje7pc14KjdfuUHA3crty/sHX8sbrfKs3UQRRW02/NRXP0nH7a7H8rFcN09bgzBsbk9qwCIz+1TAUIobgXzr+2ZB6NxK5p4Z98EFo3b8+VAISp3320xKRS3R4IeNhVsp084ru+8Z08+zLXnc34g1HXPuVmObz0My0LUyKG2jZQBoecNHDlgtPsUog4L3Q8yuvDPXjcdFaGf/UrBRXkeVIQuxLNfCdhwzl4FQIM59/QX8MjNA7JvZOde9mvE1/SLxmn2qh8wUnPfy5ZgaGavbPMxmv1OWlCc5n4aAYIzD8PyGPMsHtp40JsnA98EHP5qytOtQAFCj+7IavC7JE9HWk9HWgbDSxOGeG/Hl+1kb/jKqgtw7GEHmY1wPLQBRSMD720PX7u8arSjXEUadl+o67fx39mfXNZRhyuqlOiPMA7SB8f3sUXdXlvQYrjhnitVPs6wj9tO3qZYm82lfmHB0BC9YFVV6Ej1Fz3iijUsuo8NgXPjNbYtcT+XgV1jivUDglEc3fmAAmL3CSCaSJM9EWIU6XZGEIH4NfZz/0S4YWLwdk037bYRmXlez+PlQeHCd9dia86KMLfP2t8+76I83EbhgjZL/WBJZI5Mg02BUvszT+xfJGL1NlYeFgc7cZanQSiH779Ow3gRboNIYF+oZ+iZFkptKYolZ2RL4sLllEU0aU0ZUbmlLQwKnQ64iMtqEDAhCL4L5hZHAxv6kO1H7ne+I58/e6YChhg5U6bKlA0CETSc4zAwUYYKRZoUwkVMiJfvePDL4VECEHtMmNgzKFxXscNqROhsRl0b6MK2xHw2mQYO11CwtJkA4rqLqzghJMpATYaAqII6yV1Y/74H5gEISzUTNLShMaecKdh3zCgWykK236ofZt37skCTd7v4ZnwGNkCMczW6t2BlYPbZbzC3Q3D0sUnA0sXy+d7fQKjAwAQNEsk0P++1lcCCIiGtTWoh+Lg8HjpeYwiEOEAiNbZo7zGgTPM8bxw0FwyGNQJPQABbVOW8ngIMmvxJzCwvVuSmeqlwrwyHWgmzwY5Jvu4RXU8+PtXYCxAhOpbseIoV9trS6COCIe3OaKki4AXMN+KwzNwXqFisLzX3ZkeAjdH93TGgU6crBo5Zhzg0E0k8imOyvTgfK/r5igt4Npx7Ol5HjzU9mPbylRRSbrLO5gO8Deow/Hn7W46iN1l/y6Hpnvp8kD6HYwBO3O9w5L0nBAyIADzY4eRY4MMYPqFgUBTIMSMn23cqPHn8oPqpu/t09wwW+OruNV7Qz6aLp1ix243ueSzQme1kORa5Vcdp+h3ZIxZKhlqyjzTaLTeFwVgmk/T9KAv3CSEwosXft0MlHgizOFOaFitTnCjZ42Y2B0psfN6B5xD47jtfsOcziN1t94knkK7fR5k/Juv+EWcPu/6fw+TxKVkNPOyLCM4ChfKnPR/qUmBqpKWJB3nRv6MM71G7ecQhbdrPcxjMXFTsgYc1H4FboCUUGriPMx/tinjjSJsTj3seClKs2aG3At3RsX8Wwh4bYOjfKZHShHQdwWa00WMBUHRlj8NiwJFykSZnYDCY4L7fVZFox7AebKBhACpc8WOwIGhgZaRVXaTgueKojQX8BKL5gYgL1DxXBDWxmJ8AND8AsXGy54IfJBb2E3ymh48iTPks0TPm8ukJOxbYmctCikUOEKj9CTfT4waJnz8X1Ay/AncHyL6uw20hMuVSnI3/P+JLLSByAF/waO554QkWkJZnc+FLjOvvDR5Gzz6ROx1y4SNDiu3NjtmiZfhjwDkAZdx3wft2XUw2IXO4MTYH3Exxb8zNwMzl6piUJWHc+YhNzwAEU2VLH9mMhCamwBAzlynpsnpS3sRi/n6b0DW88nW5frkjynEVn5EiR9dBlbr2w+FpkC2CpRym+og2pGj5Eg3kfDlCLOeRFkeX1qGc4djnU4Dna7HfLOa24rrQLhD3Y4WSTQdDnYshAQ9aMCwCVUH4dd8o2R5vymQvXJsawx7xwwdCNp63Q8Hb4Ih3CTvuN9K5JaSNMpZMDc49MbbzhOS8jXA/9O67QRaTq9hY5D4r4qEGAJ4qR8Xd8FZ5itW1YdogpHWzPEGTg3RfLPNMgTlz29wPwntlnM/LpE5Fskb6BUmbq9LJknwM06zI+R78CDLZHBdf3ZK8rR/fhatdlV/xIiebw4PzNltUDTKgzu1iTTbBh8Plj4TisUo9xVUDtqP4hmWDL7UrV4GaFWtl2qbZQSI1yhZCzTG2RC+juM6QRRRrgBKKWZjM2q0j5CNt1qV4e2UF07bQZlQtmBJvE8EgbbTleFN1FdMW61QASHt1Kd5aWcGgseq8SGql+hkiX5SYkW2OoUHiTSHWRFVu1hB70AA2xlbAGuzqmPaQGAgV6SqxGt5nfE0jIwJbD9RsGNHErZLSJJnZo0s+ngDUiq63uCpGLarMH1+MtGdh+Or3h2BDZQHSBC0zIi68xIKaEaogDXK1jJvu7hlhLXc1FA3XlULzhrk7TljbXCVF8109Ew74WzXIMFcZNLaGaXPKUSJXwZu1GSsnu3ydpOE/Sv+p8GeBtoE6UONSNWNfhT0GxLwVto7CX+mqGeFM55UZOGbZ9x7embJ9RV0Tj82OL8WaTusjazkTvWUla8zSQ5ql+A+ZmvyUhSeTFdfdrIS0NeY3aTUFr9f5T9ufxVU3L5SBwIw/LGdEBSRX1sdFAbz2Uhbud4UqkNUGQ4Mp86QULu0nqgo8OegACgA+9SaumNoSlViZAxNgWljiMLy3JZMKzidwRMVW5HkEGOZWWQzX9e+TCswnCcGRjecS4RhmV3olu9UPs+hTKSGftnvVKfwGGNNWSHFQSLfo/Y71t1jFZ1/LC/b2u+ZnLyKKKdYQMZWZ2DyIKnvX7bdskW+R2/u8erHhq7/7K7q8k6pVge4ESnmwxw5UqXAmKoK2fQytvuoj/3MAvNXFWEGxwjCqaWYfQ6XA1z1dJrhZqOSSye4DL3bg5D++FjniN55EEhLZIJKp0t30hPhwoglpWxDRVMldZitahXEuQwkiHlBzn0REknEohTVJ4DF7sYW8ExqBVVkqZilq0WwVgx9xRIAA/bMUpF4FYqKwxb5nwsFAKATJh7GniqRvy6ZYH/EAhRLPomrG2tCLg6nENlkZaL4YY2Ewqnr4AN+wQhRBwPvCH97B5Qv8iqnBvi7wdX/ojyVyE70ZlhOM7dy3N5nz6OaT8idf4mj6Do9n3L/XhhRNDs0Ly6cJ4du398AD/+ZjodC/2HIYWhMlaILX9u/3KZTCxXvBtYCHhfGBBPEOBCtzV+ZLZOPoorg63AKU+kEIcGeE1RdXPIbKukCabvpCAnE+TmW1MSPddAWHnHwcqsLCI5ppyii44iNUlMEMZhlF8HEoCQp6Z6Yibbi8x6Eg9XyvjATnY8ofVXz2qqL2vEUR8szbOQtwKM0XeBJZjtGFiq0J5+VNdGS7QS70rwLVkg6v7P/gcUIVmGxL6T8aY2dqGlUBUYRQDekiDnkbMsDlYYYAV+rrPFZ8e4wfzSpfKfedKS7RW6iXPi+iiqLUb1kNhIZevYpC2N2jnUgFwkVWQwwYfKUFt8u9WhUdRGGKWoMqD8eSwVdD4WoGKjMIeADpzDZOwlCzk/YtAUhzPBUqYGf7it8n7kZUWxEGoKDYvuRuy46Pqhcc9Q/0zzxJg1X9Mrf89fjopth32ZDqrzNS3kRrSBxTmjEpoxB0RJs6F/Fd0jxnFzhqqjTFdUcWC55lkAcnxUQeLHJavCBZFsarw4Pfg2hHq5xvfpDlRXy1y7e7nIpMNj8ibmVUPIRXtX98JPF8fLUt/sp8iEDZDKkI5Cr+dRdGy5bvj0GUCZ2GkShe2P9G6O9VX+b0/2T10FKiK0JDQrX62sAA7ZOcq/g2+Elw3vQ65DV2fBYGqzTYZDWN7nv6J4XfcnP/b/8fUpcne4OkAgA= + + \ No newline at end of file diff --git a/Disco.Data/Migrations/Configuration.cs b/Disco.Data/Migrations/Configuration.cs index 6cdabeb6..25c0b270 100644 --- a/Disco.Data/Migrations/Configuration.cs +++ b/Disco.Data/Migrations/Configuration.cs @@ -13,9 +13,9 @@ namespace Disco.Data.Migrations AutomaticMigrationsEnabled = false; } - protected override void Seed(DiscoDataContext context) + protected override void Seed(DiscoDataContext Database) { - context.SeedDatabase(); + Database.SeedDatabase(); } } } diff --git a/Disco.Data/Migrations/DiscoDataMigrator.cs b/Disco.Data/Migrations/DiscoDataMigrator.cs index 0148b6d4..5b9dae75 100644 --- a/Disco.Data/Migrations/DiscoDataMigrator.cs +++ b/Disco.Data/Migrations/DiscoDataMigrator.cs @@ -49,12 +49,12 @@ namespace Disco.Data.Migrations public static void SeedDatabase() { // Seed/Update Database - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - dbContext.SeedDatabase(); + database.SeedDatabase(); try { - dbContext.SaveChanges(); + database.SaveChanges(); } catch (Exception ex) { diff --git a/Disco.Data/Properties/AssemblyInfo.cs b/Disco.Data/Properties/AssemblyInfo.cs index 9ccb1356..67c11b3c 100644 --- a/Disco.Data/Properties/AssemblyInfo.cs +++ b/Disco.Data/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2249")] -[assembly: AssemblyFileVersion("1.2.0725.2249")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1541")] +[assembly: AssemblyFileVersion("1.2.1001.1541")] \ No newline at end of file diff --git a/Disco.Data/Repository/DiscoDataContext.cs b/Disco.Data/Repository/DiscoDataContext.cs index fa939189..73d84d7a 100644 --- a/Disco.Data/Repository/DiscoDataContext.cs +++ b/Disco.Data/Repository/DiscoDataContext.cs @@ -23,6 +23,7 @@ namespace Disco.Data.Repository public virtual DbSet Users { get; set; } public virtual DbSet UserAttachments { get; set; } + public virtual DbSet AuthorizationRoles { get; set; } public virtual DbSet DeviceUserAssignments { get; set; } diff --git a/Disco.Data/Repository/DiscoDataContextInitializer.cs b/Disco.Data/Repository/DiscoDataContextInitializer.cs deleted file mode 100644 index aabb3b52..00000000 --- a/Disco.Data/Repository/DiscoDataContextInitializer.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Shouldn't Need this => Moved to Entity Migrations... - -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Text; -//using System.Data.Entity; - -//namespace Disco.Data.Repository -//{ -// class DiscoDataContextInitializer : CreateDatabaseIfNotExists -// { -// protected override void Seed(DiscoDataContext context) -// { -// context.SeedDatabase(); -// context.SaveChanges(); -// } -// } -//} diff --git a/Disco.Data/Repository/DiscoDataSeeder.cs b/Disco.Data/Repository/DiscoDataSeeder.cs index c9878f1b..54b3218b 100644 --- a/Disco.Data/Repository/DiscoDataSeeder.cs +++ b/Disco.Data/Repository/DiscoDataSeeder.cs @@ -8,224 +8,224 @@ namespace Disco.Data.Repository { public static class DiscoDataSeeder { - public static void SeedDatabase(this DiscoDataContext context) + public static void SeedDatabase(this DiscoDataContext Database) { - context.SeedDeploymentId(); - context.SeedDeviceModels(); - context.SeedDeviceProfiles(); - context.SeedJobTypes(); - context.SeedJobSubTypes(); + Database.SeedDeploymentId(); + Database.SeedDeviceModels(); + Database.SeedDeviceProfiles(); + Database.SeedJobTypes(); + Database.SeedJobSubTypes(); } - public static void SeedDeploymentId(this DiscoDataContext context) + public static void SeedDeploymentId(this DiscoDataContext Database) { - if (context.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0) + if (Database.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0) { var deploymentId = Guid.NewGuid().ToString("D"); - context.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId }); + Database.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId }); } } - public static void SeedJobTypes(this DiscoDataContext context) + public static void SeedJobTypes(this DiscoDataContext Database) { - if (context.JobTypes.Count() == 0) + if (Database.JobTypes.Count() == 0) { - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" }); + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" }); } // 2012-05-22 #region "User Management" Added - if (context.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0) - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" }); + if (Database.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0) + Database.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" }); #endregion // End } - public static void SeedDeviceModels(this DiscoDataContext context) + public static void SeedDeviceModels(this DiscoDataContext Database) { - if (context.DeviceModels.Count() == 0) + if (Database.DeviceModels.Count() == 0) { - context.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" }); + Database.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" }); } - UpdateDeviceModelConfiguration(context); + UpdateDeviceModelConfiguration(Database); // Removed: 2013-01-14 G# //UpdateDeviceModelImageStorage(context); // Added: 2013-02-07 G# - UpdateDeviceModelDuplicates(context); + UpdateDeviceModelDuplicates(Database); } - public static void SeedDeviceProfiles(this DiscoDataContext context) + public static void SeedDeviceProfiles(this DiscoDataContext Database) { - if (context.DeviceProfiles.Count() == 0) + if (Database.DeviceProfiles.Count() == 0) { - context.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" }); + Database.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" }); } } - public static void SeedJobSubTypes(this DiscoDataContext context) + public static void SeedJobSubTypes(this DiscoDataContext Database) { - if (context.JobSubTypes.Count() == 0) + if (Database.JobSubTypes.Count() == 0) { - context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" }); - context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" }); - context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" }); - context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" }); - context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" }); - context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" }); - context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" }); - context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" }); - context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" }); - context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" }); - context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" }); - context.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" }); - context.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" }); - context.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" }); - context.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" }); - context.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" }); - context.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" }); - context.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" }); - context.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" }); - context.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" }); - context.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" }); - context.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" }); - context.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" }); - context.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" }); - context.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" }); - context.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" }); - context.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" }); - context.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" }); - context.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" }); - context.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" }); - context.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" }); - context.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" }); - context.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" }); - context.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" }); - context.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" }); + Database.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" }); + Database.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" }); + Database.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" }); + Database.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" }); + Database.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" }); + Database.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" }); + Database.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" }); + Database.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" }); + Database.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" }); + Database.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" }); + Database.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" }); + Database.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" }); + Database.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" }); + Database.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" }); + Database.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" }); + Database.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" }); + Database.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" }); + Database.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" }); + Database.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" }); + Database.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" }); + Database.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" }); + Database.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" }); + Database.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" }); + Database.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" }); + Database.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" }); + Database.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" }); + Database.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" }); + Database.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" }); + Database.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" }); + Database.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" }); + Database.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" }); + Database.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" }); + Database.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" }); } // Feature Request 2012-04-27 by Elijah: https://disco.uservoice.com/forums/159707-feedback/suggestions/2803945-customisable-job-sub-types #region "Optical Drive" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" }); #endregion // End Feature Request // 2012-05-22 #region "User Management" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0) + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0) { - context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement }); - context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact }); + Database.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement }); + Database.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact }); } #endregion // End // 2012-05-29 - Audits #region "Audit" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" }); #endregion // End // Feature Request 2012-06-16 by James: https://disco.uservoice.com/forums/159707-feedback/suggestions/3002911-add-in-microphone-in-hardware-warranty-and-non-war #region "Microphone" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" }); #endregion // End Feature Request // Feature Request 2013-05-16 by Michael #region "Bezel - Case Bottom Load Cover" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "BezelCaseBottomCover") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom Load Cover" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "BezelCaseBottomCover") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom Load Cover" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "BezelCaseBottomCover") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom Load Cover" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "BezelCaseBottomCover") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottomCover", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom Load Cover" }); #endregion // End Feature Request // Feature Request https://github.com/garysharp/Disco/issues/1 #region "Device Stolen/Lost" - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceStolen") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "DeviceStolen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Stolen" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceLost") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "DeviceLost", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Lost" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceStolen") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "DeviceStolen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Stolen" }); + if (Database.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "DeviceLost") == 0) + Database.JobSubTypes.Add(new JobSubType { Id = "DeviceLost", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Device Lost" }); #endregion // End Feature Request } - private static void UpdateDeviceModelConfiguration(this DiscoDataContext context) + private static void UpdateDeviceModelConfiguration(this DiscoDataContext Database) { - if (context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0) + if (Database.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0) { - var configurationItems = context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList(); + var configurationItems = Database.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList(); - var deviceProfiles = context.DeviceProfiles.ToDictionary(dp => dp.Id); + var deviceProfiles = Database.DeviceProfiles.ToDictionary(dp => dp.Id); foreach (var configurationItem in configurationItems) { int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1)); @@ -254,47 +254,19 @@ namespace Disco.Data.Repository } } // Remove from DB - context.ConfigurationItems.Remove(configurationItem); + Database.ConfigurationItems.Remove(configurationItem); } } } - // Removed: 2013-01-14 G# - // private static void UpdateDeviceModelImageStorage(this DiscoDataContext dbContext) - // { - //#pragma warning disable 0618 - // var updateModels = dbContext.DeviceModels.Where(dm => dm.Image != null); - // if (updateModels.Count() > 0) - // { - // var dataStoreLocation = dbContext.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault(); - // if (!string.IsNullOrEmpty(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation)) - // { - // var deviceModelImagesLocation = System.IO.Path.Combine(dataStoreLocation, "DeviceModelImages"); - // if (!System.IO.Directory.Exists(deviceModelImagesLocation)) - // System.IO.Directory.CreateDirectory(deviceModelImagesLocation); - // foreach (var model in updateModels) - // { - // var modelpath = System.IO.Path.Combine(deviceModelImagesLocation, string.Format("{0}.png", model.Id)); - - // if (model.Image != null && model.Image.Length > 0) - // { - // System.IO.File.WriteAllBytes(modelpath, model.Image); - // } - // model.Image = null; - // } - // } - // } - //#pragma warning restore 0618 - // } - // Added: 2013-02-07 G# // Fix previous problem with duplicate device models being created if new devices enrol at the same time // http://www.discoict.com.au/forum/support/2013/2/duplicate-device-models.aspx // Thanks to Michael Vorster for reporting this problem. - private static void UpdateDeviceModelDuplicates(this DiscoDataContext dbContext) + private static void UpdateDeviceModelDuplicates(this DiscoDataContext Database) { - var deviceModels = dbContext.DeviceModels.ToList(); + var deviceModels = Database.DeviceModels.ToList(); var duplicateModels = deviceModels.GroupBy(g => string.Format("{0}|{1}", g.Manufacturer, g.Model)).Where(g => g.Count() > 1); foreach (var duplicateModel in duplicateModels) { @@ -302,7 +274,7 @@ namespace Disco.Data.Repository foreach (var redundantModel in duplicateModel.Where(m => m != primaryModel)) { - foreach (var affectedDevice in dbContext.Devices.Where(d => d.DeviceModelId == redundantModel.Id)) + foreach (var affectedDevice in Database.Devices.Where(d => d.DeviceModelId == redundantModel.Id)) { affectedDevice.DeviceModelId = primaryModel.Id; } diff --git a/Disco.Data/Repository/Monitor/RepositoryMonitor.cs b/Disco.Data/Repository/Monitor/RepositoryMonitor.cs index fdcd6ff7..dd6c1c8a 100644 --- a/Disco.Data/Repository/Monitor/RepositoryMonitor.cs +++ b/Disco.Data/Repository/Monitor/RepositoryMonitor.cs @@ -21,17 +21,17 @@ namespace Disco.Data.Repository.Monitor public static Subject StreamBeforeCommit { get { return streamBefore; } } public static Subject StreamAfterCommit { get { return streamAfter; } } - internal static RepositoryMonitorEvent[] BeforeSaveChanges(DiscoDataContext dbContext) + internal static RepositoryMonitorEvent[] BeforeSaveChanges(DiscoDataContext Database) { - var contextStateManager = ((IObjectContextAdapter)dbContext).ObjectContext.ObjectStateManager; + var contextStateManager = ((IObjectContextAdapter)Database).ObjectContext.ObjectStateManager; - dbContext.ChangeTracker.DetectChanges(); - var changes = dbContext.ChangeTracker.Entries().Where(entry => entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Deleted || entry.State == System.Data.EntityState.Modified); + Database.ChangeTracker.DetectChanges(); + var changes = Database.ChangeTracker.Entries().Where(entry => entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Deleted || entry.State == System.Data.EntityState.Modified); var events = changes.Select(entryState => { ObjectStateEntry stateEntry = contextStateManager.GetObjectStateEntry(entryState.Entity); - var monitorEvent = EventFromEntryState(dbContext, entryState, stateEntry); + var monitorEvent = EventFromEntryState(Database, entryState, stateEntry); // Push to Stream streamBefore.OnNext(monitorEvent); @@ -41,7 +41,7 @@ namespace Disco.Data.Repository.Monitor return events; } - internal static void AfterSaveChanges(DiscoDataContext dbContext, IEnumerable changes) + internal static void AfterSaveChanges(DiscoDataContext Database, IEnumerable changes) { foreach (var change in changes) { @@ -88,7 +88,7 @@ namespace Disco.Data.Repository.Monitor deferredAction.Invoke(monitorEvent); } - internal static RepositoryMonitorEvent EventFromEntryState(DiscoDataContext dbContext, DbEntityEntry entityEntry, ObjectStateEntry entryState) + internal static RepositoryMonitorEvent EventFromEntryState(DiscoDataContext Database, DbEntityEntry entityEntry, ObjectStateEntry entryState) { RepositoryMonitorEventType eventType; string[] modifiedProperties = null; @@ -135,7 +135,7 @@ namespace Disco.Data.Repository.Monitor EntityKey = entityKey, EntityType = entityType, ModifiedProperties = modifiedProperties, - dbContext = dbContext, + Database = Database, dbEntityState = entityEntry, objectEntryState = entryState }; diff --git a/Disco.Data/Repository/Monitor/RepositoryMonitorEvent.cs b/Disco.Data/Repository/Monitor/RepositoryMonitorEvent.cs index 467ff817..36e89136 100644 --- a/Disco.Data/Repository/Monitor/RepositoryMonitorEvent.cs +++ b/Disco.Data/Repository/Monitor/RepositoryMonitorEvent.cs @@ -21,7 +21,7 @@ namespace Disco.Data.Repository.Monitor internal List> executeAfterCommit; [JsonIgnore] - public DiscoDataContext dbContext { get; set; } + public DiscoDataContext Database { get; set; } public RepositoryMonitorEventType EventType { get; set; } diff --git a/Disco.Models/Authorization/IAuthorizationToken.cs b/Disco.Models/Authorization/IAuthorizationToken.cs new file mode 100644 index 00000000..39ef4e4f --- /dev/null +++ b/Disco.Models/Authorization/IAuthorizationToken.cs @@ -0,0 +1,26 @@ +using Disco.Models.Repository; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Authorization +{ + public interface IAuthorizationToken + { + User User { get; set; } + List GroupMembership { get; set; } + List RoleTokens { get; set; } + + bool HasAny(params string[] ClaimKeys); + bool HasAny(IEnumerable ClaimKeys); + bool HasAll(params string[] ClaimKeys); + bool HasAll(IEnumerable ClaimKeys); + bool Has(string ClaimKey); + + void Require(string ClaimKey); + void RequireAll(params string[] ClaimKeys); + void RequireAny(params string[] ClaimKeys); + } +} diff --git a/Disco.Models/Authorization/IClaimNavigatorItem.cs b/Disco.Models/Authorization/IClaimNavigatorItem.cs new file mode 100644 index 00000000..1900869a --- /dev/null +++ b/Disco.Models/Authorization/IClaimNavigatorItem.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Authorization +{ + public interface IClaimNavigatorItem + { + string Key { get; } + string Name { get; } + string Description { get; } + bool Hidden { get; } + + List Children { get; } + bool IsGroup { get; } + bool? Value { get; } + } +} diff --git a/Disco.Models/Authorization/IRoleToken.cs b/Disco.Models/Authorization/IRoleToken.cs new file mode 100644 index 00000000..a209e3bf --- /dev/null +++ b/Disco.Models/Authorization/IRoleToken.cs @@ -0,0 +1,15 @@ +using Disco.Models.Repository; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Authorization +{ + public interface IRoleToken + { + AuthorizationRole Role { get; set; } + List SubjectIds { get; set; } + } +} diff --git a/Disco.Models/BI/Config/OrganisationAddress.cs b/Disco.Models/BI/Config/OrganisationAddress.cs index 391f2ec3..7b4dc69b 100644 --- a/Disco.Models/BI/Config/OrganisationAddress.cs +++ b/Disco.Models/BI/Config/OrganisationAddress.cs @@ -34,7 +34,7 @@ namespace Disco.Models.BI.Config public string ToConfigurationEntry() { StringBuilder entryBuilder = new StringBuilder(); - + entryBuilder.AppendLine(Name.Trim()); entryBuilder.AppendLine(Address.Trim()); entryBuilder.AppendLine(Suburb.Trim()); @@ -46,7 +46,7 @@ namespace Disco.Models.BI.Config { entryBuilder.AppendLine(ShortName.Trim()); } - + return entryBuilder.ToString(); } @@ -70,5 +70,9 @@ namespace Disco.Models.BI.Config throw new ArgumentException("Invalid Configuration Address Entry", "entry"); } + public override string ToString() + { + return string.Format("{0} ({1})", this.Name, this.ShortName); + } } } diff --git a/Disco.Models/Disco.Models.csproj b/Disco.Models/Disco.Models.csproj index 83e4f38f..48e280da 100644 --- a/Disco.Models/Disco.Models.csproj +++ b/Disco.Models/Disco.Models.csproj @@ -45,6 +45,9 @@ + + + @@ -72,7 +75,9 @@ + + @@ -98,7 +103,11 @@ + + + + diff --git a/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryGroup.cs b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryGroup.cs new file mode 100644 index 00000000..4f88d54e --- /dev/null +++ b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryGroup.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Interop.ActiveDirectory +{ + public class ActiveDirectoryGroup : IActiveDirectoryObject + { + public string Name { get; set; } + public string DistinguishedName { get; set; } + public string SamAccountName { get; set; } + public string SecurityIdentifier { get; set; } + public string CommonName { get; set; } + + public List MemberOf { get; set; } + } +} diff --git a/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryMachineAccount.cs b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryMachineAccount.cs index 5654fe6c..bf4ac261 100644 --- a/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryMachineAccount.cs +++ b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryMachineAccount.cs @@ -6,37 +6,24 @@ using Disco.Models.Repository; namespace Disco.Models.Interop.ActiveDirectory { - public class ActiveDirectoryMachineAccount + public class ActiveDirectoryMachineAccount : IActiveDirectoryObject { public string DistinguishedName { get; set; } public string DnsName { get; set; } public string Domain { get; set; } public string Name { get; set; } public Guid NetbootGUID { get; set; } - public string ObjectSid { get; set; } + public string SecurityIdentifier { get; set; } public string Path { get; set; } - public string sAMAccountName { get; set; } + public string SamAccountName { get; set; } public bool IsCriticalSystemObject { get; set; } public Dictionary LoadedProperties { get; set; } - public string ParentDistinguishedName - { - get - { - // Determine Parent - if (!string.IsNullOrWhiteSpace(DistinguishedName)) - return DistinguishedName.Substring(0, DistinguishedName.IndexOf(",DC=")).Substring(DistinguishedName.IndexOf(",") + 1); - else - return null; - } - } - public User ToRepositoryUser() { return new User { - Id = this.sAMAccountName, - Type = "Computer", + Id = this.SamAccountName, DisplayName = this.Name }; } diff --git a/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryUserAccount.cs b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryUserAccount.cs index d0db5827..7ba9ec5d 100644 --- a/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryUserAccount.cs +++ b/Disco.Models/Interop/ActiveDirectory/ActiveDirectoryUserAccount.cs @@ -6,7 +6,7 @@ using Disco.Models.Repository; namespace Disco.Models.Interop.ActiveDirectory { - public class ActiveDirectoryUserAccount + public class ActiveDirectoryUserAccount : IActiveDirectoryObject { public string DisplayName { get; set; } public string DistinguishedName { get; set; } @@ -15,25 +15,23 @@ namespace Disco.Models.Interop.ActiveDirectory public string GivenName { get; set; } public List Groups { get; set; } public string Name { get; set; } - public string ObjectSid { get; set; } + public string SecurityIdentifier { get; set; } public string Path { get; set; } public string Phone { get; set; } - public string sAMAccountName { get; set; } + public string SamAccountName { get; set; } public string Surname { get; set; } - public string Type { get; set; } public Dictionary LoadedProperties { get; set; } public User ToRepositoryUser() { return new User { - Id = this.sAMAccountName, + Id = this.SamAccountName, DisplayName = this.DisplayName, Surname = this.Surname, GivenName = this.GivenName, EmailAddress = this.Email, PhoneNumber = this.Phone, - Type = this.Type }; } diff --git a/Disco.Models/Interop/ActiveDirectory/IActiveDirectoryObject.cs b/Disco.Models/Interop/ActiveDirectory/IActiveDirectoryObject.cs new file mode 100644 index 00000000..15db7abf --- /dev/null +++ b/Disco.Models/Interop/ActiveDirectory/IActiveDirectoryObject.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Interop.ActiveDirectory +{ + public interface IActiveDirectoryObject + { + string DistinguishedName { get; set; } + string SecurityIdentifier { get; set; } + + string SamAccountName { get; set; } + + string Name { get; set; } + } +} diff --git a/Disco.Models/Properties/AssemblyInfo.cs b/Disco.Models/Properties/AssemblyInfo.cs index d27853eb..fedaa987 100644 --- a/Disco.Models/Properties/AssemblyInfo.cs +++ b/Disco.Models/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2249")] -[assembly: AssemblyFileVersion("1.2.0725.2249")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1541")] +[assembly: AssemblyFileVersion("1.2.1001.1541")] \ No newline at end of file diff --git a/Disco.Models/Repository/User/AuthorizationRole.cs b/Disco.Models/Repository/User/AuthorizationRole.cs new file mode 100644 index 00000000..9ced2ca0 --- /dev/null +++ b/Disco.Models/Repository/User/AuthorizationRole.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.Repository +{ + public class AuthorizationRole + { + [Key] + public int Id { get; set; } + [Required, StringLength(100)] + public string Name { get; set; } + + public string SubjectIds { get; set; } + + public string ClaimsJson { get; set; } + } +} diff --git a/Disco.Models/Repository/User/User.cs b/Disco.Models/Repository/User/User.cs index a6f338c7..544fcf61 100644 --- a/Disco.Models/Repository/User/User.cs +++ b/Disco.Models/Repository/User/User.cs @@ -19,8 +19,6 @@ namespace Disco.Models.Repository [StringLength(200)] public string GivenName { get; set; } - [StringLength(8)] - public string Type { get; set; } [StringLength(100)] public string PhoneNumber { get; set; } [StringLength(150)] @@ -32,17 +30,6 @@ namespace Disco.Models.Repository [InverseProperty("UserId")] public virtual IList Jobs { get; set; } - //#region Helper Members - //[NotMapped, XmlIgnore, ScriptIgnore] - //public List CurrentDeviceUserAssignments - //{ - // get - // { - // return this.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).ToList(); - // } - //} - //#endregion - public override string ToString() { return string.Format("{0} ({1})", this.DisplayName, this.Id); @@ -63,17 +50,6 @@ namespace Disco.Models.Repository this.EmailAddress = u.EmailAddress; if (this.PhoneNumber != u.PhoneNumber) this.PhoneNumber = u.PhoneNumber; - if (this.Type != u.Type) - this.Type = u.Type; } - - public static class Types - { - public const string Admin = "Admin"; - public const string Computer = "Computer"; - public const string Staff = "Staff"; - public const string Student = "Student"; - } - } } diff --git a/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleCreateModel.cs b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleCreateModel.cs new file mode 100644 index 00000000..a73a6a11 --- /dev/null +++ b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleCreateModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.UI.Config.AuthorizationRole +{ + public interface ConfigAuthorizationRoleCreateModel : BaseUIModel + { + Models.Repository.AuthorizationRole AuthorizationRole { get; set; } + } +} diff --git a/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleIndexModel.cs b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleIndexModel.cs new file mode 100644 index 00000000..f0ee1e97 --- /dev/null +++ b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleIndexModel.cs @@ -0,0 +1,14 @@ +using Disco.Models.Authorization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.UI.Config.AuthorizationRole +{ + public interface ConfigAuthorizationRoleIndexModel : BaseUIModel + { + List Tokens { get; set; } + } +} diff --git a/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleShowModel.cs b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleShowModel.cs new file mode 100644 index 00000000..e3aa4b9b --- /dev/null +++ b/Disco.Models/UI/Config/AuthorizationRole/ConfigAuthorizationRoleShowModel.cs @@ -0,0 +1,14 @@ +using Disco.Models.Authorization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Models.UI.Config.AuthorizationRole +{ + public interface ConfigAuthorizationRoleShowModel : BaseUIModel + { + IRoleToken Token { get; set; } + } +} diff --git a/Disco.Models/UI/Config/DeviceBatch/ConfigDeviceBatchShowModel.cs b/Disco.Models/UI/Config/DeviceBatch/ConfigDeviceBatchShowModel.cs index 6344a51d..d4b0c6ec 100644 --- a/Disco.Models/UI/Config/DeviceBatch/ConfigDeviceBatchShowModel.cs +++ b/Disco.Models/UI/Config/DeviceBatch/ConfigDeviceBatchShowModel.cs @@ -9,6 +9,9 @@ namespace Disco.Models.UI.Config.DeviceBatch public interface ConfigDeviceBatchShowModel : BaseUIModel { Disco.Models.Repository.DeviceBatch DeviceBatch { get; set; } + + Disco.Models.Repository.DeviceModel DefaultDeviceModel { get; set; } + List DeviceModels { get; set; } List DeviceModelMembers { get; set; } diff --git a/Disco.Models/UI/Config/DeviceProfile/ConfigDeviceProfileShowModel.cs b/Disco.Models/UI/Config/DeviceProfile/ConfigDeviceProfileShowModel.cs index c9dd868f..59761b64 100644 --- a/Disco.Models/UI/Config/DeviceProfile/ConfigDeviceProfileShowModel.cs +++ b/Disco.Models/UI/Config/DeviceProfile/ConfigDeviceProfileShowModel.cs @@ -9,6 +9,8 @@ namespace Disco.Models.UI.Config.DeviceProfile public interface ConfigDeviceProfileShowModel : BaseUIModel { Disco.Models.Repository.DeviceProfile DeviceProfile { get; set; } + Disco.Models.BI.Config.OrganisationAddress DefaultOrganisationAddress { get; set; } + List OrganisationAddresses { get; set; } int DeviceCount { get; set; } diff --git a/Disco.Models/UI/User/UserShowModel.cs b/Disco.Models/UI/User/UserShowModel.cs index 8c54743b..c8854c3b 100644 --- a/Disco.Models/UI/User/UserShowModel.cs +++ b/Disco.Models/UI/User/UserShowModel.cs @@ -1,4 +1,5 @@ -using System; +using Disco.Models.Authorization; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,5 +12,6 @@ namespace Disco.Models.UI.User Disco.Models.Repository.User User { get; set; } Disco.Models.BI.Job.JobTableModel Jobs { get; set; } List DocumentTemplates { get; set; } + IClaimNavigatorItem ClaimNavigator { get; set; } } } diff --git a/Disco.Services/Authorization/AccessDeniedException.cs b/Disco.Services/Authorization/AccessDeniedException.cs new file mode 100644 index 00000000..05a97a1e --- /dev/null +++ b/Disco.Services/Authorization/AccessDeniedException.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization +{ + public class AccessDeniedException : Exception + { + private string _message { get; set; } + + public AccessDeniedException(string Message) + { + this._message = Message; + } + + public override string Message + { + get + { + if (this._message == null) + { + return "Your account does not have the required permission to access this Disco feature."; + } + else + { + return this._message; + } + } + } + } +} diff --git a/Disco.Services/Authorization/AuthorizationToken.cs b/Disco.Services/Authorization/AuthorizationToken.cs new file mode 100644 index 00000000..a9812c56 --- /dev/null +++ b/Disco.Services/Authorization/AuthorizationToken.cs @@ -0,0 +1,161 @@ +using Disco.Models.Authorization; +using Disco.Models.Repository; +using Disco.Services.Authorization.Roles; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization +{ + public class AuthorizationToken : IAuthorizationToken + { + public User User { get; set; } + public List GroupMembership { get; set; } + public List RoleTokens { get; set; } + + #region Token Builders + + public static AuthorizationToken BuildToken(User User, List GroupMembership) + { + return new AuthorizationToken() + { + User = User, + GroupMembership = GroupMembership, + RoleTokens = RoleCache.GetRoleTokens(GroupMembership, User) + }; + } + + public static AuthorizationToken BuildComputerAccountToken(User User) + { + return new AuthorizationToken() + { + User = User, + GroupMembership = new List(), + RoleTokens = new List() + { + (IRoleToken)RoleCache.GetRoleToken(RoleCache.ComputerAccountTokenId) + } + }; + } + + #endregion + + #region Token Accessors + + internal const string RequireAuthenticationMessage = "This Disco feature requires authentication."; + internal const string RequireDiscoAuthorizationMessage = "Your account does not have the required permission to access this Disco feature. This feature requires your account to be included in at least one Disco Authorization Role."; + internal const string RequireMessageTemplate = "Your account does not have the required permission ({0}) to access this Disco feature."; + internal const string RequireAllMessageTemplate = "Your account does not have the required permission to access this Disco feature. This feature requires permission for: {0}."; + internal const string RequireAnyMessageTemplate = "Your account does not have the required permission to access this Disco feature. This feature requires at least one of these permissions: {0}."; + + internal static string BuildRequireMessage(string ClaimKey) + { + return string.Format(RequireMessageTemplate, Claims.GetClaimDetails(ClaimKey).Item1); + } + internal static string BuildRequireAllMessage(IEnumerable ClaimKeys) + { + var claimFriendlyNames = ClaimKeys.Select(ck => Claims.GetClaimDetails(ck).Item1); + return string.Format(RequireAllMessageTemplate, string.Join("; ", claimFriendlyNames)); + } + internal static string BuildRequireAnyMessage(IEnumerable ClaimKeys) + { + var claimFriendlyNames = ClaimKeys.Select(ck => Claims.GetClaimDetails(ck).Item1); + return string.Format(RequireAnyMessageTemplate, string.Join("; ", claimFriendlyNames)); + } + + /// + /// Checks if token contains at least one of the claims requested. + /// + /// Claim Keys from + /// true if the token satisfies the claim request, otherwise false. + public bool HasAny(params string[] ClaimKeys) + { + return HasAny((IEnumerable)ClaimKeys); + } + + /// + /// Checks if token contains at least one of the claims requested. + /// + /// Claim Keys from + /// true if the token satisfies the claim request, otherwise false. + public bool HasAny(IEnumerable ClaimKeys) + { + return ClaimKeys.Any(ck => Has(Claims.GetClaimAccessor(ck))); + } + + /// + /// Checks if token contains all the claims requested. + /// + /// Claim Keys from + /// true if the token satisfies the claim request, otherwise false. + public bool HasAll(params string[] ClaimKeys) + { + return HasAll((IEnumerable)ClaimKeys); + } + /// + /// Checks if token contains all the claims requested. + /// + /// Claim Keys from + /// true if the token satisfies the claim request, otherwise false. + public bool HasAll(IEnumerable ClaimKeys) + { + return ClaimKeys.All(ck => Has(Claims.GetClaimAccessor(ck))); + } + + /// + /// Checks if token contains the claim requested. + /// + /// Claim Key from + /// true if the token satisfies the claim request, otherwise false. + public bool Has(string ClaimKey) + { + Func claimAccessor = Claims.GetClaimAccessor(ClaimKey); + + return Has(claimAccessor); + } + + /// + /// Checks if token contains the claim requested. + /// + /// A lambda which validates the tokens + /// true if the token satisfies the claim request, otherwise false. + public bool Has(Func ClaimAccessor) + { + return RoleTokens.Any(rt => ClaimAccessor.Invoke(((RoleToken)rt).Claims)); + } + + /// + /// Validates the token contains the claim required. An is thrown if the requirements are not met. + /// + /// Claim Key from + public void Require(string ClaimKey) + { + if (!Has(ClaimKey)) + throw new AccessDeniedException(BuildRequireMessage(ClaimKey)); + } + + /// + /// Validates the token contains all the claims required. An is thrown if the requirements are not met. + /// + /// Claim Keys from + public void RequireAll(params string[] ClaimKeys) + { + if (!HasAll(ClaimKeys)) + throw new AccessDeniedException(BuildRequireAllMessage(ClaimKeys)); + } + + /// + /// Validates the token contains at least one of the claims required. An is thrown if the requirements are not met. + /// + /// Claim Keys from + public void RequireAny(params string[] ClaimKeys) + { + if (!HasAny(ClaimKeys)) + throw new AccessDeniedException(BuildRequireAnyMessage(ClaimKeys)); + } + + #endregion + } +} diff --git a/Disco.Services/Authorization/ClaimNavigatorItem.cs b/Disco.Services/Authorization/ClaimNavigatorItem.cs new file mode 100644 index 00000000..e33cff5f --- /dev/null +++ b/Disco.Services/Authorization/ClaimNavigatorItem.cs @@ -0,0 +1,84 @@ +using Disco.Models.Authorization; +using Disco.Services.Authorization.Roles; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization +{ + public class ClaimNavigatorItem : IClaimNavigatorItem + { + private Func accessor { get; set; } + + public string Key { get; private set; } + public string Name { get; private set; } + public string Description { get; private set; } + public bool Hidden { get; private set; } + + public List Children { get; private set; } + public bool IsGroup { get { return Children != null; } } + + public bool? Value { get; private set; } + + internal ClaimNavigatorItem(string Key, bool Hidden) + { + this.Key = Key; + var details = Claims.GetClaimDetails(Key); + this.Name = details.Item1; + this.Description = details.Item2; + this.accessor = Claims.GetClaimAccessor(Key); + this.Hidden = Hidden; + } + + internal ClaimNavigatorItem(string Key, string Name, string Description, bool Hidden, List Children) + { + this.Key = Key; + this.Name = Name; + this.Description = Description; + + this.Hidden = Hidden; + + this.Children = Children; + } + + private ClaimNavigatorItem() + { + // Private Constructor + } + + public IClaimNavigatorItem BuildClaimTree(RoleClaims RoleClaims) + { + return new ClaimNavigatorItem() + { + Key = this.Key, + Name = this.Name, + Description = this.Description, + Hidden = this.Hidden, + accessor = this.accessor, + Value = this.accessor == null ? (bool?)null : this.accessor(RoleClaims), + Children = this.Children == null ? null : this.Children.Cast().Select(c => c.BuildClaimTree(RoleClaims)).ToList() + }; + } + + public IClaimNavigatorItem BuildClaimTree(IEnumerable RoleClaims) + { + return new ClaimNavigatorItem() + { + Key = this.Key, + Name = this.Name, + Description = this.Description, + Hidden = this.Hidden, + accessor = this.accessor, + Value = this.accessor == null ? (bool?)null : RoleClaims.Any(rc => this.accessor(rc)), + Children = this.Children == null ? null : this.Children.Cast().Select(c => c.BuildClaimTree(RoleClaims)).ToList() + }; + } + + public override string ToString() + { + return string.Format("{0}: {1}={2}", this.Name, this.Key, this.Value); + } + } +} diff --git a/Disco.Services/Authorization/Claims.cs b/Disco.Services/Authorization/Claims.cs new file mode 100644 index 00000000..829f4c91 --- /dev/null +++ b/Disco.Services/Authorization/Claims.cs @@ -0,0 +1,1559 @@ + + + +// +// This file was generated by a T4 template. +// Don't change it directly as your change would get overwritten. Instead, make changes +// to the .tt file (i.e. the T4 template) and save it to regenerate this file. +using Disco.Models.Authorization; +using Disco.Models.Repository; +using Disco.Services.Authorization.Roles; +using System; +using System.Collections.Generic; + +namespace Disco.Services.Authorization +{ + public static class Claims + { + private static Dictionary, Action, string, string>> _roleClaims; + private static ClaimNavigatorItem _claimNavigator; + + static Claims() + { +#region Role Claim Dictionary + _roleClaims = new Dictionary, Action, string, string>>() + { + { "Config.DeviceCertificate.DownloadCertificates", new Tuple, Action, string, string>(c => c.Config.DeviceCertificate.DownloadCertificates, (c, v) => c.Config.DeviceCertificate.DownloadCertificates = v, "Download Certificates", "Can download certificates") }, + { "Config.Enrolment.Configure", new Tuple, Action, string, string>(c => c.Config.Enrolment.Configure, (c, v) => c.Config.Enrolment.Configure = v, "Configure Enrolment", "Can configure device enrolment") }, + { "Config.Enrolment.DownloadBootstrapper", new Tuple, Action, string, string>(c => c.Config.Enrolment.DownloadBootstrapper, (c, v) => c.Config.Enrolment.DownloadBootstrapper = v, "Download Bootstrapper", "Can download the Device Bootstrapper") }, + { "Config.Enrolment.Show", new Tuple, Action, string, string>(c => c.Config.Enrolment.Show, (c, v) => c.Config.Enrolment.Show = v, "Show Enrolment", "Can show device enrolment") }, + { "Config.Enrolment.ShowStatus", new Tuple, Action, string, string>(c => c.Config.Enrolment.ShowStatus, (c, v) => c.Config.Enrolment.ShowStatus = v, "Show Enrolment Status", "Can show the enrolment status") }, + { "Config.DeviceBatch.Configure", new Tuple, Action, string, string>(c => c.Config.DeviceBatch.Configure, (c, v) => c.Config.DeviceBatch.Configure = v, "Configure Device Batches", "Can configure device batches") }, + { "Config.DeviceBatch.Create", new Tuple, Action, string, string>(c => c.Config.DeviceBatch.Create, (c, v) => c.Config.DeviceBatch.Create = v, "Create Device Batches", "Can create device batches") }, + { "Config.DeviceBatch.Delete", new Tuple, Action, string, string>(c => c.Config.DeviceBatch.Delete, (c, v) => c.Config.DeviceBatch.Delete = v, "Delete Device Batches", "Can delete device batches") }, + { "Config.DeviceBatch.Show", new Tuple, Action, string, string>(c => c.Config.DeviceBatch.Show, (c, v) => c.Config.DeviceBatch.Show = v, "Show Device Batches", "Can show device batches") }, + { "Config.DeviceBatch.ShowTimeline", new Tuple, Action, string, string>(c => c.Config.DeviceBatch.ShowTimeline, (c, v) => c.Config.DeviceBatch.ShowTimeline = v, "Show Timeline", "Can show device batch timeline") }, + { "Config.DeviceModel.ConfigureComponents", new Tuple, Action, string, string>(c => c.Config.DeviceModel.ConfigureComponents, (c, v) => c.Config.DeviceModel.ConfigureComponents = v, "Configure Device Model Components", "Can configure device model components") }, + { "Config.DeviceModel.Configure", new Tuple, Action, string, string>(c => c.Config.DeviceModel.Configure, (c, v) => c.Config.DeviceModel.Configure = v, "Configure Device Models", "Can configure device models") }, + { "Config.DeviceModel.Delete", new Tuple, Action, string, string>(c => c.Config.DeviceModel.Delete, (c, v) => c.Config.DeviceModel.Delete = v, "Delete Device Models", "Can delete device models") }, + { "Config.DeviceModel.Show", new Tuple, Action, string, string>(c => c.Config.DeviceModel.Show, (c, v) => c.Config.DeviceModel.Show = v, "Show Device Models", "Can show device models") }, + { "Config.DeviceProfile.ConfigureComputerNameTemplate", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.ConfigureComputerNameTemplate, (c, v) => c.Config.DeviceProfile.ConfigureComputerNameTemplate = v, "Configure Computer Name Templates", "Can configure computer name templates for device profiles") }, + { "Config.DeviceProfile.ConfigureDefaults", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.ConfigureDefaults, (c, v) => c.Config.DeviceProfile.ConfigureDefaults = v, "Configure Default Device Profiles", "Can configure default device profiles") }, + { "Config.DeviceProfile.Configure", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.Configure, (c, v) => c.Config.DeviceProfile.Configure = v, "Configure Device Profiles", "Can configure device profiles") }, + { "Config.DeviceProfile.Create", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.Create, (c, v) => c.Config.DeviceProfile.Create = v, "Create Device Profiles", "Can create device profiles") }, + { "Config.DeviceProfile.Delete", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.Delete, (c, v) => c.Config.DeviceProfile.Delete = v, "Delete Device Profiles", "Can delete device profiles") }, + { "Config.DeviceProfile.Show", new Tuple, Action, string, string>(c => c.Config.DeviceProfile.Show, (c, v) => c.Config.DeviceProfile.Show = v, "Show Device Profiles", "Can show device profiles") }, + { "Config.DocumentTemplate.BulkGenerate", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.BulkGenerate, (c, v) => c.Config.DocumentTemplate.BulkGenerate = v, "Bulk Generate Document Templates", "Can bulk generate document templates") }, + { "Config.DocumentTemplate.Configure", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.Configure, (c, v) => c.Config.DocumentTemplate.Configure = v, "Configure Document Templates", "Can configure document templates") }, + { "Config.DocumentTemplate.ConfigureFilterExpression", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.ConfigureFilterExpression, (c, v) => c.Config.DocumentTemplate.ConfigureFilterExpression = v, "Configure Filter Expression", "Can configure filter expressions for document templates") }, + { "Config.DocumentTemplate.Create", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.Create, (c, v) => c.Config.DocumentTemplate.Create = v, "Create Document Templates", "Can create document templates") }, + { "Config.DocumentTemplate.Delete", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.Delete, (c, v) => c.Config.DocumentTemplate.Delete = v, "Delete Document Templates", "Can delete document templates") }, + { "Config.DocumentTemplate.ShowStatus", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.ShowStatus, (c, v) => c.Config.DocumentTemplate.ShowStatus = v, "Show Document Template Import Status", "Can show the document template import status") }, + { "Config.DocumentTemplate.Show", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.Show, (c, v) => c.Config.DocumentTemplate.Show = v, "Show Document Templates", "Can show document templates") }, + { "Config.DocumentTemplate.UndetectedPages", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.UndetectedPages, (c, v) => c.Config.DocumentTemplate.UndetectedPages = v, "Undetected Pages", "Can show and assign imported documents which were not undetected") }, + { "Config.DocumentTemplate.Upload", new Tuple, Action, string, string>(c => c.Config.DocumentTemplate.Upload, (c, v) => c.Config.DocumentTemplate.Upload = v, "Upload Document Templates", "Can upload document templates") }, + { "Config.Logging.Show", new Tuple, Action, string, string>(c => c.Config.Logging.Show, (c, v) => c.Config.Logging.Show = v, "Show Logging", "Can show logging") }, + { "Config.Plugin.Configure", new Tuple, Action, string, string>(c => c.Config.Plugin.Configure, (c, v) => c.Config.Plugin.Configure = v, "Configure Plugins", "Can configure plugins") }, + { "Config.Plugin.InstallLocal", new Tuple, Action, string, string>(c => c.Config.Plugin.InstallLocal, (c, v) => c.Config.Plugin.InstallLocal = v, "Install/Update Local Plugins", "Can install and update locally uploaded plugins") }, + { "Config.Plugin.Install", new Tuple, Action, string, string>(c => c.Config.Plugin.Install, (c, v) => c.Config.Plugin.Install = v, "Install/Update Plugins", "Can install and update plugins") }, + { "Config.Plugin.Show", new Tuple, Action, string, string>(c => c.Config.Plugin.Show, (c, v) => c.Config.Plugin.Show = v, "Show Plugins", "Can show plugins") }, + { "Config.Plugin.Uninstall", new Tuple, Action, string, string>(c => c.Config.Plugin.Uninstall, (c, v) => c.Config.Plugin.Uninstall = v, "Uninstall Plugins", "Can uninstall plugins") }, + { "Config.System.ConfigureProxy", new Tuple, Action, string, string>(c => c.Config.System.ConfigureProxy, (c, v) => c.Config.System.ConfigureProxy = v, "Configure Proxy Settings", "Can configure the proxy settings") }, + { "Config.System.Show", new Tuple, Action, string, string>(c => c.Config.System.Show, (c, v) => c.Config.System.Show = v, "Show System Configuration", "Can show the system configuration") }, + { "Config.Organisation.ConfigureAddresses", new Tuple, Action, string, string>(c => c.Config.Organisation.ConfigureAddresses, (c, v) => c.Config.Organisation.ConfigureAddresses = v, "Configure Addresses", "Can configure organisation addresses") }, + { "Config.Organisation.ConfigureLogo", new Tuple, Action, string, string>(c => c.Config.Organisation.ConfigureLogo, (c, v) => c.Config.Organisation.ConfigureLogo = v, "Configure Logo", "Can configure the organisation logo") }, + { "Config.Organisation.ConfigureMultiSiteMode", new Tuple, Action, string, string>(c => c.Config.Organisation.ConfigureMultiSiteMode, (c, v) => c.Config.Organisation.ConfigureMultiSiteMode = v, "Configure Multi-Site Mode", "Can configure multi-site mode") }, + { "Config.Organisation.ConfigureName", new Tuple, Action, string, string>(c => c.Config.Organisation.ConfigureName, (c, v) => c.Config.Organisation.ConfigureName = v, "Configure Name", "Can configure the organisation name") }, + { "Config.Organisation.Show", new Tuple, Action, string, string>(c => c.Config.Organisation.Show, (c, v) => c.Config.Organisation.Show = v, "Show Organisation Details", "Can show the organisation details") }, + { "Config.Show", new Tuple, Action, string, string>(c => c.Config.Show, (c, v) => c.Config.Show = v, "Show Configuration", "Can show the configuration menu") }, + { "Job.Lists.AllOpen", new Tuple, Action, string, string>(c => c.Job.Lists.AllOpen, (c, v) => c.Job.Lists.AllOpen = v, "All Open List", "Can show list") }, + { "Job.Lists.AwaitingFinanceAgreementBreach", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingFinanceAgreementBreach, (c, v) => c.Job.Lists.AwaitingFinanceAgreementBreach = v, "Awaiting Finance Agreement Breach List", "Can show list (NOTE: Requires Awaiting Finance List)") }, + { "Job.Lists.AwaitingFinanceCharge", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingFinanceCharge, (c, v) => c.Job.Lists.AwaitingFinanceCharge = v, "Awaiting Finance Charge List", "Can show list (NOTE: Requires Awaiting Finance List)") }, + { "Job.Lists.AwaitingFinanceInsuranceProcessing", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingFinanceInsuranceProcessing, (c, v) => c.Job.Lists.AwaitingFinanceInsuranceProcessing = v, "Awaiting Finance Insurance Processing List", "Can show list (NOTE: Requires Awaiting Finance List)") }, + { "Job.Lists.AwaitingFinance", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingFinance, (c, v) => c.Job.Lists.AwaitingFinance = v, "Awaiting Finance List", "Can show list") }, + { "Job.Lists.AwaitingFinancePayment", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingFinancePayment, (c, v) => c.Job.Lists.AwaitingFinancePayment = v, "Awaiting Finance Payment List", "Can show list (NOTE: Requires Awaiting Finance List)") }, + { "Job.Lists.AwaitingTechnicianAction", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingTechnicianAction, (c, v) => c.Job.Lists.AwaitingTechnicianAction = v, "Awaiting Technician Action List", "Can show list") }, + { "Job.Lists.AwaitingUserAction", new Tuple, Action, string, string>(c => c.Job.Lists.AwaitingUserAction, (c, v) => c.Job.Lists.AwaitingUserAction = v, "Awaiting User Action List", "Can show list") }, + { "Job.Lists.DevicesAwaitingRepair", new Tuple, Action, string, string>(c => c.Job.Lists.DevicesAwaitingRepair, (c, v) => c.Job.Lists.DevicesAwaitingRepair = v, "Devices Awaiting Repair List", "Can show list") }, + { "Job.Lists.DevicesReadyForReturn", new Tuple, Action, string, string>(c => c.Job.Lists.DevicesReadyForReturn, (c, v) => c.Job.Lists.DevicesReadyForReturn = v, "Devices Ready For Return List", "Can show list") }, + { "Job.Lists.Locations", new Tuple, Action, string, string>(c => c.Job.Lists.Locations, (c, v) => c.Job.Lists.Locations = v, "Locations List", "Can show list") }, + { "Job.Lists.LongRunningJobs", new Tuple, Action, string, string>(c => c.Job.Lists.LongRunningJobs, (c, v) => c.Job.Lists.LongRunningJobs = v, "Long Running Jobs List", "Can show list") }, + { "Job.Lists.RecentlyClosed", new Tuple, Action, string, string>(c => c.Job.Lists.RecentlyClosed, (c, v) => c.Job.Lists.RecentlyClosed = v, "Recently Closed List", "Can show list") }, + { "Job.Actions.AddAttachments", new Tuple, Action, string, string>(c => c.Job.Actions.AddAttachments, (c, v) => c.Job.Actions.AddAttachments = v, "Add Attachments", "Can add attachments to jobs") }, + { "Job.Actions.AddLogs", new Tuple, Action, string, string>(c => c.Job.Actions.AddLogs, (c, v) => c.Job.Actions.AddLogs = v, "Add Logs", "Can add job logs") }, + { "Job.Actions.Close", new Tuple, Action, string, string>(c => c.Job.Actions.Close, (c, v) => c.Job.Actions.Close = v, "Close Jobs", "Can close jobs") }, + { "Job.Actions.ConvertHWarToHNWar", new Tuple, Action, string, string>(c => c.Job.Actions.ConvertHWarToHNWar, (c, v) => c.Job.Actions.ConvertHWarToHNWar = v, "Convert HWar Jobs To HNWar", "Can convert warranty jobs to non-warranty jobs") }, + { "Job.Actions.Create", new Tuple, Action, string, string>(c => c.Job.Actions.Create, (c, v) => c.Job.Actions.Create = v, "Create Jobs", "Can create jobs") }, + { "Job.Actions.Delete", new Tuple, Action, string, string>(c => c.Job.Actions.Delete, (c, v) => c.Job.Actions.Delete = v, "Delete Jobs", "Can delete jobs") }, + { "Job.Actions.ForceClose", new Tuple, Action, string, string>(c => c.Job.Actions.ForceClose, (c, v) => c.Job.Actions.ForceClose = v, "Force Close Jobs", "Can force close jobs") }, + { "Job.Actions.GenerateDocuments", new Tuple, Action, string, string>(c => c.Job.Actions.GenerateDocuments, (c, v) => c.Job.Actions.GenerateDocuments = v, "Generate Documents", "Can generate documents for jobs") }, + { "Job.Actions.LogRepair", new Tuple, Action, string, string>(c => c.Job.Actions.LogRepair, (c, v) => c.Job.Actions.LogRepair = v, "Log Repair", "Can log repair for non-warranty jobs") }, + { "Job.Actions.LogWarranty", new Tuple, Action, string, string>(c => c.Job.Actions.LogWarranty, (c, v) => c.Job.Actions.LogWarranty = v, "Log Warranty", "Can log warranty for jobs") }, + { "Job.Actions.RemoveAnyAttachments", new Tuple, Action, string, string>(c => c.Job.Actions.RemoveAnyAttachments, (c, v) => c.Job.Actions.RemoveAnyAttachments = v, "Remove Any Attachments", "Can remove any attachments from jobs") }, + { "Job.Actions.RemoveAnyLogs", new Tuple, Action, string, string>(c => c.Job.Actions.RemoveAnyLogs, (c, v) => c.Job.Actions.RemoveAnyLogs = v, "Remove Any Logs", "Can remove any job logs") }, + { "Job.Actions.RemoveOwnAttachments", new Tuple, Action, string, string>(c => c.Job.Actions.RemoveOwnAttachments, (c, v) => c.Job.Actions.RemoveOwnAttachments = v, "Remove Own Attachments", "Can remove own attachments from jobs") }, + { "Job.Actions.RemoveOwnLogs", new Tuple, Action, string, string>(c => c.Job.Actions.RemoveOwnLogs, (c, v) => c.Job.Actions.RemoveOwnLogs = v, "Remove Own Logs", "Can remove own job logs") }, + { "Job.Actions.Reopen", new Tuple, Action, string, string>(c => c.Job.Actions.Reopen, (c, v) => c.Job.Actions.Reopen = v, "Reopen Jobs", "Can reopen jobs") }, + { "Job.Actions.UpdateSubTypes", new Tuple, Action, string, string>(c => c.Job.Actions.UpdateSubTypes, (c, v) => c.Job.Actions.UpdateSubTypes = v, "Update Sub Types", "Can update sub types for jobs") }, + { "Job.Properties.WarrantyProperties.ExternalCompletedDate", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.ExternalCompletedDate, (c, v) => c.Job.Properties.WarrantyProperties.ExternalCompletedDate = v, "External Completed Date Property", "Can update property") }, + { "Job.Properties.WarrantyProperties.ExternalLoggedDate", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.ExternalLoggedDate, (c, v) => c.Job.Properties.WarrantyProperties.ExternalLoggedDate = v, "External Logged Date Property", "Can update property") }, + { "Job.Properties.WarrantyProperties.ExternalName", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.ExternalName, (c, v) => c.Job.Properties.WarrantyProperties.ExternalName = v, "External Name Property", "Can update property") }, + { "Job.Properties.WarrantyProperties.ExternalReference", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.ExternalReference, (c, v) => c.Job.Properties.WarrantyProperties.ExternalReference = v, "External Reference Property", "Can update property") }, + { "Job.Properties.WarrantyProperties.ProviderDetails", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.ProviderDetails, (c, v) => c.Job.Properties.WarrantyProperties.ProviderDetails = v, "Provider Details", "Can access warranty provider details") }, + { "Job.Properties.WarrantyProperties.WarrantyCompleted", new Tuple, Action, string, string>(c => c.Job.Properties.WarrantyProperties.WarrantyCompleted, (c, v) => c.Job.Properties.WarrantyProperties.WarrantyCompleted = v, "Warranty Completed Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.AccountingChargeAdded", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.AccountingChargeAdded, (c, v) => c.Job.Properties.NonWarrantyProperties.AccountingChargeAdded = v, "Accounting Charge Added Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.AccountingChargePaid", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.AccountingChargePaid, (c, v) => c.Job.Properties.NonWarrantyProperties.AccountingChargePaid = v, "Accounting Charge Paid Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.AccountingChargeRequired", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.AccountingChargeRequired, (c, v) => c.Job.Properties.NonWarrantyProperties.AccountingChargeRequired = v, "Accounting Charge Required Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.AddComponents", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.AddComponents, (c, v) => c.Job.Properties.NonWarrantyProperties.AddComponents = v, "Add Components", "Can add job components (NOTE: Requires Edit Components)") }, + { "Job.Properties.NonWarrantyProperties.EditComponents", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.EditComponents, (c, v) => c.Job.Properties.NonWarrantyProperties.EditComponents = v, "Edit Components", "Can edit and remove job components") }, + { "Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent, (c, v) => c.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent = v, "Insurance Claim Form Sent Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.InsuranceDetails", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.InsuranceDetails, (c, v) => c.Job.Properties.NonWarrantyProperties.InsuranceDetails = v, "Insurance Detail Properties", "Can update insurance detail properties") }, + { "Job.Properties.NonWarrantyProperties.InvoiceReceived", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.InvoiceReceived, (c, v) => c.Job.Properties.NonWarrantyProperties.InvoiceReceived = v, "Invoice Received Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.IsInsuranceClaim", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.IsInsuranceClaim, (c, v) => c.Job.Properties.NonWarrantyProperties.IsInsuranceClaim = v, "Is Insurance Claim Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.PurchaseOrderRaised", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised, (c, v) => c.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised = v, "Purchase Order Raised Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.PurchaseOrderReference", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.PurchaseOrderReference, (c, v) => c.Job.Properties.NonWarrantyProperties.PurchaseOrderReference = v, "Purchase Order Reference Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.PurchaseOrderSent", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.PurchaseOrderSent, (c, v) => c.Job.Properties.NonWarrantyProperties.PurchaseOrderSent = v, "Purchase Order Sent Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.RepairerCompletedDate", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.RepairerCompletedDate, (c, v) => c.Job.Properties.NonWarrantyProperties.RepairerCompletedDate = v, "Repairer Completed Date Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.RepairerLoggedDate", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.RepairerLoggedDate, (c, v) => c.Job.Properties.NonWarrantyProperties.RepairerLoggedDate = v, "Repairer Logged Date Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.RepairerName", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.RepairerName, (c, v) => c.Job.Properties.NonWarrantyProperties.RepairerName = v, "Repairer Name Property", "Can update property") }, + { "Job.Properties.NonWarrantyProperties.RepairerReference", new Tuple, Action, string, string>(c => c.Job.Properties.NonWarrantyProperties.RepairerReference, (c, v) => c.Job.Properties.NonWarrantyProperties.RepairerReference = v, "Repairer Reference Property", "Can update property") }, + { "Job.Properties.DeviceHeldLocation", new Tuple, Action, string, string>(c => c.Job.Properties.DeviceHeldLocation, (c, v) => c.Job.Properties.DeviceHeldLocation = v, "Device Held Location Property", "Can update property") }, + { "Job.Properties.DeviceHeld", new Tuple, Action, string, string>(c => c.Job.Properties.DeviceHeld, (c, v) => c.Job.Properties.DeviceHeld = v, "Device Held Property", "Can update property") }, + { "Job.Properties.DeviceReadyForReturn", new Tuple, Action, string, string>(c => c.Job.Properties.DeviceReadyForReturn, (c, v) => c.Job.Properties.DeviceReadyForReturn = v, "Device Ready For Return Property", "Can update property") }, + { "Job.Properties.DeviceReturned", new Tuple, Action, string, string>(c => c.Job.Properties.DeviceReturned, (c, v) => c.Job.Properties.DeviceReturned = v, "Device Returned Property", "Can update property") }, + { "Job.Properties.ExpectedClosedDate", new Tuple, Action, string, string>(c => c.Job.Properties.ExpectedClosedDate, (c, v) => c.Job.Properties.ExpectedClosedDate = v, "Expected Closed Date Property", "Can update property") }, + { "Job.Properties.Flags", new Tuple, Action, string, string>(c => c.Job.Properties.Flags, (c, v) => c.Job.Properties.Flags = v, "Flags Property", "Can update property") }, + { "Job.Properties.NotWaitingForUserAction", new Tuple, Action, string, string>(c => c.Job.Properties.NotWaitingForUserAction, (c, v) => c.Job.Properties.NotWaitingForUserAction = v, "Not Waiting For User Action Property", "Can update property") }, + { "Job.Properties.WaitingForUserAction", new Tuple, Action, string, string>(c => c.Job.Properties.WaitingForUserAction, (c, v) => c.Job.Properties.WaitingForUserAction = v, "Waiting For User Action Property", "Can update property") }, + { "Job.Types.ShowHMisc", new Tuple, Action, string, string>(c => c.Job.Types.ShowHMisc, (c, v) => c.Job.Types.ShowHMisc = v, "Show Hardware - Miscellaneous Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowHNWar", new Tuple, Action, string, string>(c => c.Job.Types.ShowHNWar, (c, v) => c.Job.Types.ShowHNWar = v, "Show Hardware - Non-Warranty Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowHWar", new Tuple, Action, string, string>(c => c.Job.Types.ShowHWar, (c, v) => c.Job.Types.ShowHWar = v, "Show Hardware - Warranty Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowSApp", new Tuple, Action, string, string>(c => c.Job.Types.ShowSApp, (c, v) => c.Job.Types.ShowSApp = v, "Show Software - Application Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowSOS", new Tuple, Action, string, string>(c => c.Job.Types.ShowSOS, (c, v) => c.Job.Types.ShowSOS = v, "Show Software - Operating System Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowSImg", new Tuple, Action, string, string>(c => c.Job.Types.ShowSImg, (c, v) => c.Job.Types.ShowSImg = v, "Show Software - Reimage Jobs", "Can show jobs of this type") }, + { "Job.Types.ShowUMgmt", new Tuple, Action, string, string>(c => c.Job.Types.ShowUMgmt, (c, v) => c.Job.Types.ShowUMgmt = v, "Show User Management Jobs", "Can show jobs of this type") }, + { "Job.Search", new Tuple, Action, string, string>(c => c.Job.Search, (c, v) => c.Job.Search = v, "Search Jobs", "Can search jobs") }, + { "Job.ShowAttachments", new Tuple, Action, string, string>(c => c.Job.ShowAttachments, (c, v) => c.Job.ShowAttachments = v, "Show Attachments", "Can show job attachments") }, + { "Job.ShowDailyChart", new Tuple, Action, string, string>(c => c.Job.ShowDailyChart, (c, v) => c.Job.ShowDailyChart = v, "Show Daily Opened & Closed", "Can show daily opened & closed chart") }, + { "Job.ShowFlags", new Tuple, Action, string, string>(c => c.Job.ShowFlags, (c, v) => c.Job.ShowFlags = v, "Show Flags", "Can show job flags") }, + { "Job.Show", new Tuple, Action, string, string>(c => c.Job.Show, (c, v) => c.Job.Show = v, "Show Jobs", "Can show jobs") }, + { "Job.ShowLogs", new Tuple, Action, string, string>(c => c.Job.ShowLogs, (c, v) => c.Job.ShowLogs = v, "Show Logs", "Can show job logs") }, + { "Job.ShowNonWarrantyComponents", new Tuple, Action, string, string>(c => c.Job.ShowNonWarrantyComponents, (c, v) => c.Job.ShowNonWarrantyComponents = v, "Show Non-Warranty Components", "Can show non-warranty job components") }, + { "Job.ShowNonWarrantyFinance", new Tuple, Action, string, string>(c => c.Job.ShowNonWarrantyFinance, (c, v) => c.Job.ShowNonWarrantyFinance = v, "Show Non-Warranty Finance", "Can show non-warranty job finance") }, + { "Job.ShowNonWarrantyInsurance", new Tuple, Action, string, string>(c => c.Job.ShowNonWarrantyInsurance, (c, v) => c.Job.ShowNonWarrantyInsurance = v, "Show Non-Warranty Insurance", "Can show non-warranty job insurance") }, + { "Job.ShowNonWarrantyRepairs", new Tuple, Action, string, string>(c => c.Job.ShowNonWarrantyRepairs, (c, v) => c.Job.ShowNonWarrantyRepairs = v, "Show Non-Warranty Repairs", "Can show non-warranty job repairs") }, + { "Job.ShowWarranty", new Tuple, Action, string, string>(c => c.Job.ShowWarranty, (c, v) => c.Job.ShowWarranty = v, "Show Warranty", "Can show job warranty") }, + { "Device.Properties.AssetNumber", new Tuple, Action, string, string>(c => c.Device.Properties.AssetNumber, (c, v) => c.Device.Properties.AssetNumber = v, "Asset Number Property", "Can update property") }, + { "Device.Properties.DeviceBatch", new Tuple, Action, string, string>(c => c.Device.Properties.DeviceBatch, (c, v) => c.Device.Properties.DeviceBatch = v, "Device Batch Property", "Can update property") }, + { "Device.Properties.DeviceProfile", new Tuple, Action, string, string>(c => c.Device.Properties.DeviceProfile, (c, v) => c.Device.Properties.DeviceProfile = v, "Device Profile Property", "Can update property") }, + { "Device.Properties.Location", new Tuple, Action, string, string>(c => c.Device.Properties.Location, (c, v) => c.Device.Properties.Location = v, "Location Property", "Can update property") }, + { "Device.Actions.AddAttachments", new Tuple, Action, string, string>(c => c.Device.Actions.AddAttachments, (c, v) => c.Device.Actions.AddAttachments = v, "Add Attachments", "Can add attachments to devices") }, + { "Device.Actions.AllowUnauthenticatedEnrol", new Tuple, Action, string, string>(c => c.Device.Actions.AllowUnauthenticatedEnrol, (c, v) => c.Device.Actions.AllowUnauthenticatedEnrol = v, "Allow Unauthenticated Enrol", "Can allow devices to enrol without authentication") }, + { "Device.Actions.AssignUser", new Tuple, Action, string, string>(c => c.Device.Actions.AssignUser, (c, v) => c.Device.Actions.AssignUser = v, "Assign User", "Can update the user assignment of devices") }, + { "Device.Actions.Decommission", new Tuple, Action, string, string>(c => c.Device.Actions.Decommission, (c, v) => c.Device.Actions.Decommission = v, "Decommission", "Can decommission devices") }, + { "Device.Actions.Delete", new Tuple, Action, string, string>(c => c.Device.Actions.Delete, (c, v) => c.Device.Actions.Delete = v, "Delete", "Can delete devices") }, + { "Device.Actions.EnrolDevices", new Tuple, Action, string, string>(c => c.Device.Actions.EnrolDevices, (c, v) => c.Device.Actions.EnrolDevices = v, "Enrol Devices", "Can add devices offline and enrol devices with the Bootstrapper") }, + { "Device.Actions.Export", new Tuple, Action, string, string>(c => c.Device.Actions.Export, (c, v) => c.Device.Actions.Export = v, "Export Devices", "Can export devices in a bulk format") }, + { "Device.Actions.GenerateDocuments", new Tuple, Action, string, string>(c => c.Device.Actions.GenerateDocuments, (c, v) => c.Device.Actions.GenerateDocuments = v, "Generate Documents", "Can generate documents for jobs") }, + { "Device.Actions.Import", new Tuple, Action, string, string>(c => c.Device.Actions.Import, (c, v) => c.Device.Actions.Import = v, "Import Devices", "Can bulk import devices") }, + { "Device.Actions.Recommission", new Tuple, Action, string, string>(c => c.Device.Actions.Recommission, (c, v) => c.Device.Actions.Recommission = v, "Recommission", "Can recommission devices") }, + { "Device.Actions.RemoveAnyAttachments", new Tuple, Action, string, string>(c => c.Device.Actions.RemoveAnyAttachments, (c, v) => c.Device.Actions.RemoveAnyAttachments = v, "Remove Any Attachments", "Can remove any attachments from devices") }, + { "Device.Actions.RemoveOwnAttachments", new Tuple, Action, string, string>(c => c.Device.Actions.RemoveOwnAttachments, (c, v) => c.Device.Actions.RemoveOwnAttachments = v, "Remove Own Attachments", "Can remove own attachments from devices") }, + { "Device.Search", new Tuple, Action, string, string>(c => c.Device.Search, (c, v) => c.Device.Search = v, "Search Devices", "Can search devices") }, + { "Device.ShowAssignmentHistory", new Tuple, Action, string, string>(c => c.Device.ShowAssignmentHistory, (c, v) => c.Device.ShowAssignmentHistory = v, "Show Assignment History", "Can show the assignment history for devices") }, + { "Device.ShowAttachments", new Tuple, Action, string, string>(c => c.Device.ShowAttachments, (c, v) => c.Device.ShowAttachments = v, "Show Attachments", "Can show device attachments") }, + { "Device.ShowCertificates", new Tuple, Action, string, string>(c => c.Device.ShowCertificates, (c, v) => c.Device.ShowCertificates = v, "Show Certificates", "Can show certificates associated with devices") }, + { "Device.ShowDetails", new Tuple, Action, string, string>(c => c.Device.ShowDetails, (c, v) => c.Device.ShowDetails = v, "Show Details", "Can show details associated with devices") }, + { "Device.Show", new Tuple, Action, string, string>(c => c.Device.Show, (c, v) => c.Device.Show = v, "Show Devices", "Can show devices") }, + { "Device.ShowJobs", new Tuple, Action, string, string>(c => c.Device.ShowJobs, (c, v) => c.Device.ShowJobs = v, "Show Devices Jobs", "Can show jobs associated with devices") }, + { "User.Actions.AddAttachments", new Tuple, Action, string, string>(c => c.User.Actions.AddAttachments, (c, v) => c.User.Actions.AddAttachments = v, "Add Attachments", "Can add attachments to users") }, + { "User.Actions.GenerateDocuments", new Tuple, Action, string, string>(c => c.User.Actions.GenerateDocuments, (c, v) => c.User.Actions.GenerateDocuments = v, "Generate Documents", "Can generate documents for users") }, + { "User.Actions.RemoveAnyAttachments", new Tuple, Action, string, string>(c => c.User.Actions.RemoveAnyAttachments, (c, v) => c.User.Actions.RemoveAnyAttachments = v, "Remove Any Attachments", "Can remove any attachments from users") }, + { "User.Actions.RemoveOwnAttachments", new Tuple, Action, string, string>(c => c.User.Actions.RemoveOwnAttachments, (c, v) => c.User.Actions.RemoveOwnAttachments = v, "Remove Own Attachments", "Can remove own attachments from users") }, + { "User.Search", new Tuple, Action, string, string>(c => c.User.Search, (c, v) => c.User.Search = v, "Search Users", "Can search users") }, + { "User.ShowAttachments", new Tuple, Action, string, string>(c => c.User.ShowAttachments, (c, v) => c.User.ShowAttachments = v, "Show Attachments", "Can show user attachments") }, + { "User.ShowAssignmentHistory", new Tuple, Action, string, string>(c => c.User.ShowAssignmentHistory, (c, v) => c.User.ShowAssignmentHistory = v, "Show Device Assignment History", "Can show the device assignment history for users") }, + { "User.Show", new Tuple, Action, string, string>(c => c.User.Show, (c, v) => c.User.Show = v, "Show Users", "Can show users") }, + { "User.ShowAuthorization", new Tuple, Action, string, string>(c => c.User.ShowAuthorization, (c, v) => c.User.ShowAuthorization = v, "Show Users Authorization", "Can show authorization permissions associated with users") }, + { "User.ShowJobs", new Tuple, Action, string, string>(c => c.User.ShowJobs, (c, v) => c.User.ShowJobs = v, "Show Users Jobs", "Can show jobs associated with users") }, + { "ComputerAccount", new Tuple, Action, string, string>(c => c.ComputerAccount, (c, v) => c.ComputerAccount = v, "Computer Account", "Represents a computer account") }, + { "DiscoAdminAccount", new Tuple, Action, string, string>(c => c.DiscoAdminAccount, (c, v) => c.DiscoAdminAccount = v, "Disco Administrator Account", "Represents a Disco Administrator account") } + }; +#endregion + +#region Role Claim Navigator + _claimNavigator = + new ClaimNavigatorItem("Claims", "Permissions", "Top-level node for all permissions", false, new List() { + new ClaimNavigatorItem("Config", "Configuration", "Permissions related to Disco Configuration", false, new List() { + new ClaimNavigatorItem("Config.DeviceCertificate", "Device Certificate", "Permissions related to Device Certificates", false, new List() { + new ClaimNavigatorItem("Config.DeviceCertificate.DownloadCertificates", false) + }), + new ClaimNavigatorItem("Config.Enrolment", "Enrolment", "Permissions related to Device Enrolment", false, new List() { + new ClaimNavigatorItem("Config.Enrolment.Configure", false), + new ClaimNavigatorItem("Config.Enrolment.DownloadBootstrapper", false), + new ClaimNavigatorItem("Config.Enrolment.Show", false), + new ClaimNavigatorItem("Config.Enrolment.ShowStatus", false) + }), + new ClaimNavigatorItem("Config.DeviceBatch", "Device Batch", "Permissions related to Device Batches", false, new List() { + new ClaimNavigatorItem("Config.DeviceBatch.Configure", false), + new ClaimNavigatorItem("Config.DeviceBatch.Create", false), + new ClaimNavigatorItem("Config.DeviceBatch.Delete", false), + new ClaimNavigatorItem("Config.DeviceBatch.Show", false), + new ClaimNavigatorItem("Config.DeviceBatch.ShowTimeline", false) + }), + new ClaimNavigatorItem("Config.DeviceModel", "Device Model", "Permissions related to Device Models", false, new List() { + new ClaimNavigatorItem("Config.DeviceModel.ConfigureComponents", false), + new ClaimNavigatorItem("Config.DeviceModel.Configure", false), + new ClaimNavigatorItem("Config.DeviceModel.Delete", false), + new ClaimNavigatorItem("Config.DeviceModel.Show", false) + }), + new ClaimNavigatorItem("Config.DeviceProfile", "Device Profile", "Permissions related to Device Profiles", false, new List() { + new ClaimNavigatorItem("Config.DeviceProfile.ConfigureComputerNameTemplate", false), + new ClaimNavigatorItem("Config.DeviceProfile.ConfigureDefaults", false), + new ClaimNavigatorItem("Config.DeviceProfile.Configure", false), + new ClaimNavigatorItem("Config.DeviceProfile.Create", false), + new ClaimNavigatorItem("Config.DeviceProfile.Delete", false), + new ClaimNavigatorItem("Config.DeviceProfile.Show", false) + }), + new ClaimNavigatorItem("Config.DocumentTemplate", "Document Template", "Permissions related to Document Templates", false, new List() { + new ClaimNavigatorItem("Config.DocumentTemplate.BulkGenerate", false), + new ClaimNavigatorItem("Config.DocumentTemplate.Configure", false), + new ClaimNavigatorItem("Config.DocumentTemplate.ConfigureFilterExpression", false), + new ClaimNavigatorItem("Config.DocumentTemplate.Create", false), + new ClaimNavigatorItem("Config.DocumentTemplate.Delete", false), + new ClaimNavigatorItem("Config.DocumentTemplate.ShowStatus", false), + new ClaimNavigatorItem("Config.DocumentTemplate.Show", false), + new ClaimNavigatorItem("Config.DocumentTemplate.UndetectedPages", false), + new ClaimNavigatorItem("Config.DocumentTemplate.Upload", false) + }), + new ClaimNavigatorItem("Config.Logging", "Logging", "Permissions related to Logging", false, new List() { + new ClaimNavigatorItem("Config.Logging.Show", false) + }), + new ClaimNavigatorItem("Config.Plugin", "Plugin", "Permissions related to Plugins", false, new List() { + new ClaimNavigatorItem("Config.Plugin.Configure", false), + new ClaimNavigatorItem("Config.Plugin.InstallLocal", false), + new ClaimNavigatorItem("Config.Plugin.Install", false), + new ClaimNavigatorItem("Config.Plugin.Show", false), + new ClaimNavigatorItem("Config.Plugin.Uninstall", false) + }), + new ClaimNavigatorItem("Config.System", "System", "Permissions related to System Configuration", false, new List() { + new ClaimNavigatorItem("Config.System.ConfigureProxy", false), + new ClaimNavigatorItem("Config.System.Show", false) + }), + new ClaimNavigatorItem("Config.Organisation", "Organisation Details", "Permissions related to the Organisation Details", false, new List() { + new ClaimNavigatorItem("Config.Organisation.ConfigureAddresses", false), + new ClaimNavigatorItem("Config.Organisation.ConfigureLogo", false), + new ClaimNavigatorItem("Config.Organisation.ConfigureMultiSiteMode", false), + new ClaimNavigatorItem("Config.Organisation.ConfigureName", false), + new ClaimNavigatorItem("Config.Organisation.Show", false) + }), + new ClaimNavigatorItem("Config.Show", false) + }), + new ClaimNavigatorItem("Job", "Job", "Permissions related to Jobs", false, new List() { + new ClaimNavigatorItem("Job.Lists", "Lists", "Permissions related to Job Lists", false, new List() { + new ClaimNavigatorItem("Job.Lists.AllOpen", false), + new ClaimNavigatorItem("Job.Lists.AwaitingFinanceAgreementBreach", false), + new ClaimNavigatorItem("Job.Lists.AwaitingFinanceCharge", false), + new ClaimNavigatorItem("Job.Lists.AwaitingFinanceInsuranceProcessing", false), + new ClaimNavigatorItem("Job.Lists.AwaitingFinance", false), + new ClaimNavigatorItem("Job.Lists.AwaitingFinancePayment", false), + new ClaimNavigatorItem("Job.Lists.AwaitingTechnicianAction", false), + new ClaimNavigatorItem("Job.Lists.AwaitingUserAction", false), + new ClaimNavigatorItem("Job.Lists.DevicesAwaitingRepair", false), + new ClaimNavigatorItem("Job.Lists.DevicesReadyForReturn", false), + new ClaimNavigatorItem("Job.Lists.Locations", false), + new ClaimNavigatorItem("Job.Lists.LongRunningJobs", false), + new ClaimNavigatorItem("Job.Lists.RecentlyClosed", false) + }), + new ClaimNavigatorItem("Job.Actions", "Actions", "Permissions related to Job Actions", false, new List() { + new ClaimNavigatorItem("Job.Actions.AddAttachments", false), + new ClaimNavigatorItem("Job.Actions.AddLogs", false), + new ClaimNavigatorItem("Job.Actions.Close", false), + new ClaimNavigatorItem("Job.Actions.ConvertHWarToHNWar", false), + new ClaimNavigatorItem("Job.Actions.Create", false), + new ClaimNavigatorItem("Job.Actions.Delete", false), + new ClaimNavigatorItem("Job.Actions.ForceClose", false), + new ClaimNavigatorItem("Job.Actions.GenerateDocuments", false), + new ClaimNavigatorItem("Job.Actions.LogRepair", false), + new ClaimNavigatorItem("Job.Actions.LogWarranty", false), + new ClaimNavigatorItem("Job.Actions.RemoveAnyAttachments", false), + new ClaimNavigatorItem("Job.Actions.RemoveAnyLogs", false), + new ClaimNavigatorItem("Job.Actions.RemoveOwnAttachments", false), + new ClaimNavigatorItem("Job.Actions.RemoveOwnLogs", false), + new ClaimNavigatorItem("Job.Actions.Reopen", false), + new ClaimNavigatorItem("Job.Actions.UpdateSubTypes", false) + }), + new ClaimNavigatorItem("Job.Properties", "Job Properties", "Permissions related to Job Properties", false, new List() { + new ClaimNavigatorItem("Job.Properties.WarrantyProperties", "Warranty Properties", "Permissions related to Warranty Job Properties", false, new List() { + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.ExternalCompletedDate", false), + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.ExternalLoggedDate", false), + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.ExternalName", false), + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.ExternalReference", false), + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.ProviderDetails", false), + new ClaimNavigatorItem("Job.Properties.WarrantyProperties.WarrantyCompleted", false) + }), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties", "Non Warranty Properties", "Permissions related to Non-Warranty Job Properties", false, new List() { + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.AccountingChargeAdded", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.AccountingChargePaid", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.AccountingChargeRequired", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.AddComponents", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.EditComponents", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.InsuranceDetails", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.InvoiceReceived", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.IsInsuranceClaim", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.PurchaseOrderRaised", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.PurchaseOrderReference", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.PurchaseOrderSent", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.RepairerCompletedDate", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.RepairerLoggedDate", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.RepairerName", false), + new ClaimNavigatorItem("Job.Properties.NonWarrantyProperties.RepairerReference", false) + }), + new ClaimNavigatorItem("Job.Properties.DeviceHeldLocation", false), + new ClaimNavigatorItem("Job.Properties.DeviceHeld", false), + new ClaimNavigatorItem("Job.Properties.DeviceReadyForReturn", false), + new ClaimNavigatorItem("Job.Properties.DeviceReturned", false), + new ClaimNavigatorItem("Job.Properties.ExpectedClosedDate", false), + new ClaimNavigatorItem("Job.Properties.Flags", false), + new ClaimNavigatorItem("Job.Properties.NotWaitingForUserAction", false), + new ClaimNavigatorItem("Job.Properties.WaitingForUserAction", false) + }), + new ClaimNavigatorItem("Job.Types", "Types", "Permissions related to Job Types", false, new List() { + new ClaimNavigatorItem("Job.Types.ShowHMisc", false), + new ClaimNavigatorItem("Job.Types.ShowHNWar", false), + new ClaimNavigatorItem("Job.Types.ShowHWar", false), + new ClaimNavigatorItem("Job.Types.ShowSApp", false), + new ClaimNavigatorItem("Job.Types.ShowSOS", false), + new ClaimNavigatorItem("Job.Types.ShowSImg", false), + new ClaimNavigatorItem("Job.Types.ShowUMgmt", false) + }), + new ClaimNavigatorItem("Job.Search", false), + new ClaimNavigatorItem("Job.ShowAttachments", false), + new ClaimNavigatorItem("Job.ShowDailyChart", false), + new ClaimNavigatorItem("Job.ShowFlags", false), + new ClaimNavigatorItem("Job.Show", false), + new ClaimNavigatorItem("Job.ShowLogs", false), + new ClaimNavigatorItem("Job.ShowNonWarrantyComponents", false), + new ClaimNavigatorItem("Job.ShowNonWarrantyFinance", false), + new ClaimNavigatorItem("Job.ShowNonWarrantyInsurance", false), + new ClaimNavigatorItem("Job.ShowNonWarrantyRepairs", false), + new ClaimNavigatorItem("Job.ShowWarranty", false) + }), + new ClaimNavigatorItem("Device", "Device", "Permissions related to Devices", false, new List() { + new ClaimNavigatorItem("Device.Properties", "Device Properties", "Permissions related to Device Properties", false, new List() { + new ClaimNavigatorItem("Device.Properties.AssetNumber", false), + new ClaimNavigatorItem("Device.Properties.DeviceBatch", false), + new ClaimNavigatorItem("Device.Properties.DeviceProfile", false), + new ClaimNavigatorItem("Device.Properties.Location", false) + }), + new ClaimNavigatorItem("Device.Actions", "Actions", "Permissions related to Device Actions", false, new List() { + new ClaimNavigatorItem("Device.Actions.AddAttachments", false), + new ClaimNavigatorItem("Device.Actions.AllowUnauthenticatedEnrol", false), + new ClaimNavigatorItem("Device.Actions.AssignUser", false), + new ClaimNavigatorItem("Device.Actions.Decommission", false), + new ClaimNavigatorItem("Device.Actions.Delete", false), + new ClaimNavigatorItem("Device.Actions.EnrolDevices", false), + new ClaimNavigatorItem("Device.Actions.Export", false), + new ClaimNavigatorItem("Device.Actions.GenerateDocuments", false), + new ClaimNavigatorItem("Device.Actions.Import", false), + new ClaimNavigatorItem("Device.Actions.Recommission", false), + new ClaimNavigatorItem("Device.Actions.RemoveAnyAttachments", false), + new ClaimNavigatorItem("Device.Actions.RemoveOwnAttachments", false) + }), + new ClaimNavigatorItem("Device.Search", false), + new ClaimNavigatorItem("Device.ShowAssignmentHistory", false), + new ClaimNavigatorItem("Device.ShowAttachments", false), + new ClaimNavigatorItem("Device.ShowCertificates", false), + new ClaimNavigatorItem("Device.ShowDetails", false), + new ClaimNavigatorItem("Device.Show", false), + new ClaimNavigatorItem("Device.ShowJobs", false) + }), + new ClaimNavigatorItem("User", "User", "Permissions related to Users", false, new List() { + new ClaimNavigatorItem("User.Actions", "Actions", "Permissions related to User Actions", false, new List() { + new ClaimNavigatorItem("User.Actions.AddAttachments", false), + new ClaimNavigatorItem("User.Actions.GenerateDocuments", false), + new ClaimNavigatorItem("User.Actions.RemoveAnyAttachments", false), + new ClaimNavigatorItem("User.Actions.RemoveOwnAttachments", false) + }), + new ClaimNavigatorItem("User.Search", false), + new ClaimNavigatorItem("User.ShowAttachments", false), + new ClaimNavigatorItem("User.ShowAssignmentHistory", false), + new ClaimNavigatorItem("User.Show", false), + new ClaimNavigatorItem("User.ShowAuthorization", false), + new ClaimNavigatorItem("User.ShowJobs", false) + }), + new ClaimNavigatorItem("ComputerAccount", true), + new ClaimNavigatorItem("DiscoAdminAccount", true) + }); +#endregion + } + + public static ClaimNavigatorItem RoleClaimNavigator + { + get { return _claimNavigator; } + } + + public static Func GetClaimAccessor(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return claimFunc.Item1; + } + + public static Action GetClaimSetter(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return claimFunc.Item2; + } + + public static Tuple GetClaimDetails(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return new Tuple(claimFunc.Item3, claimFunc.Item4); + } + + public static RoleClaims BuildClaims(IEnumerable ClaimKeys){ + var c = new RoleClaims(); + foreach (var claimKey in ClaimKeys) + c.Set(claimKey, true); + + return c; + } + + public static RoleClaims AdministratorClaims() { + var c = new RoleClaims(); +#region Set All Administrator Claims + c.Config.DeviceCertificate.DownloadCertificates = true; + c.Config.Enrolment.Configure = true; + c.Config.Enrolment.DownloadBootstrapper = true; + c.Config.Enrolment.Show = true; + c.Config.Enrolment.ShowStatus = true; + c.Config.DeviceBatch.Configure = true; + c.Config.DeviceBatch.Create = true; + c.Config.DeviceBatch.Delete = true; + c.Config.DeviceBatch.Show = true; + c.Config.DeviceBatch.ShowTimeline = true; + c.Config.DeviceModel.ConfigureComponents = true; + c.Config.DeviceModel.Configure = true; + c.Config.DeviceModel.Delete = true; + c.Config.DeviceModel.Show = true; + c.Config.DeviceProfile.ConfigureComputerNameTemplate = true; + c.Config.DeviceProfile.ConfigureDefaults = true; + c.Config.DeviceProfile.Configure = true; + c.Config.DeviceProfile.Create = true; + c.Config.DeviceProfile.Delete = true; + c.Config.DeviceProfile.Show = true; + c.Config.DocumentTemplate.BulkGenerate = true; + c.Config.DocumentTemplate.Configure = true; + c.Config.DocumentTemplate.ConfigureFilterExpression = true; + c.Config.DocumentTemplate.Create = true; + c.Config.DocumentTemplate.Delete = true; + c.Config.DocumentTemplate.ShowStatus = true; + c.Config.DocumentTemplate.Show = true; + c.Config.DocumentTemplate.UndetectedPages = true; + c.Config.DocumentTemplate.Upload = true; + c.Config.Logging.Show = true; + c.Config.Plugin.Configure = true; + c.Config.Plugin.InstallLocal = true; + c.Config.Plugin.Install = true; + c.Config.Plugin.Show = true; + c.Config.Plugin.Uninstall = true; + c.Config.System.ConfigureProxy = true; + c.Config.System.Show = true; + c.Config.Organisation.ConfigureAddresses = true; + c.Config.Organisation.ConfigureLogo = true; + c.Config.Organisation.ConfigureMultiSiteMode = true; + c.Config.Organisation.ConfigureName = true; + c.Config.Organisation.Show = true; + c.Config.Show = true; + c.Job.Lists.AllOpen = true; + c.Job.Lists.AwaitingFinanceAgreementBreach = true; + c.Job.Lists.AwaitingFinanceCharge = true; + c.Job.Lists.AwaitingFinanceInsuranceProcessing = true; + c.Job.Lists.AwaitingFinance = true; + c.Job.Lists.AwaitingFinancePayment = true; + c.Job.Lists.AwaitingTechnicianAction = true; + c.Job.Lists.AwaitingUserAction = true; + c.Job.Lists.DevicesAwaitingRepair = true; + c.Job.Lists.DevicesReadyForReturn = true; + c.Job.Lists.Locations = true; + c.Job.Lists.LongRunningJobs = true; + c.Job.Lists.RecentlyClosed = true; + c.Job.Actions.AddAttachments = true; + c.Job.Actions.AddLogs = true; + c.Job.Actions.Close = true; + c.Job.Actions.ConvertHWarToHNWar = true; + c.Job.Actions.Create = true; + c.Job.Actions.Delete = true; + c.Job.Actions.ForceClose = true; + c.Job.Actions.GenerateDocuments = true; + c.Job.Actions.LogRepair = true; + c.Job.Actions.LogWarranty = true; + c.Job.Actions.RemoveAnyAttachments = true; + c.Job.Actions.RemoveAnyLogs = true; + c.Job.Actions.RemoveOwnAttachments = true; + c.Job.Actions.RemoveOwnLogs = true; + c.Job.Actions.Reopen = true; + c.Job.Actions.UpdateSubTypes = true; + c.Job.Properties.WarrantyProperties.ExternalCompletedDate = true; + c.Job.Properties.WarrantyProperties.ExternalLoggedDate = true; + c.Job.Properties.WarrantyProperties.ExternalName = true; + c.Job.Properties.WarrantyProperties.ExternalReference = true; + c.Job.Properties.WarrantyProperties.ProviderDetails = true; + c.Job.Properties.WarrantyProperties.WarrantyCompleted = true; + c.Job.Properties.NonWarrantyProperties.AccountingChargeAdded = true; + c.Job.Properties.NonWarrantyProperties.AccountingChargePaid = true; + c.Job.Properties.NonWarrantyProperties.AccountingChargeRequired = true; + c.Job.Properties.NonWarrantyProperties.AddComponents = true; + c.Job.Properties.NonWarrantyProperties.EditComponents = true; + c.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent = true; + c.Job.Properties.NonWarrantyProperties.InsuranceDetails = true; + c.Job.Properties.NonWarrantyProperties.InvoiceReceived = true; + c.Job.Properties.NonWarrantyProperties.IsInsuranceClaim = true; + c.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised = true; + c.Job.Properties.NonWarrantyProperties.PurchaseOrderReference = true; + c.Job.Properties.NonWarrantyProperties.PurchaseOrderSent = true; + c.Job.Properties.NonWarrantyProperties.RepairerCompletedDate = true; + c.Job.Properties.NonWarrantyProperties.RepairerLoggedDate = true; + c.Job.Properties.NonWarrantyProperties.RepairerName = true; + c.Job.Properties.NonWarrantyProperties.RepairerReference = true; + c.Job.Properties.DeviceHeldLocation = true; + c.Job.Properties.DeviceHeld = true; + c.Job.Properties.DeviceReadyForReturn = true; + c.Job.Properties.DeviceReturned = true; + c.Job.Properties.ExpectedClosedDate = true; + c.Job.Properties.Flags = true; + c.Job.Properties.NotWaitingForUserAction = true; + c.Job.Properties.WaitingForUserAction = true; + c.Job.Types.ShowHMisc = true; + c.Job.Types.ShowHNWar = true; + c.Job.Types.ShowHWar = true; + c.Job.Types.ShowSApp = true; + c.Job.Types.ShowSOS = true; + c.Job.Types.ShowSImg = true; + c.Job.Types.ShowUMgmt = true; + c.Job.Search = true; + c.Job.ShowAttachments = true; + c.Job.ShowDailyChart = true; + c.Job.ShowFlags = true; + c.Job.Show = true; + c.Job.ShowLogs = true; + c.Job.ShowNonWarrantyComponents = true; + c.Job.ShowNonWarrantyFinance = true; + c.Job.ShowNonWarrantyInsurance = true; + c.Job.ShowNonWarrantyRepairs = true; + c.Job.ShowWarranty = true; + c.Device.Properties.AssetNumber = true; + c.Device.Properties.DeviceBatch = true; + c.Device.Properties.DeviceProfile = true; + c.Device.Properties.Location = true; + c.Device.Actions.AddAttachments = true; + c.Device.Actions.AllowUnauthenticatedEnrol = true; + c.Device.Actions.AssignUser = true; + c.Device.Actions.Decommission = true; + c.Device.Actions.Delete = true; + c.Device.Actions.EnrolDevices = true; + c.Device.Actions.Export = true; + c.Device.Actions.GenerateDocuments = true; + c.Device.Actions.Import = true; + c.Device.Actions.Recommission = true; + c.Device.Actions.RemoveAnyAttachments = true; + c.Device.Actions.RemoveOwnAttachments = true; + c.Device.Search = true; + c.Device.ShowAssignmentHistory = true; + c.Device.ShowAttachments = true; + c.Device.ShowCertificates = true; + c.Device.ShowDetails = true; + c.Device.Show = true; + c.Device.ShowJobs = true; + c.User.Actions.AddAttachments = true; + c.User.Actions.GenerateDocuments = true; + c.User.Actions.RemoveAnyAttachments = true; + c.User.Actions.RemoveOwnAttachments = true; + c.User.Search = true; + c.User.ShowAttachments = true; + c.User.ShowAssignmentHistory = true; + c.User.Show = true; + c.User.ShowAuthorization = true; + c.User.ShowJobs = true; + c.DiscoAdminAccount = true; +#endregion + return c; + } + + public static RoleClaims ComputerAccountClaims() { + return new RoleClaims() { + ComputerAccount = true + }; + } + +#region Role Claim Constants + + /// Configuration + /// Permissions related to Disco Configuration + /// + public static class Config + { + + /// Device Certificate + /// Permissions related to Device Certificates + /// + public static class DeviceCertificate + { + + /// Download Certificates + /// Can download certificates + /// + public const string DownloadCertificates = "Config.DeviceCertificate.DownloadCertificates"; + } + + /// Enrolment + /// Permissions related to Device Enrolment + /// + public static class Enrolment + { + + /// Configure Enrolment + /// Can configure device enrolment + /// + public const string Configure = "Config.Enrolment.Configure"; + + /// Download Bootstrapper + /// Can download the Device Bootstrapper + /// + public const string DownloadBootstrapper = "Config.Enrolment.DownloadBootstrapper"; + + /// Show Enrolment + /// Can show device enrolment + /// + public const string Show = "Config.Enrolment.Show"; + + /// Show Enrolment Status + /// Can show the enrolment status + /// + public const string ShowStatus = "Config.Enrolment.ShowStatus"; + } + + /// Device Batch + /// Permissions related to Device Batches + /// + public static class DeviceBatch + { + + /// Configure Device Batches + /// Can configure device batches + /// + public const string Configure = "Config.DeviceBatch.Configure"; + + /// Create Device Batches + /// Can create device batches + /// + public const string Create = "Config.DeviceBatch.Create"; + + /// Delete Device Batches + /// Can delete device batches + /// + public const string Delete = "Config.DeviceBatch.Delete"; + + /// Show Device Batches + /// Can show device batches + /// + public const string Show = "Config.DeviceBatch.Show"; + + /// Show Timeline + /// Can show device batch timeline + /// + public const string ShowTimeline = "Config.DeviceBatch.ShowTimeline"; + } + + /// Device Model + /// Permissions related to Device Models + /// + public static class DeviceModel + { + + /// Configure Device Model Components + /// Can configure device model components + /// + public const string ConfigureComponents = "Config.DeviceModel.ConfigureComponents"; + + /// Configure Device Models + /// Can configure device models + /// + public const string Configure = "Config.DeviceModel.Configure"; + + /// Delete Device Models + /// Can delete device models + /// + public const string Delete = "Config.DeviceModel.Delete"; + + /// Show Device Models + /// Can show device models + /// + public const string Show = "Config.DeviceModel.Show"; + } + + /// Device Profile + /// Permissions related to Device Profiles + /// + public static class DeviceProfile + { + + /// Configure Computer Name Templates + /// Can configure computer name templates for device profiles + /// + public const string ConfigureComputerNameTemplate = "Config.DeviceProfile.ConfigureComputerNameTemplate"; + + /// Configure Default Device Profiles + /// Can configure default device profiles + /// + public const string ConfigureDefaults = "Config.DeviceProfile.ConfigureDefaults"; + + /// Configure Device Profiles + /// Can configure device profiles + /// + public const string Configure = "Config.DeviceProfile.Configure"; + + /// Create Device Profiles + /// Can create device profiles + /// + public const string Create = "Config.DeviceProfile.Create"; + + /// Delete Device Profiles + /// Can delete device profiles + /// + public const string Delete = "Config.DeviceProfile.Delete"; + + /// Show Device Profiles + /// Can show device profiles + /// + public const string Show = "Config.DeviceProfile.Show"; + } + + /// Document Template + /// Permissions related to Document Templates + /// + public static class DocumentTemplate + { + + /// Bulk Generate Document Templates + /// Can bulk generate document templates + /// + public const string BulkGenerate = "Config.DocumentTemplate.BulkGenerate"; + + /// Configure Document Templates + /// Can configure document templates + /// + public const string Configure = "Config.DocumentTemplate.Configure"; + + /// Configure Filter Expression + /// Can configure filter expressions for document templates + /// + public const string ConfigureFilterExpression = "Config.DocumentTemplate.ConfigureFilterExpression"; + + /// Create Document Templates + /// Can create document templates + /// + public const string Create = "Config.DocumentTemplate.Create"; + + /// Delete Document Templates + /// Can delete document templates + /// + public const string Delete = "Config.DocumentTemplate.Delete"; + + /// Show Document Template Import Status + /// Can show the document template import status + /// + public const string ShowStatus = "Config.DocumentTemplate.ShowStatus"; + + /// Show Document Templates + /// Can show document templates + /// + public const string Show = "Config.DocumentTemplate.Show"; + + /// Undetected Pages + /// Can show and assign imported documents which were not undetected + /// + public const string UndetectedPages = "Config.DocumentTemplate.UndetectedPages"; + + /// Upload Document Templates + /// Can upload document templates + /// + public const string Upload = "Config.DocumentTemplate.Upload"; + } + + /// Logging + /// Permissions related to Logging + /// + public static class Logging + { + + /// Show Logging + /// Can show logging + /// + public const string Show = "Config.Logging.Show"; + } + + /// Plugin + /// Permissions related to Plugins + /// + public static class Plugin + { + + /// Configure Plugins + /// Can configure plugins + /// + public const string Configure = "Config.Plugin.Configure"; + + /// Install/Update Local Plugins + /// Can install and update locally uploaded plugins + /// + public const string InstallLocal = "Config.Plugin.InstallLocal"; + + /// Install/Update Plugins + /// Can install and update plugins + /// + public const string Install = "Config.Plugin.Install"; + + /// Show Plugins + /// Can show plugins + /// + public const string Show = "Config.Plugin.Show"; + + /// Uninstall Plugins + /// Can uninstall plugins + /// + public const string Uninstall = "Config.Plugin.Uninstall"; + } + + /// System + /// Permissions related to System Configuration + /// + public static class System + { + + /// Configure Proxy Settings + /// Can configure the proxy settings + /// + public const string ConfigureProxy = "Config.System.ConfigureProxy"; + + /// Show System Configuration + /// Can show the system configuration + /// + public const string Show = "Config.System.Show"; + } + + /// Organisation Details + /// Permissions related to the Organisation Details + /// + public static class Organisation + { + + /// Configure Addresses + /// Can configure organisation addresses + /// + public const string ConfigureAddresses = "Config.Organisation.ConfigureAddresses"; + + /// Configure Logo + /// Can configure the organisation logo + /// + public const string ConfigureLogo = "Config.Organisation.ConfigureLogo"; + + /// Configure Multi-Site Mode + /// Can configure multi-site mode + /// + public const string ConfigureMultiSiteMode = "Config.Organisation.ConfigureMultiSiteMode"; + + /// Configure Name + /// Can configure the organisation name + /// + public const string ConfigureName = "Config.Organisation.ConfigureName"; + + /// Show Organisation Details + /// Can show the organisation details + /// + public const string Show = "Config.Organisation.Show"; + } + + /// Show Configuration + /// Can show the configuration menu + /// + public const string Show = "Config.Show"; + } + + /// Job + /// Permissions related to Jobs + /// + public static class Job + { + + /// Lists + /// Permissions related to Job Lists + /// + public static class Lists + { + + /// All Open List + /// Can show list + /// + public const string AllOpen = "Job.Lists.AllOpen"; + + /// Awaiting Finance Agreement Breach List + /// Can show list (NOTE: Requires Awaiting Finance List) + /// + public const string AwaitingFinanceAgreementBreach = "Job.Lists.AwaitingFinanceAgreementBreach"; + + /// Awaiting Finance Charge List + /// Can show list (NOTE: Requires Awaiting Finance List) + /// + public const string AwaitingFinanceCharge = "Job.Lists.AwaitingFinanceCharge"; + + /// Awaiting Finance Insurance Processing List + /// Can show list (NOTE: Requires Awaiting Finance List) + /// + public const string AwaitingFinanceInsuranceProcessing = "Job.Lists.AwaitingFinanceInsuranceProcessing"; + + /// Awaiting Finance List + /// Can show list + /// + public const string AwaitingFinance = "Job.Lists.AwaitingFinance"; + + /// Awaiting Finance Payment List + /// Can show list (NOTE: Requires Awaiting Finance List) + /// + public const string AwaitingFinancePayment = "Job.Lists.AwaitingFinancePayment"; + + /// Awaiting Technician Action List + /// Can show list + /// + public const string AwaitingTechnicianAction = "Job.Lists.AwaitingTechnicianAction"; + + /// Awaiting User Action List + /// Can show list + /// + public const string AwaitingUserAction = "Job.Lists.AwaitingUserAction"; + + /// Devices Awaiting Repair List + /// Can show list + /// + public const string DevicesAwaitingRepair = "Job.Lists.DevicesAwaitingRepair"; + + /// Devices Ready For Return List + /// Can show list + /// + public const string DevicesReadyForReturn = "Job.Lists.DevicesReadyForReturn"; + + /// Locations List + /// Can show list + /// + public const string Locations = "Job.Lists.Locations"; + + /// Long Running Jobs List + /// Can show list + /// + public const string LongRunningJobs = "Job.Lists.LongRunningJobs"; + + /// Recently Closed List + /// Can show list + /// + public const string RecentlyClosed = "Job.Lists.RecentlyClosed"; + } + + /// Actions + /// Permissions related to Job Actions + /// + public static class Actions + { + + /// Add Attachments + /// Can add attachments to jobs + /// + public const string AddAttachments = "Job.Actions.AddAttachments"; + + /// Add Logs + /// Can add job logs + /// + public const string AddLogs = "Job.Actions.AddLogs"; + + /// Close Jobs + /// Can close jobs + /// + public const string Close = "Job.Actions.Close"; + + /// Convert HWar Jobs To HNWar + /// Can convert warranty jobs to non-warranty jobs + /// + public const string ConvertHWarToHNWar = "Job.Actions.ConvertHWarToHNWar"; + + /// Create Jobs + /// Can create jobs + /// + public const string Create = "Job.Actions.Create"; + + /// Delete Jobs + /// Can delete jobs + /// + public const string Delete = "Job.Actions.Delete"; + + /// Force Close Jobs + /// Can force close jobs + /// + public const string ForceClose = "Job.Actions.ForceClose"; + + /// Generate Documents + /// Can generate documents for jobs + /// + public const string GenerateDocuments = "Job.Actions.GenerateDocuments"; + + /// Log Repair + /// Can log repair for non-warranty jobs + /// + public const string LogRepair = "Job.Actions.LogRepair"; + + /// Log Warranty + /// Can log warranty for jobs + /// + public const string LogWarranty = "Job.Actions.LogWarranty"; + + /// Remove Any Attachments + /// Can remove any attachments from jobs + /// + public const string RemoveAnyAttachments = "Job.Actions.RemoveAnyAttachments"; + + /// Remove Any Logs + /// Can remove any job logs + /// + public const string RemoveAnyLogs = "Job.Actions.RemoveAnyLogs"; + + /// Remove Own Attachments + /// Can remove own attachments from jobs + /// + public const string RemoveOwnAttachments = "Job.Actions.RemoveOwnAttachments"; + + /// Remove Own Logs + /// Can remove own job logs + /// + public const string RemoveOwnLogs = "Job.Actions.RemoveOwnLogs"; + + /// Reopen Jobs + /// Can reopen jobs + /// + public const string Reopen = "Job.Actions.Reopen"; + + /// Update Sub Types + /// Can update sub types for jobs + /// + public const string UpdateSubTypes = "Job.Actions.UpdateSubTypes"; + } + + /// Job Properties + /// Permissions related to Job Properties + /// + public static class Properties + { + + /// Warranty Properties + /// Permissions related to Warranty Job Properties + /// + public static class WarrantyProperties + { + + /// External Completed Date Property + /// Can update property + /// + public const string ExternalCompletedDate = "Job.Properties.WarrantyProperties.ExternalCompletedDate"; + + /// External Logged Date Property + /// Can update property + /// + public const string ExternalLoggedDate = "Job.Properties.WarrantyProperties.ExternalLoggedDate"; + + /// External Name Property + /// Can update property + /// + public const string ExternalName = "Job.Properties.WarrantyProperties.ExternalName"; + + /// External Reference Property + /// Can update property + /// + public const string ExternalReference = "Job.Properties.WarrantyProperties.ExternalReference"; + + /// Provider Details + /// Can access warranty provider details + /// + public const string ProviderDetails = "Job.Properties.WarrantyProperties.ProviderDetails"; + + /// Warranty Completed Property + /// Can update property + /// + public const string WarrantyCompleted = "Job.Properties.WarrantyProperties.WarrantyCompleted"; + } + + /// Non Warranty Properties + /// Permissions related to Non-Warranty Job Properties + /// + public static class NonWarrantyProperties + { + + /// Accounting Charge Added Property + /// Can update property + /// + public const string AccountingChargeAdded = "Job.Properties.NonWarrantyProperties.AccountingChargeAdded"; + + /// Accounting Charge Paid Property + /// Can update property + /// + public const string AccountingChargePaid = "Job.Properties.NonWarrantyProperties.AccountingChargePaid"; + + /// Accounting Charge Required Property + /// Can update property + /// + public const string AccountingChargeRequired = "Job.Properties.NonWarrantyProperties.AccountingChargeRequired"; + + /// Add Components + /// Can add job components (NOTE: Requires Edit Components) + /// + public const string AddComponents = "Job.Properties.NonWarrantyProperties.AddComponents"; + + /// Edit Components + /// Can edit and remove job components + /// + public const string EditComponents = "Job.Properties.NonWarrantyProperties.EditComponents"; + + /// Insurance Claim Form Sent Property + /// Can update property + /// + public const string InsuranceClaimFormSent = "Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent"; + + /// Insurance Detail Properties + /// Can update insurance detail properties + /// + public const string InsuranceDetails = "Job.Properties.NonWarrantyProperties.InsuranceDetails"; + + /// Invoice Received Property + /// Can update property + /// + public const string InvoiceReceived = "Job.Properties.NonWarrantyProperties.InvoiceReceived"; + + /// Is Insurance Claim Property + /// Can update property + /// + public const string IsInsuranceClaim = "Job.Properties.NonWarrantyProperties.IsInsuranceClaim"; + + /// Purchase Order Raised Property + /// Can update property + /// + public const string PurchaseOrderRaised = "Job.Properties.NonWarrantyProperties.PurchaseOrderRaised"; + + /// Purchase Order Reference Property + /// Can update property + /// + public const string PurchaseOrderReference = "Job.Properties.NonWarrantyProperties.PurchaseOrderReference"; + + /// Purchase Order Sent Property + /// Can update property + /// + public const string PurchaseOrderSent = "Job.Properties.NonWarrantyProperties.PurchaseOrderSent"; + + /// Repairer Completed Date Property + /// Can update property + /// + public const string RepairerCompletedDate = "Job.Properties.NonWarrantyProperties.RepairerCompletedDate"; + + /// Repairer Logged Date Property + /// Can update property + /// + public const string RepairerLoggedDate = "Job.Properties.NonWarrantyProperties.RepairerLoggedDate"; + + /// Repairer Name Property + /// Can update property + /// + public const string RepairerName = "Job.Properties.NonWarrantyProperties.RepairerName"; + + /// Repairer Reference Property + /// Can update property + /// + public const string RepairerReference = "Job.Properties.NonWarrantyProperties.RepairerReference"; + } + + /// Device Held Location Property + /// Can update property + /// + public const string DeviceHeldLocation = "Job.Properties.DeviceHeldLocation"; + + /// Device Held Property + /// Can update property + /// + public const string DeviceHeld = "Job.Properties.DeviceHeld"; + + /// Device Ready For Return Property + /// Can update property + /// + public const string DeviceReadyForReturn = "Job.Properties.DeviceReadyForReturn"; + + /// Device Returned Property + /// Can update property + /// + public const string DeviceReturned = "Job.Properties.DeviceReturned"; + + /// Expected Closed Date Property + /// Can update property + /// + public const string ExpectedClosedDate = "Job.Properties.ExpectedClosedDate"; + + /// Flags Property + /// Can update property + /// + public const string Flags = "Job.Properties.Flags"; + + /// Not Waiting For User Action Property + /// Can update property + /// + public const string NotWaitingForUserAction = "Job.Properties.NotWaitingForUserAction"; + + /// Waiting For User Action Property + /// Can update property + /// + public const string WaitingForUserAction = "Job.Properties.WaitingForUserAction"; + } + + /// Types + /// Permissions related to Job Types + /// + public static class Types + { + + /// Show Hardware - Miscellaneous Jobs + /// Can show jobs of this type + /// + public const string ShowHMisc = "Job.Types.ShowHMisc"; + + /// Show Hardware - Non-Warranty Jobs + /// Can show jobs of this type + /// + public const string ShowHNWar = "Job.Types.ShowHNWar"; + + /// Show Hardware - Warranty Jobs + /// Can show jobs of this type + /// + public const string ShowHWar = "Job.Types.ShowHWar"; + + /// Show Software - Application Jobs + /// Can show jobs of this type + /// + public const string ShowSApp = "Job.Types.ShowSApp"; + + /// Show Software - Operating System Jobs + /// Can show jobs of this type + /// + public const string ShowSOS = "Job.Types.ShowSOS"; + + /// Show Software - Reimage Jobs + /// Can show jobs of this type + /// + public const string ShowSImg = "Job.Types.ShowSImg"; + + /// Show User Management Jobs + /// Can show jobs of this type + /// + public const string ShowUMgmt = "Job.Types.ShowUMgmt"; + } + + /// Search Jobs + /// Can search jobs + /// + public const string Search = "Job.Search"; + + /// Show Attachments + /// Can show job attachments + /// + public const string ShowAttachments = "Job.ShowAttachments"; + + /// Show Daily Opened & Closed + /// Can show daily opened & closed chart + /// + public const string ShowDailyChart = "Job.ShowDailyChart"; + + /// Show Flags + /// Can show job flags + /// + public const string ShowFlags = "Job.ShowFlags"; + + /// Show Jobs + /// Can show jobs + /// + public const string Show = "Job.Show"; + + /// Show Logs + /// Can show job logs + /// + public const string ShowLogs = "Job.ShowLogs"; + + /// Show Non-Warranty Components + /// Can show non-warranty job components + /// + public const string ShowNonWarrantyComponents = "Job.ShowNonWarrantyComponents"; + + /// Show Non-Warranty Finance + /// Can show non-warranty job finance + /// + public const string ShowNonWarrantyFinance = "Job.ShowNonWarrantyFinance"; + + /// Show Non-Warranty Insurance + /// Can show non-warranty job insurance + /// + public const string ShowNonWarrantyInsurance = "Job.ShowNonWarrantyInsurance"; + + /// Show Non-Warranty Repairs + /// Can show non-warranty job repairs + /// + public const string ShowNonWarrantyRepairs = "Job.ShowNonWarrantyRepairs"; + + /// Show Warranty + /// Can show job warranty + /// + public const string ShowWarranty = "Job.ShowWarranty"; + } + + /// Device + /// Permissions related to Devices + /// + public static class Device + { + + /// Device Properties + /// Permissions related to Device Properties + /// + public static class Properties + { + + /// Asset Number Property + /// Can update property + /// + public const string AssetNumber = "Device.Properties.AssetNumber"; + + /// Device Batch Property + /// Can update property + /// + public const string DeviceBatch = "Device.Properties.DeviceBatch"; + + /// Device Profile Property + /// Can update property + /// + public const string DeviceProfile = "Device.Properties.DeviceProfile"; + + /// Location Property + /// Can update property + /// + public const string Location = "Device.Properties.Location"; + } + + /// Actions + /// Permissions related to Device Actions + /// + public static class Actions + { + + /// Add Attachments + /// Can add attachments to devices + /// + public const string AddAttachments = "Device.Actions.AddAttachments"; + + /// Allow Unauthenticated Enrol + /// Can allow devices to enrol without authentication + /// + public const string AllowUnauthenticatedEnrol = "Device.Actions.AllowUnauthenticatedEnrol"; + + /// Assign User + /// Can update the user assignment of devices + /// + public const string AssignUser = "Device.Actions.AssignUser"; + + /// Decommission + /// Can decommission devices + /// + public const string Decommission = "Device.Actions.Decommission"; + + /// Delete + /// Can delete devices + /// + public const string Delete = "Device.Actions.Delete"; + + /// Enrol Devices + /// Can add devices offline and enrol devices with the Bootstrapper + /// + public const string EnrolDevices = "Device.Actions.EnrolDevices"; + + /// Export Devices + /// Can export devices in a bulk format + /// + public const string Export = "Device.Actions.Export"; + + /// Generate Documents + /// Can generate documents for jobs + /// + public const string GenerateDocuments = "Device.Actions.GenerateDocuments"; + + /// Import Devices + /// Can bulk import devices + /// + public const string Import = "Device.Actions.Import"; + + /// Recommission + /// Can recommission devices + /// + public const string Recommission = "Device.Actions.Recommission"; + + /// Remove Any Attachments + /// Can remove any attachments from devices + /// + public const string RemoveAnyAttachments = "Device.Actions.RemoveAnyAttachments"; + + /// Remove Own Attachments + /// Can remove own attachments from devices + /// + public const string RemoveOwnAttachments = "Device.Actions.RemoveOwnAttachments"; + } + + /// Search Devices + /// Can search devices + /// + public const string Search = "Device.Search"; + + /// Show Assignment History + /// Can show the assignment history for devices + /// + public const string ShowAssignmentHistory = "Device.ShowAssignmentHistory"; + + /// Show Attachments + /// Can show device attachments + /// + public const string ShowAttachments = "Device.ShowAttachments"; + + /// Show Certificates + /// Can show certificates associated with devices + /// + public const string ShowCertificates = "Device.ShowCertificates"; + + /// Show Details + /// Can show details associated with devices + /// + public const string ShowDetails = "Device.ShowDetails"; + + /// Show Devices + /// Can show devices + /// + public const string Show = "Device.Show"; + + /// Show Devices Jobs + /// Can show jobs associated with devices + /// + public const string ShowJobs = "Device.ShowJobs"; + } + + /// User + /// Permissions related to Users + /// + public static class User + { + + /// Actions + /// Permissions related to User Actions + /// + public static class Actions + { + + /// Add Attachments + /// Can add attachments to users + /// + public const string AddAttachments = "User.Actions.AddAttachments"; + + /// Generate Documents + /// Can generate documents for users + /// + public const string GenerateDocuments = "User.Actions.GenerateDocuments"; + + /// Remove Any Attachments + /// Can remove any attachments from users + /// + public const string RemoveAnyAttachments = "User.Actions.RemoveAnyAttachments"; + + /// Remove Own Attachments + /// Can remove own attachments from users + /// + public const string RemoveOwnAttachments = "User.Actions.RemoveOwnAttachments"; + } + + /// Search Users + /// Can search users + /// + public const string Search = "User.Search"; + + /// Show Attachments + /// Can show user attachments + /// + public const string ShowAttachments = "User.ShowAttachments"; + + /// Show Device Assignment History + /// Can show the device assignment history for users + /// + public const string ShowAssignmentHistory = "User.ShowAssignmentHistory"; + + /// Show Users + /// Can show users + /// + public const string Show = "User.Show"; + + /// Show Users Authorization + /// Can show authorization permissions associated with users + /// + public const string ShowAuthorization = "User.ShowAuthorization"; + + /// Show Users Jobs + /// Can show jobs associated with users + /// + public const string ShowJobs = "User.ShowJobs"; + } + + /// Computer Account + /// Represents a computer account + /// + public const string ComputerAccount = "ComputerAccount"; + + /// Disco Administrator Account + /// Represents a Disco Administrator account + /// + public const string DiscoAdminAccount = "DiscoAdminAccount"; +#endregion + } + public static class ClaimExtensions + { + public static bool Has(this RoleClaims c, string ClaimKey) + { + Func claimFunc = Claims.GetClaimAccessor(ClaimKey); + + return claimFunc(c); + } + + public static void Set(this RoleClaims c, string ClaimKey, bool Value) + { + Action claimSetter = Claims.GetClaimSetter(ClaimKey); + + claimSetter(c, Value); + } + + public static void SetClaims(this AuthorizationRole role, RoleClaims Claims) + { + role.ClaimsJson = Newtonsoft.Json.JsonConvert.SerializeObject(Claims); + } + } +} diff --git a/Disco.Services/Authorization/Claims.tt b/Disco.Services/Authorization/Claims.tt new file mode 100644 index 00000000..5e1632b3 --- /dev/null +++ b/Disco.Services/Authorization/Claims.tt @@ -0,0 +1,392 @@ +<#@ template language="C#" debug="true" hostspecific="true" #> +<#@ output extension=".cs" #> +<#@ assembly name="System.Core" #> +<#@ assembly name="Microsoft.VisualStudio.Shell.Interop" #> +<#@ assembly name="EnvDTE" #> +<#@ assembly name="EnvDTE80" #> +<#@ assembly name="VSLangProj" #> +<#@ assembly name="System.Xml" #> +<#@ assembly name="System.Xml.Linq" #> +<#@ assembly name="C:\Windows\Microsoft.NET\Framework\v4.0.30319\CustomMarshalers.dll" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Text.RegularExpressions" #> +<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #> +<#@ import namespace="EnvDTE" #> +<#@ import namespace="EnvDTE80" #> +<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> +<#@ import namespace="System.Runtime.InteropServices.CustomMarshalers" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<#@ import namespace="System.Reflection" #> + + + +<# + // Get the DTE service from the host + EnvDTE.DTE Dte = null; + var serviceProvider = Host as IServiceProvider; + if (serviceProvider != null) + Dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); + + // Fail if we couldn't get the DTE. This can happen when trying to run in TextTransform.exe + if (Dte == null) + throw new Exception("T4MVC can only execute through the Visual Studio host"); + + List permissions = new List(); + List groups = new List(); + + var piRolePermission = Dte.Solution.FindProjectItem(Host.ResolvePath(@"Roles\RoleClaims.cs")); + var piGroups = FindClaimGroupProjectItems(piRolePermission.ContainingProject.ProjectItems.Item("Authorization").ProjectItems.Item("Roles").ProjectItems.Item("ClaimGroups")).ToList(); + + ParseProjectItem(piRolePermission, groups, permissions); + foreach (ProjectItem piItem in piGroups) + ParseProjectItem(piItem, groups, permissions); + + var permissionRoot = BuildHierarchy(groups, permissions); + + + + #> +// +// This file was generated by a T4 template. +// Don't change it directly as your change would get overwritten. Instead, make changes +// to the .tt file (i.e. the T4 template) and save it to regenerate this file. +using Disco.Models.Authorization; +using Disco.Models.Repository; +using Disco.Services.Authorization.Roles; +using System; +using System.Collections.Generic; + +namespace Disco.Services.Authorization +{ + public static class Claims + { + private static Dictionary, Action, string, string>> _roleClaims; + private static ClaimNavigatorItem _claimNavigator; + + static Claims() + { +#region Role Claim Dictionary + _roleClaims = new Dictionary, Action, string, string>>() + { +<#WriteAccessHashes(permissionRoot);#> + }; +#endregion + +#region Role Claim Navigator + _claimNavigator = +<#WriteNavigator(permissionRoot);#>; +#endregion + } + + public static ClaimNavigatorItem RoleClaimNavigator + { + get { return _claimNavigator; } + } + + public static Func GetClaimAccessor(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return claimFunc.Item1; + } + + public static Action GetClaimSetter(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return claimFunc.Item2; + } + + public static Tuple GetClaimDetails(string ClaimKey) { + Tuple, Action, string, string> claimFunc; + + if (!_roleClaims.TryGetValue(ClaimKey, out claimFunc)) + throw new ArgumentException("Unknown Claim Key", "ClaimKey"); + + return new Tuple(claimFunc.Item3, claimFunc.Item4); + } + + public static RoleClaims BuildClaims(IEnumerable ClaimKeys){ + var c = new RoleClaims(); + foreach (var claimKey in ClaimKeys) + c.Set(claimKey, true); + + return c; + } + + public static RoleClaims AdministratorClaims() { + var c = new RoleClaims(); +#region Set All Administrator Claims +<#WriteAdministratorClaims(permissionRoot);#> +#endregion + return c; + } + + public static RoleClaims ComputerAccountClaims() { + return new RoleClaims() { + ComputerAccount = true + }; + } + +#region Role Claim Constants +<#WritePermissionConsts(permissionRoot);#> +#endregion + } + public static class ClaimExtensions + { + public static bool Has(this RoleClaims c, string ClaimKey) + { + Func claimFunc = Claims.GetClaimAccessor(ClaimKey); + + return claimFunc(c); + } + + public static void Set(this RoleClaims c, string ClaimKey, bool Value) + { + Action claimSetter = Claims.GetClaimSetter(ClaimKey); + + claimSetter(c, Value); + } + + public static void SetClaims(this AuthorizationRole role, RoleClaims Claims) + { + role.ClaimsJson = Newtonsoft.Json.JsonConvert.SerializeObject(Claims); + } + } +} +<#+ + +void DumpPermission(Permission p){ + PushIndent(" "); + WriteLine(p.Name); + foreach (Permission pChild in p.Children) + { + DumpPermission(pChild); + } + PopIndent(); +} + +void WriteNavigator(Permission root){ + PushIndent(" "); + WriteLine("new ClaimNavigatorItem(\"Claims\", \"Permissions\", \"Top-level node for all permissions\", false, new List() {"); + PushIndent(" "); + for (int childIndex = 0; childIndex < root.Children.Count; childIndex++) + { + WriteNavigator_Recurse(root.Children[childIndex], string.Empty); + if (childIndex < root.Children.Count -1) + WriteLine(","); + } + WriteLine(string.Empty); + PopIndent(); + Write("})"); + PopIndent(); +} + +void WriteNavigator_Recurse(Permission p, string Prefix){ + var key = string.Concat(Prefix, p.Name); + + if (p.IsGroup){ + var groupPrefix = string.Concat(key, "."); + WriteLine("new ClaimNavigatorItem(\"{0}{1}\", \"{2}\", \"{3}\", {4}, new List() {{", Prefix, p.Name, p.FriendlyName, p.Description, p.Hidden ? "true" : "false"); + PushIndent(" "); + for (int childIndex = 0; childIndex < p.Children.Count; childIndex++) + { + WriteNavigator_Recurse(p.Children[childIndex], groupPrefix); + if (childIndex < p.Children.Count -1) + WriteLine(","); + else + WriteLine(string.Empty); + } + PopIndent(); + Write("})"); + }else{ + Write("new ClaimNavigatorItem(\"{0}{1}\", {2})", Prefix, p.Name, p.Hidden ? "true" : "false"); + } +} + +void WriteAdministratorClaims(Permission root){ + PushIndent(" "); + Stack parents = new Stack(); + parents.Push("c"); + foreach (var pChild in root.Children) + WriteAdministratorClaims_Recurse(pChild, parents); + PopIndent(); +} + +void WriteAdministratorClaims_Recurse(Permission p, Stack parents){ + if (p.IsGroup){ + parents.Push(string.Format("{0}.{1}", parents.Peek(), p.Name)); + foreach (var pChild in p.Children) + WriteAdministratorClaims_Recurse(pChild, parents); + parents.Pop(); + }else{ + if (p.Name != "ComputerAccount") + WriteLine("{0}.{1} = true;", parents.Peek(), p.Name); + } +} + + +void WriteAccessHashes(Permission root){ + StringBuilder hashes = new StringBuilder(); + Stack parents = new Stack(); + parents.Push("c"); + foreach (var pChild in root.Children) + WriteAccessHashes_Recurse(pChild, string.Empty, parents, hashes); + WriteLine(hashes.ToString().TrimEnd().TrimEnd(',')); +} + +void WriteAccessHashes_Recurse(Permission p, string Prefix, Stack parents, StringBuilder hashes){ + if (p.IsGroup){ + parents.Push(string.Format("{0}.{1}", parents.Peek(), p.Name)); + foreach (var pChild in p.Children) + WriteAccessHashes_Recurse(pChild, string.Concat(Prefix, p.Name, "."), parents, hashes); + parents.Pop(); + }else{ + var fqn = string.Concat(Prefix, p.Name); + hashes.AppendFormat(" {{ \"{0}\", new Tuple, Action, string, string>(c => {1}.{2}, (c, v) => {1}.{2} = v, \"{3}\", \"{4}\") }},", fqn, parents.Peek(), p.Name, p.FriendlyName, p.Description); + hashes.AppendLine(); + } +} + +void WritePermissionConsts(Permission root){ + PushIndent(" "); + PushIndent(" "); + foreach (var pChild in root.Children) + WritePermissionConsts_Recurse(pChild, string.Empty); + PopIndent(); + PopIndent(); +} +void WritePermissionConsts_Recurse(Permission p, string Prefix){ + if (p.IsGroup){ + WriteLine(""); + WriteLine("/// {0}", p.FriendlyName); + WriteLine("/// {0}", p.Description); + WriteLine("/// "); + WriteLine("public static class {0}", p.Name); + WriteLine("{"); + PushIndent(" "); + foreach (var pChild in p.Children) + WritePermissionConsts_Recurse(pChild, string.Concat(Prefix, p.Name, ".")); + PopIndent(); + WriteLine("}"); + }else{ + WriteLine(""); + WriteLine("/// {0}", p.FriendlyName); + WriteLine("/// {0}", p.Description); + WriteLine("/// "); + WriteLine("public const string {0} = \"{1}{0}\";", p.Name, Prefix); + } +} + +Permission BuildHierarchy(List groups, List permissions){ + var top = groups[0]; + + // Find Parents + var groupDict = groups.ToDictionary(p => p.FullName); + + // Hierarchy + foreach (var p in permissions.Where(p => p.IsGroup)) + { + var g = groupDict[p.Type]; + p.Children = g.Children; + p.FriendlyName = g.FriendlyName; + p.Description = g.Description; + } + + return top; +} + +void ParseProjectItem(ProjectItem item, List groups, List permissions){ + foreach (var ns in item.FileCodeModel.CodeElements.OfType()) + { + foreach (var cl in ns.Members.OfType()) + { + var g = BuildPermission(cl); + groups.Add(g); + foreach (var pr in cl.Members.OfType()) + { + var p = BuildPermission(pr); + permissions.Add(p); + g.Children.Add(p); + } + g.Children = g.Children.OrderBy(p => p.IsGroup).OrderBy(p => p.FriendlyName).ToList(); + } + } +} + +IEnumerable FindClaimGroupProjectItems(ProjectItem item){ + const string collectionGuid = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"; + + if (item.Kind == collectionGuid) + foreach (ProjectItem subItem in item.ProjectItems) + foreach (var returnItem in FindClaimGroupProjectItems(subItem)) + yield return returnItem; + else + yield return item; +} + +Permission BuildPermission(CodeClass2 item){ + return new Permission(item.FullName, item.Name, item.FullName, item.Attributes); +} + +Permission BuildPermission(CodeProperty2 item){ + return new Permission(item.FullName, item.Name, item.Type.AsFullName, item.Attributes); +} + +[ComImport, Guid("00020400-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +public interface IDispatch +{ + void Reserved(); + [PreserveSig] + int GetTypeInfo(uint nInfo, int lcid, + [MarshalAs( + UnmanagedType.CustomMarshaler, + MarshalTypeRef = typeof(TypeToTypeInfoMarshaler))] + out System.Type typeInfo); +} + +class Permission { + public string FullName {get;set;} + public string Name {get;set;} + public string Type {get;set;} + public bool Hidden {get;set;} + + public bool IsGroup {get { return Type != "System.Boolean"; } } + + public List Children {get;set;} + + public string FriendlyName {get;set;} + public string Description {get;set;} + + public Permission(string FullName, string Name, string Type, CodeElements Attributes) + { + this.FullName = FullName; + this.Name = Name; + this.Type = Type; + + Children = new List(); + + if (Attributes.Count > 0){ + CodeAttribute att = (CodeAttribute)Attributes.Item("ClaimDetails"); + + if (att.Children != null){ + + var attChildren = att.Children.OfType().ToArray(); + this.FriendlyName = attChildren[0].Value.Trim('"'); + this.Description = attChildren[1].Value.Trim('"'); + + if (attChildren.Length > 2) { + this.Hidden = bool.Parse(attChildren[2].Value); + } + } + } + } +} +#> \ No newline at end of file diff --git a/Disco.Services/Authorization/DiscoAuthorizeAllAttribute.cs b/Disco.Services/Authorization/DiscoAuthorizeAllAttribute.cs new file mode 100644 index 00000000..557409ed --- /dev/null +++ b/Disco.Services/Authorization/DiscoAuthorizeAllAttribute.cs @@ -0,0 +1,41 @@ +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web.Mvc; + +namespace Disco.Services.Authorization +{ + public class DiscoAuthorizeAllAttribute : AuthorizeAttribute + { + string[] authorizedClaims; + + public DiscoAuthorizeAllAttribute(params string[] AuthorisedClaims) + { + if (AuthorisedClaims == null || AuthorisedClaims.Length == 0) + throw new ArgumentNullException("AuthorisedClaims"); + + this.authorizedClaims = AuthorisedClaims; + } + + protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) + { + if (httpContext == null) + throw new ArgumentNullException("httpContext"); + + var authToken = UserService.CurrentAuthorization; + + if (authToken == null) + return false; // No Current User + + return authToken.HasAll(authorizedClaims); + } + + protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) + { + filterContext.Result = new HttpUnauthorizedResult(AuthorizationToken.BuildRequireAllMessage(authorizedClaims)); + } + } +} diff --git a/Disco.Services/Authorization/DiscoAuthorizeAnyAttribute.cs b/Disco.Services/Authorization/DiscoAuthorizeAnyAttribute.cs new file mode 100644 index 00000000..d04f9e9e --- /dev/null +++ b/Disco.Services/Authorization/DiscoAuthorizeAnyAttribute.cs @@ -0,0 +1,41 @@ +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web.Mvc; + +namespace Disco.Services.Authorization +{ + public class DiscoAuthorizeAnyAttribute : AuthorizeAttribute + { + string[] authorizedClaims; + + public DiscoAuthorizeAnyAttribute(params string[] AuthorisedClaims) + { + if (AuthorisedClaims == null || AuthorisedClaims.Length == 0) + throw new ArgumentNullException("AuthorisedClaims"); + + this.authorizedClaims = AuthorisedClaims; + } + + protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) + { + if (httpContext == null) + throw new ArgumentNullException("httpContext"); + + var authToken = UserService.CurrentAuthorization; + + if (authToken == null) + return false; // No Current User + + return authToken.HasAny(authorizedClaims); + } + + protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) + { + filterContext.Result = new HttpUnauthorizedResult(AuthorizationToken.BuildRequireAnyMessage(authorizedClaims)); + } + } +} diff --git a/Disco.Services/Authorization/DiscoAuthorizeAttribute.cs b/Disco.Services/Authorization/DiscoAuthorizeAttribute.cs new file mode 100644 index 00000000..9d042417 --- /dev/null +++ b/Disco.Services/Authorization/DiscoAuthorizeAttribute.cs @@ -0,0 +1,53 @@ +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web.Mvc; + +namespace Disco.Services.Authorization +{ + public class DiscoAuthorizeAttribute : AuthorizeAttribute + { + string authorizedClaim; + + public DiscoAuthorizeAttribute() { } + + public DiscoAuthorizeAttribute(string AuthorisedClaim) + { + this.authorizedClaim = AuthorisedClaim; + } + + protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) + { + if (httpContext == null) + throw new ArgumentNullException("httpContext"); + + var authToken = UserService.CurrentAuthorization; + + if (authToken == null) + return false; // No Current User + + if (authorizedClaim == null) + return authToken.RoleTokens.Count > 0; // Just Authenticate - no Authorization (but require at least 1 role) + else + return authToken.Has(authorizedClaim); + } + + protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) + { + string resultMessage; + + if (UserService.CurrentAuthorization == null) + resultMessage = AuthorizationToken.RequireAuthenticationMessage; + else + if (string.IsNullOrEmpty(authorizedClaim)) + resultMessage = AuthorizationToken.RequireDiscoAuthorizationMessage; + else + resultMessage = AuthorizationToken.BuildRequireMessage(authorizedClaim); + + filterContext.Result = new HttpUnauthorizedResult(resultMessage); + } + } +} diff --git a/Disco.Services/Authorization/Roles/BaseRoleClaimGroup.cs b/Disco.Services/Authorization/Roles/BaseRoleClaimGroup.cs new file mode 100644 index 00000000..c10a7e27 --- /dev/null +++ b/Disco.Services/Authorization/Roles/BaseRoleClaimGroup.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles +{ + public abstract class BaseRoleClaimGroup + { + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimDetailsAttribute.cs b/Disco.Services/Authorization/Roles/ClaimDetailsAttribute.cs new file mode 100644 index 00000000..0021ae89 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimDetailsAttribute.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class ClaimDetailsAttribute : Attribute + { + public string Name { get; set; } + public string Description { get; set; } + public bool Hidden { get; set; } + + public ClaimDetailsAttribute(string Name, string Description, bool Hidden = false) + { + this.Name = Name; + this.Description = Description; + this.Hidden = Hidden; + } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/ConfigClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/ConfigClaims.cs new file mode 100644 index 00000000..64c63c67 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/ConfigClaims.cs @@ -0,0 +1,59 @@ +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceBatch; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceCertificate; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceModel; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceProfile; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DocumentTemplate; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Enrolment; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Logging; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Origanisation; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Plugin; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration.System; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration +{ + [ClaimDetails("Configuration", "Permissions related to Disco Configuration")] + public class ConfigClaims : BaseRoleClaimGroup + { + public ConfigClaims() + { + this.DeviceCertificate = new DeviceCertificateClaims(); + this.Enrolment = new EnrolmentClaims(); + this.DeviceBatch = new DeviceBatchClaims(); + this.DeviceModel = new DeviceModelClaims(); + this.DeviceProfile = new DeviceProfileClaims(); + this.DocumentTemplate = new DocumentTemplateClaims(); + this.Logging = new LoggingClaims(); + this.Plugin = new PluginClaims(); + this.System = new SystemClaims(); + this.Organisation = new OrganisationClaims(); + } + + [ClaimDetails("Show Configuration", "Can show the configuration menu")] + public bool Show { get; set; } + + public DeviceCertificateClaims DeviceCertificate { get; set; } + + public EnrolmentClaims Enrolment { get; set; } + + public DeviceBatchClaims DeviceBatch { get; set; } + + public DeviceModelClaims DeviceModel { get; set; } + + public DeviceProfileClaims DeviceProfile { get; set; } + + public DocumentTemplateClaims DocumentTemplate { get; set; } + + public LoggingClaims Logging { get; set; } + + public PluginClaims Plugin { get; set; } + + public SystemClaims System { get; set; } + + public OrganisationClaims Organisation { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceBatch/DeviceBatchClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceBatch/DeviceBatchClaims.cs new file mode 100644 index 00000000..927a16d4 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceBatch/DeviceBatchClaims.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceBatch +{ + [ClaimDetails("Device Batch", "Permissions related to Device Batches")] + public class DeviceBatchClaims : BaseRoleClaimGroup + { + [ClaimDetails("Configure Device Batches", "Can configure device batches")] + public bool Configure { get; set; } + + [ClaimDetails("Create Device Batches", "Can create device batches")] + public bool Create { get; set; } + + [ClaimDetails("Delete Device Batches", "Can delete device batches")] + public bool Delete { get; set; } + + [ClaimDetails("Show Device Batches", "Can show device batches")] + public bool Show { get; set; } + + [ClaimDetails("Show Timeline", "Can show device batch timeline")] + public bool ShowTimeline { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceCertificate/DeviceCertificateClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceCertificate/DeviceCertificateClaims.cs new file mode 100644 index 00000000..a1c97058 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceCertificate/DeviceCertificateClaims.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceCertificate +{ + [ClaimDetails("Device Certificate", "Permissions related to Device Certificates")] + public class DeviceCertificateClaims : BaseRoleClaimGroup + { + [ClaimDetails("Download Certificates", "Can download certificates")] + public bool DownloadCertificates { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceModel/DeviceModelClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceModel/DeviceModelClaims.cs new file mode 100644 index 00000000..71f12188 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceModel/DeviceModelClaims.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceModel +{ + [ClaimDetails("Device Model", "Permissions related to Device Models")] + public class DeviceModelClaims : BaseRoleClaimGroup + { + [ClaimDetails("Configure Device Models", "Can configure device models")] + public bool Configure { get; set; } + + [ClaimDetails("Configure Device Model Components", "Can configure device model components")] + public bool ConfigureComponents { get; set; } + + [ClaimDetails("Delete Device Models", "Can delete device models")] + public bool Delete { get; set; } + + [ClaimDetails("Show Device Models", "Can show device models")] + public bool Show { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceProfile/DeviceProfileClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceProfile/DeviceProfileClaims.cs new file mode 100644 index 00000000..709dd2fd --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DeviceProfile/DeviceProfileClaims.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DeviceProfile +{ + [ClaimDetails("Device Profile", "Permissions related to Device Profiles")] + public class DeviceProfileClaims : BaseRoleClaimGroup + { + [ClaimDetails("Configure Device Profiles", "Can configure device profiles")] + public bool Configure { get; set; } + + [ClaimDetails("Configure Computer Name Templates", "Can configure computer name templates for device profiles")] + public bool ConfigureComputerNameTemplate { get; set; } + + [ClaimDetails("Configure Default Device Profiles", "Can configure default device profiles")] + public bool ConfigureDefaults { get; set; } + + [ClaimDetails("Create Device Profiles", "Can create device profiles")] + public bool Create { get; set; } + + [ClaimDetails("Delete Device Profiles", "Can delete device profiles")] + public bool Delete { get; set; } + + [ClaimDetails("Show Device Profiles", "Can show device profiles")] + public bool Show { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DocumentTemplate/DocumentTemplateClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DocumentTemplate/DocumentTemplateClaims.cs new file mode 100644 index 00000000..0d31d347 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/DocumentTemplate/DocumentTemplateClaims.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.DocumentTemplate +{ + [ClaimDetails("Document Template", "Permissions related to Document Templates")] + public class DocumentTemplateClaims : BaseRoleClaimGroup + { + [ClaimDetails("Configure Document Templates", "Can configure document templates")] + public bool Configure { get; set; } + + [ClaimDetails("Configure Filter Expression", "Can configure filter expressions for document templates")] + public bool ConfigureFilterExpression { get; set; } + + [ClaimDetails("Upload Document Templates", "Can upload document templates")] + public bool Upload { get; set; } + + [ClaimDetails("Create Document Templates", "Can create document templates")] + public bool Create { get; set; } + + [ClaimDetails("Delete Document Templates", "Can delete document templates")] + public bool Delete { get; set; } + + [ClaimDetails("Show Document Templates", "Can show document templates")] + public bool Show { get; set; } + + [ClaimDetails("Show Document Template Import Status", "Can show the document template import status")] + public bool ShowStatus { get; set; } + + [ClaimDetails("Bulk Generate Document Templates", "Can bulk generate document templates")] + public bool BulkGenerate { get; set; } + + [ClaimDetails("Undetected Pages", "Can show and assign imported documents which were not undetected")] + public bool UndetectedPages { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Enrolment/EnrolmentClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Enrolment/EnrolmentClaims.cs new file mode 100644 index 00000000..8b478a07 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Enrolment/EnrolmentClaims.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Enrolment +{ + [ClaimDetails("Enrolment", "Permissions related to Device Enrolment")] + public class EnrolmentClaims + { + [ClaimDetails("Show Enrolment", "Can show device enrolment")] + public bool Show { get; set; } + + [ClaimDetails("Configure Enrolment", "Can configure device enrolment")] + public bool Configure { get; set; } + + [ClaimDetails("Show Enrolment Status", "Can show the enrolment status")] + public bool ShowStatus { get; set; } + + [ClaimDetails("Download Bootstrapper", "Can download the Device Bootstrapper")] + public bool DownloadBootstrapper { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Logging/LoggingClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Logging/LoggingClaims.cs new file mode 100644 index 00000000..44752b03 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Logging/LoggingClaims.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Logging +{ + [ClaimDetails("Logging", "Permissions related to Logging")] + public class LoggingClaims : BaseRoleClaimGroup + { + [ClaimDetails("Show Logging", "Can show logging")] + public bool Show { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Origanisation/OrganisationClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Origanisation/OrganisationClaims.cs new file mode 100644 index 00000000..203a5d57 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Origanisation/OrganisationClaims.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Origanisation +{ + [ClaimDetails("Organisation Details", "Permissions related to the Organisation Details")] + public class OrganisationClaims : BaseRoleClaimGroup + { + [ClaimDetails("Show Organisation Details", "Can show the organisation details")] + public bool Show { get; set; } + + [ClaimDetails("Configure Name", "Can configure the organisation name")] + public bool ConfigureName { get; set; } + + [ClaimDetails("Configure Logo", "Can configure the organisation logo")] + public bool ConfigureLogo { get; set; } + + [ClaimDetails("Configure Multi-Site Mode", "Can configure multi-site mode")] + public bool ConfigureMultiSiteMode { get; set; } + + [ClaimDetails("Configure Addresses", "Can configure organisation addresses")] + public bool ConfigureAddresses { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Plugin/PluginClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Plugin/PluginClaims.cs new file mode 100644 index 00000000..822b4fc9 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/Plugin/PluginClaims.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.Plugin +{ + [ClaimDetails("Plugin", "Permissions related to Plugins")] + public class PluginClaims : BaseRoleClaimGroup + { + [ClaimDetails("Show Plugins", "Can show plugins")] + public bool Show { get; set; } + + [ClaimDetails("Install/Update Plugins", "Can install and update plugins")] + public bool Install { get; set; } + + [ClaimDetails("Install/Update Local Plugins", "Can install and update locally uploaded plugins")] + public bool InstallLocal { get; set; } + + [ClaimDetails("Uninstall Plugins", "Can uninstall plugins")] + public bool Uninstall { get; set; } + + [ClaimDetails("Configure Plugins", "Can configure plugins")] + public bool Configure { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/System/SystemClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/System/SystemClaims.cs new file mode 100644 index 00000000..c54f9de8 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Configuration/System/SystemClaims.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Configuration.System +{ + [ClaimDetails("System", "Permissions related to System Configuration")] + public class SystemClaims : BaseRoleClaimGroup + { + [ClaimDetails("Show System Configuration", "Can show the system configuration")] + public bool Show { get; set; } + + [ClaimDetails("Configure Proxy Settings", "Can configure the proxy settings")] + public bool ConfigureProxy { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceActionsClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceActionsClaims.cs new file mode 100644 index 00000000..02135c86 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceActionsClaims.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Device +{ + [ClaimDetails("Actions", "Permissions related to Device Actions")] + public class DeviceActionsClaims : BaseRoleClaimGroup + { + [ClaimDetails("Allow Unauthenticated Enrol", "Can allow devices to enrol without authentication")] + public bool AllowUnauthenticatedEnrol { get; set; } + + [ClaimDetails("Assign User", "Can update the user assignment of devices")] + public bool AssignUser { get; set; } + + [ClaimDetails("Decommission", "Can decommission devices")] + public bool Decommission { get; set; } + [ClaimDetails("Recommission", "Can recommission devices")] + public bool Recommission { get; set; } + [ClaimDetails("Delete", "Can delete devices")] + public bool Delete { get; set; } + + [ClaimDetails("Add Attachments", "Can add attachments to devices")] + public bool AddAttachments { get; set; } + [ClaimDetails("Remove Any Attachments", "Can remove any attachments from devices")] + public bool RemoveAnyAttachments { get; set; } + [ClaimDetails("Remove Own Attachments", "Can remove own attachments from devices")] + public bool RemoveOwnAttachments { get; set; } + + [ClaimDetails("Generate Documents", "Can generate documents for jobs")] + public bool GenerateDocuments { get; set; } + + [ClaimDetails("Enrol Devices", "Can add devices offline and enrol devices with the Bootstrapper")] + public bool EnrolDevices { get; set; } + [ClaimDetails("Import Devices", "Can bulk import devices")] + public bool Import { get; set; } + [ClaimDetails("Export Devices", "Can export devices in a bulk format")] + public bool Export { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceClaims.cs new file mode 100644 index 00000000..d2e2372b --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DeviceClaims.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Device +{ + [ClaimDetails("Device", "Permissions related to Devices")] + public class DeviceClaims : BaseRoleClaimGroup + { + public DeviceClaims() + { + this.Properties = new DevicePropertiesClaims(); + this.Actions = new DeviceActionsClaims(); + } + + [ClaimDetails("Search Devices", "Can search devices")] + public bool Search { get; set; } + + [ClaimDetails("Show Devices", "Can show devices")] + public bool Show { get; set; } + + [ClaimDetails("Show Details", "Can show details associated with devices")] + public bool ShowDetails { get; set; } + [ClaimDetails("Show Attachments", "Can show device attachments")] + public bool ShowAttachments { get; set; } + [ClaimDetails("Show Certificates", "Can show certificates associated with devices")] + public bool ShowCertificates { get; set; } + [ClaimDetails("Show Devices Jobs", "Can show jobs associated with devices")] + public bool ShowJobs { get; set; } + [ClaimDetails("Show Assignment History", "Can show the assignment history for devices")] + public bool ShowAssignmentHistory { get; set; } + + + public DevicePropertiesClaims Properties { get; set; } + + public DeviceActionsClaims Actions { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Device/DevicePropertiesClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DevicePropertiesClaims.cs new file mode 100644 index 00000000..7a5ce4e5 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Device/DevicePropertiesClaims.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Device +{ + [ClaimDetails("Device Properties", "Permissions related to Device Properties")] + public class DevicePropertiesClaims : BaseRoleClaimGroup + { + [ClaimDetails("Device Profile Property", "Can update property")] + public bool DeviceProfile { get; set; } + + [ClaimDetails("Device Batch Property", "Can update property")] + public bool DeviceBatch { get; set; } + + [ClaimDetails("Asset Number Property", "Can update property")] + public bool AssetNumber { get; set; } + + [ClaimDetails("Location Property", "Can update property")] + public bool Location { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobActionsClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobActionsClaims.cs new file mode 100644 index 00000000..779df4dd --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobActionsClaims.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Actions", "Permissions related to Job Actions")] + public class JobActionsClaims : BaseRoleClaimGroup + { + [ClaimDetails("Create Jobs", "Can create jobs")] + public bool Create { get; set; } + [ClaimDetails("Close Jobs", "Can close jobs")] + public bool Close { get; set; } + [ClaimDetails("Force Close Jobs", "Can force close jobs")] + public bool ForceClose { get; set; } + [ClaimDetails("Reopen Jobs", "Can reopen jobs")] + public bool Reopen { get; set; } + [ClaimDetails("Delete Jobs", "Can delete jobs")] + public bool Delete { get; set; } + + [ClaimDetails("Log Warranty", "Can log warranty for jobs")] + public bool LogWarranty { get; set; } + [ClaimDetails("Log Repair", "Can log repair for non-warranty jobs")] + public bool LogRepair { get; set; } + + [ClaimDetails("Convert HWar Jobs To HNWar", "Can convert warranty jobs to non-warranty jobs")] + public bool ConvertHWarToHNWar { get; set; } + + [ClaimDetails("Add Logs", "Can add job logs")] + public bool AddLogs { get; set; } + [ClaimDetails("Remove Any Logs", "Can remove any job logs")] + public bool RemoveAnyLogs { get; set; } + [ClaimDetails("Remove Own Logs", "Can remove own job logs")] + public bool RemoveOwnLogs { get; set; } + + [ClaimDetails("Add Attachments", "Can add attachments to jobs")] + public bool AddAttachments { get; set; } + [ClaimDetails("Remove Any Attachments", "Can remove any attachments from jobs")] + public bool RemoveAnyAttachments { get; set; } + [ClaimDetails("Remove Own Attachments", "Can remove own attachments from jobs")] + public bool RemoveOwnAttachments { get; set; } + + [ClaimDetails("Generate Documents", "Can generate documents for jobs")] + public bool GenerateDocuments { get; set; } + + [ClaimDetails("Update Sub Types", "Can update sub types for jobs")] + public bool UpdateSubTypes { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobClaims.cs new file mode 100644 index 00000000..78ba49f4 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobClaims.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Job", "Permissions related to Jobs")] + public class JobClaims : BaseRoleClaimGroup + { + public JobClaims() + { + this.Lists = new JobListsClaims(); + this.Actions = new JobActionsClaims(); + this.Properties = new JobPropertiesClaims(); + this.Types = new JobTypesClaims(); + } + + [ClaimDetails("Search Jobs", "Can search jobs")] + public bool Search { get; set; } + + [ClaimDetails("Show Jobs", "Can show jobs")] + public bool Show { get; set; } + + [ClaimDetails("Show Daily Opened & Closed", "Can show daily opened & closed chart")] + public bool ShowDailyChart { get; set; } + + [ClaimDetails("Show Logs", "Can show job logs")] + public bool ShowLogs { get; set; } + [ClaimDetails("Show Attachments", "Can show job attachments")] + public bool ShowAttachments { get; set; } + + [ClaimDetails("Show Non-Warranty Components", "Can show non-warranty job components")] + public bool ShowNonWarrantyComponents { get; set; } + [ClaimDetails("Show Non-Warranty Finance", "Can show non-warranty job finance")] + public bool ShowNonWarrantyFinance { get; set; } + [ClaimDetails("Show Non-Warranty Repairs", "Can show non-warranty job repairs")] + public bool ShowNonWarrantyRepairs { get; set; } + [ClaimDetails("Show Non-Warranty Insurance", "Can show non-warranty job insurance")] + public bool ShowNonWarrantyInsurance { get; set; } + + [ClaimDetails("Show Warranty", "Can show job warranty")] + public bool ShowWarranty { get; set; } + + [ClaimDetails("Show Flags", "Can show job flags")] + public bool ShowFlags { get; set; } + + public JobListsClaims Lists { get; set; } + + public JobActionsClaims Actions { get; set; } + + public JobPropertiesClaims Properties { get; set; } + + public JobTypesClaims Types { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobListsClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobListsClaims.cs new file mode 100644 index 00000000..f89336e5 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobListsClaims.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Lists", "Permissions related to Job Lists")] + public class JobListsClaims : BaseRoleClaimGroup + { + [ClaimDetails("Awaiting Technician Action List", "Can show list")] + public bool AwaitingTechnicianAction { get; set; } + [ClaimDetails("Long Running Jobs List", "Can show list")] + public bool LongRunningJobs { get; set; } + + [ClaimDetails("All Open List", "Can show list")] + public bool AllOpen { get; set; } + [ClaimDetails("Devices Ready For Return List", "Can show list")] + public bool DevicesReadyForReturn { get; set; } + [ClaimDetails("Devices Awaiting Repair List", "Can show list")] + public bool DevicesAwaitingRepair { get; set; } + + [ClaimDetails("Awaiting Finance List", "Can show list")] + public bool AwaitingFinance { get; set; } + + [ClaimDetails("Awaiting Finance Charge List", "Can show list (NOTE: Requires Awaiting Finance List)")] + public bool AwaitingFinanceCharge { get; set; } + [ClaimDetails("Awaiting Finance Payment List", "Can show list (NOTE: Requires Awaiting Finance List)")] + public bool AwaitingFinancePayment { get; set; } + [ClaimDetails("Awaiting Finance Insurance Processing List", "Can show list (NOTE: Requires Awaiting Finance List)")] + public bool AwaitingFinanceInsuranceProcessing { get; set; } + [ClaimDetails("Awaiting Finance Agreement Breach List", "Can show list (NOTE: Requires Awaiting Finance List)")] + public bool AwaitingFinanceAgreementBreach { get; set; } + + [ClaimDetails("Awaiting User Action List", "Can show list")] + public bool AwaitingUserAction { get; set; } + [ClaimDetails("Recently Closed List", "Can show list")] + public bool RecentlyClosed { get; set; } + [ClaimDetails("Locations List", "Can show list")] + public bool Locations { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobNonWarrantyPropertiesClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobNonWarrantyPropertiesClaims.cs new file mode 100644 index 00000000..80026bc8 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobNonWarrantyPropertiesClaims.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Non Warranty Properties", "Permissions related to Non-Warranty Job Properties")] + public class JobNonWarrantyPropertiesClaims : BaseRoleClaimGroup + { + [ClaimDetails("Add Components", "Can add job components (NOTE: Requires Edit Components)")] + public bool AddComponents { get; set; } + [ClaimDetails("Edit Components", "Can edit and remove job components")] + public bool EditComponents { get; set; } + + [ClaimDetails("Is Insurance Claim Property", "Can update property")] + public bool IsInsuranceClaim { get; set; } + + [ClaimDetails("Insurance Claim Form Sent Property", "Can update property")] + public bool InsuranceClaimFormSent { get; set; } + + [ClaimDetails("Accounting Charge Required Property", "Can update property")] + public bool AccountingChargeRequired { get; set; } + [ClaimDetails("Accounting Charge Added Property", "Can update property")] + public bool AccountingChargeAdded { get; set; } + [ClaimDetails("Accounting Charge Paid Property", "Can update property")] + public bool AccountingChargePaid { get; set; } + [ClaimDetails("Purchase Order Raised Property", "Can update property")] + public bool PurchaseOrderRaised { get; set; } + [ClaimDetails("Purchase Order Reference Property", "Can update property")] + public bool PurchaseOrderReference { get; set; } + [ClaimDetails("Purchase Order Sent Property", "Can update property")] + public bool PurchaseOrderSent { get; set; } + [ClaimDetails("Invoice Received Property", "Can update property")] + public bool InvoiceReceived { get; set; } + + [ClaimDetails("Repairer Name Property", "Can update property")] + public bool RepairerName { get; set; } + [ClaimDetails("Repairer Completed Date Property", "Can update property")] + public bool RepairerCompletedDate { get; set; } + [ClaimDetails("Repairer Logged Date Property", "Can update property")] + public bool RepairerLoggedDate { get; set; } + [ClaimDetails("Repairer Reference Property", "Can update property")] + public bool RepairerReference { get; set; } + + [ClaimDetails("Insurance Detail Properties", "Can update insurance detail properties")] + public bool InsuranceDetails { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobPropertiesClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobPropertiesClaims.cs new file mode 100644 index 00000000..de2ecd5c --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobPropertiesClaims.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Job Properties", "Permissions related to Job Properties")] + public class JobPropertiesClaims : BaseRoleClaimGroup + { + public JobPropertiesClaims() + { + this.WarrantyProperties = new JobWarrantyPropertiesClaims(); + this.NonWarrantyProperties = new JobNonWarrantyPropertiesClaims(); + } + + public JobWarrantyPropertiesClaims WarrantyProperties { get; set; } + public JobNonWarrantyPropertiesClaims NonWarrantyProperties { get; set; } + + [ClaimDetails("Device Held Property", "Can update property")] + public bool DeviceHeld { get; set; } + [ClaimDetails("Device Ready For Return Property", "Can update property")] + public bool DeviceReadyForReturn { get; set; } + [ClaimDetails("Device Returned Property", "Can update property")] + public bool DeviceReturned { get; set; } + [ClaimDetails("Waiting For User Action Property", "Can update property")] + public bool WaitingForUserAction { get; set; } + [ClaimDetails("Not Waiting For User Action Property", "Can update property")] + public bool NotWaitingForUserAction { get; set; } + + [ClaimDetails("Flags Property", "Can update property")] + public bool Flags { get; set; } + + [ClaimDetails("Expected Closed Date Property", "Can update property")] + public bool ExpectedClosedDate { get; set; } + [ClaimDetails("Device Held Location Property", "Can update property")] + public bool DeviceHeldLocation { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobTypesClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobTypesClaims.cs new file mode 100644 index 00000000..1b54eada --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobTypesClaims.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Types", "Permissions related to Job Types")] + public class JobTypesClaims : BaseRoleClaimGroup + { + [ClaimDetails("Show Hardware - Miscellaneous Jobs", "Can show jobs of this type")] + public bool ShowHMisc { get; set; } + [ClaimDetails("Show Hardware - Non-Warranty Jobs", "Can show jobs of this type")] + public bool ShowHNWar { get; set; } + [ClaimDetails("Show Hardware - Warranty Jobs", "Can show jobs of this type")] + public bool ShowHWar { get; set; } + + [ClaimDetails("Show Software - Application Jobs", "Can show jobs of this type")] + public bool ShowSApp { get; set; } + [ClaimDetails("Show Software - Reimage Jobs", "Can show jobs of this type")] + public bool ShowSImg { get; set; } + [ClaimDetails("Show Software - Operating System Jobs", "Can show jobs of this type")] + public bool ShowSOS { get; set; } + + [ClaimDetails("Show User Management Jobs", "Can show jobs of this type")] + public bool ShowUMgmt { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobWarrantyPropertiesClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobWarrantyPropertiesClaims.cs new file mode 100644 index 00000000..c2a7c491 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/Job/JobWarrantyPropertiesClaims.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.Job +{ + [ClaimDetails("Warranty Properties", "Permissions related to Warranty Job Properties")] + public class JobWarrantyPropertiesClaims : BaseRoleClaimGroup + { + [ClaimDetails("Warranty Completed Property", "Can update property")] + public bool WarrantyCompleted { get; set; } + + [ClaimDetails("External Name Property", "Can update property")] + public bool ExternalName { get; set; } + [ClaimDetails("External Logged Date Property", "Can update property")] + public bool ExternalLoggedDate { get; set; } + [ClaimDetails("External Reference Property", "Can update property")] + public bool ExternalReference { get; set; } + [ClaimDetails("External Completed Date Property", "Can update property")] + public bool ExternalCompletedDate { get; set; } + + [ClaimDetails("Provider Details", "Can access warranty provider details")] + public bool ProviderDetails { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/User/UserActionsClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/User/UserActionsClaims.cs new file mode 100644 index 00000000..913fdf96 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/User/UserActionsClaims.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.User +{ + [ClaimDetails("Actions", "Permissions related to User Actions")] + public class UserActionsClaims : BaseRoleClaimGroup + { + [ClaimDetails("Add Attachments", "Can add attachments to users")] + public bool AddAttachments { get; set; } + [ClaimDetails("Remove Any Attachments", "Can remove any attachments from users")] + public bool RemoveAnyAttachments { get; set; } + [ClaimDetails("Remove Own Attachments", "Can remove own attachments from users")] + public bool RemoveOwnAttachments { get; set; } + + [ClaimDetails("Generate Documents", "Can generate documents for users")] + public bool GenerateDocuments { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/ClaimGroups/User/UserClaims.cs b/Disco.Services/Authorization/Roles/ClaimGroups/User/UserClaims.cs new file mode 100644 index 00000000..5437d4f0 --- /dev/null +++ b/Disco.Services/Authorization/Roles/ClaimGroups/User/UserClaims.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles.ClaimGroups.User +{ + [ClaimDetails("User", "Permissions related to Users")] + public class UserClaims : BaseRoleClaimGroup + { + public UserClaims() + { + this.Actions = new UserActionsClaims(); + } + + [ClaimDetails("Search Users", "Can search users")] + public bool Search { get; set; } + + [ClaimDetails("Show Users", "Can show users")] + public bool Show { get; set; } + + [ClaimDetails("Show Attachments", "Can show user attachments")] + public bool ShowAttachments { get; set; } + + [ClaimDetails("Show Device Assignment History", "Can show the device assignment history for users")] + public bool ShowAssignmentHistory { get; set; } + + [ClaimDetails("Show Users Jobs", "Can show jobs associated with users")] + public bool ShowJobs { get; set; } + + [ClaimDetails("Show Users Authorization", "Can show authorization permissions associated with users")] + public bool ShowAuthorization { get; set; } + + public UserActionsClaims Actions { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/RoleCache.cs b/Disco.Services/Authorization/Roles/RoleCache.cs new file mode 100644 index 00000000..28497f99 --- /dev/null +++ b/Disco.Services/Authorization/Roles/RoleCache.cs @@ -0,0 +1,106 @@ +using Disco.Data.Repository; +using Disco.Models.Authorization; +using Disco.Models.Repository; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles +{ + public static class RoleCache + { + internal const int AdministratorsTokenId = -1; + internal const int ComputerAccountTokenId = -200; + internal const string AdministratorsTokenSubjectIds = "Domain Admins,Disco Admins"; + internal const string ClaimsJsonEmpty = "null"; + + private static List _Cache; + + internal static void Initialize(DiscoDataContext Database) + { + _Cache = Database.AuthorizationRoles.ToList().Select(ar => RoleToken.FromAuthorizationRole(ar)).ToList(); + + // Add System Roles + AddSystemRoles(); + } + + private static void AddSystemRoles() + { + // Disco Administrators + _Cache.Add(RoleToken.FromAuthorizationRole(new AuthorizationRole() + { + Id = AdministratorsTokenId, + Name = "Disco Administrators", + SubjectIds = AdministratorsTokenSubjectIds + }, Claims.AdministratorClaims())); + + // Computer Accounts + _Cache.Add(RoleToken.FromAuthorizationRole(new AuthorizationRole() + { + Id = ComputerAccountTokenId, + Name = "Domain Computer Account" + }, Claims.ComputerAccountClaims())); + } + + /// + /// Create a clone of an Authorization Role + /// Creates immutable clones to avoid side-effects + /// + /// Authorization Role to Clone + /// A copy of the Authorization Role + private static AuthorizationRole CloneAuthoriationRole(AuthorizationRole TemplateRole) + { + return new AuthorizationRole() + { + Id = TemplateRole.Id, + Name = TemplateRole.Name, + ClaimsJson = TemplateRole.ClaimsJson, + SubjectIds = TemplateRole.SubjectIds + }; + } + + internal static RoleToken AddRole(AuthorizationRole Role) + { + var token = RoleToken.FromAuthorizationRole(CloneAuthoriationRole(Role)); + _Cache.Add(token); + return token; + } + + internal static void RemoveRole(AuthorizationRole Role) + { + var token = GetRoleToken(Role.Id); + if (token != null) + _Cache.Remove(token); + } + + internal static RoleToken UpdateRole(AuthorizationRole Role) + { + RemoveRole(Role); + return AddRole(Role); + } + + internal static RoleToken GetRoleToken(int Id) + { + return _Cache.FirstOrDefault(t => t.Role.Id == Id); + } + internal static RoleToken GetRoleToken(string SecurityGroup) + { + return _Cache.FirstOrDefault(t => t.SubjectIdHashes.Contains(SecurityGroup.ToLower())); + } + internal static List GetRoleTokens(IEnumerable SecurityGroup) + { + var securityGroups = SecurityGroup.Select(sg => sg.ToLower()); + + return _Cache.Where(t => securityGroups.Any(sg => t.SubjectIdHashes.Contains(sg))).Cast().ToList(); + } + internal static List GetRoleTokens(IEnumerable SecurityGroup, User User) + { + var subjectIds = (new string[] { User.Id }).Concat(SecurityGroup).Select(sg => sg.ToLower()); + + return _Cache.Where(t => subjectIds.Any(sg => t.SubjectIdHashes.Contains(sg))).Cast().ToList(); + } + } +} diff --git a/Disco.Services/Authorization/Roles/RoleClaims.cs b/Disco.Services/Authorization/Roles/RoleClaims.cs new file mode 100644 index 00000000..0add33a9 --- /dev/null +++ b/Disco.Services/Authorization/Roles/RoleClaims.cs @@ -0,0 +1,39 @@ +using Disco.Services.Authorization.Roles.ClaimGroups; +using Disco.Services.Authorization.Roles.ClaimGroups.Configuration; +using Disco.Services.Authorization.Roles.ClaimGroups.Device; +using Disco.Services.Authorization.Roles.ClaimGroups.Job; +using Disco.Services.Authorization.Roles.ClaimGroups.User; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles +{ + public class RoleClaims : BaseRoleClaimGroup + { + public RoleClaims() + { + this.Config = new ConfigClaims(); + + this.Job = new JobClaims(); + this.Device = new DeviceClaims(); + this.User = new UserClaims(); + } + + [ClaimDetails("Computer Account", "Represents a computer account", true)] + public bool ComputerAccount { get; set; } + + [ClaimDetails("Disco Administrator Account", "Represents a Disco Administrator account", true)] + public bool DiscoAdminAccount { get; set; } + + public ConfigClaims Config { get; set; } + + public JobClaims Job { get; set; } + + public DeviceClaims Device { get; set; } + + public UserClaims User { get; set; } + } +} diff --git a/Disco.Services/Authorization/Roles/RoleToken.cs b/Disco.Services/Authorization/Roles/RoleToken.cs new file mode 100644 index 00000000..0c78e10b --- /dev/null +++ b/Disco.Services/Authorization/Roles/RoleToken.cs @@ -0,0 +1,39 @@ +using Disco.Models.Authorization; +using Disco.Models.Repository; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Authorization.Roles +{ + public class RoleToken : IRoleToken + { + public AuthorizationRole Role { get; set; } + internal HashSet SubjectIdHashes { get; set; } + public List SubjectIds { get; set; } + public RoleClaims Claims { get; set; } + + public static RoleToken FromAuthorizationRole(AuthorizationRole Role) + { + var claims = JsonConvert.DeserializeObject(Role.ClaimsJson); + + return FromAuthorizationRole(Role, claims); + } + + internal static RoleToken FromAuthorizationRole(AuthorizationRole Role, RoleClaims Claims) + { + string[] sg = (Role.SubjectIds == null ? new string[0] : Role.SubjectIds.Split(',').ToArray()); + + return new RoleToken() + { + Role = Role, + SubjectIdHashes = new HashSet(sg.Select(i => i.ToLower())), + SubjectIds = sg.ToList(), + Claims = Claims + }; + } + } +} diff --git a/Disco.Services/Disco.Services.csproj b/Disco.Services/Disco.Services.csproj index 43aa97a8..21817985 100644 --- a/Disco.Services/Disco.Services.csproj +++ b/Disco.Services/Disco.Services.csproj @@ -73,6 +73,7 @@ True ..\packages\Microsoft.SqlServer.Compact.4.0.8876.1\lib\net40\System.Data.SqlServerCe.dll + @@ -88,6 +89,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + True + Claims.tt + + + + + + + @@ -141,6 +181,19 @@ + + + + + + + + + + + + + @@ -154,8 +207,15 @@ + + TextTemplatingFileGenerator + Claims.cs + + + + diff --git a/Disco.Services/Logging/LogContext.cs b/Disco.Services/Logging/LogContext.cs index d1dfd317..d0e3733e 100644 --- a/Disco.Services/Logging/LogContext.cs +++ b/Disco.Services/Logging/LogContext.cs @@ -70,10 +70,10 @@ namespace Disco.Services.Logging } } - private static void InitalizeDatabase(Targets.LogPersistContext logDbContext) + private static void InitalizeDatabase(Targets.LogPersistContext LogDatabase) { // Add Modules - var existingModules = logDbContext.Modules.Include("EventTypes").ToDictionary(m => m.Id); + var existingModules = LogDatabase.Modules.Include("EventTypes").ToDictionary(m => m.Id); foreach (var module in LogModules) { // Update/Insert Module @@ -95,7 +95,7 @@ namespace Disco.Services.Logging Name = module.Value.ModuleName, Description = module.Value.ModuleDescription }; - logDbContext.Modules.Add(dbModule); + LogDatabase.Modules.Add(dbModule); } // Update/Insert Event Types Dictionary existingEventTypes = (dbModule.EventTypes == null) ? new Dictionary() : dbModule.EventTypes.ToDictionary(et => et.Id); @@ -123,17 +123,17 @@ namespace Disco.Services.Logging Severity = eventType.Value.Severity, Format = eventType.Value.Format }; - logDbContext.EventTypes.Add(dbEventType); + LogDatabase.EventTypes.Add(dbEventType); } } } - logDbContext.SaveChanges(); + LogDatabase.SaveChanges(); } - public static string LogFileBasePath(DiscoDataContext DiscoContext) + public static string LogFileBasePath(DiscoDataContext Database) { - var logDirectoryBase = Path.Combine(DiscoContext.DiscoConfiguration.DataStoreLocation, "Logs"); + var logDirectoryBase = Path.Combine(Database.DiscoConfiguration.DataStoreLocation, "Logs"); // Create Directory Structure if (!Directory.Exists(logDirectoryBase)) { @@ -155,9 +155,9 @@ namespace Disco.Services.Logging return logDirectoryBase; } - public static string LogFilePath(DiscoDataContext DiscoContext, DateTime Date, bool CreateDirectory = true) + public static string LogFilePath(DiscoDataContext Database, DateTime Date, bool CreateDirectory = true) { - var logDirectoryBase = LogFileBasePath(DiscoContext); + var logDirectoryBase = LogFileBasePath(Database); var logDirectory = Path.Combine(logDirectoryBase, Date.Year.ToString()); if (CreateDirectory && !Directory.Exists(logDirectory)) { @@ -167,11 +167,11 @@ namespace Disco.Services.Logging return Path.Combine(logDirectory, logFileName); } - internal static void ReInitalize(DiscoDataContext DiscoContext) + internal static void ReInitalize(DiscoDataContext Database) { lock (_CurrentLock) { - var logPath = LogFilePath(DiscoContext, DateTime.Today); + var logPath = LogFilePath(Database, DateTime.Today); //var connectionString = string.Format("Data Source=\"{0}\"", logPath); @@ -204,7 +204,7 @@ namespace Disco.Services.Logging try { // Get Yesterdays Log - var yesterdaysLogPath = LogFilePath(DiscoContext, DateTime.Today.AddDays(-1), false); + var yesterdaysLogPath = LogFilePath(Database, DateTime.Today.AddDays(-1), false); if (File.Exists(yesterdaysLogPath)) { SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder(); @@ -229,9 +229,9 @@ namespace Disco.Services.Logging } private static IScheduler _ReInitializeScheduler; - public static void Initalize(DiscoDataContext DiscoContext, ISchedulerFactory SchedulerFactory) + public static void Initalize(DiscoDataContext Database, ISchedulerFactory SchedulerFactory) { - ReInitalize(DiscoContext); + ReInitalize(Database); _ReInitializeScheduler = SchedulerFactory.GetScheduler(); diff --git a/Disco.Services/Logging/LogReInitalizeJob.cs b/Disco.Services/Logging/LogReInitalizeJob.cs index 064c1120..176a501a 100644 --- a/Disco.Services/Logging/LogReInitalizeJob.cs +++ b/Disco.Services/Logging/LogReInitalizeJob.cs @@ -11,9 +11,9 @@ namespace Disco.Services.Logging { public void Execute(IJobExecutionContext context) { - using (DiscoDataContext DiscoContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - LogContext.ReInitalize(DiscoContext); + LogContext.ReInitalize(database); } } } diff --git a/Disco.Services/Logging/ReadLogContext.cs b/Disco.Services/Logging/ReadLogContext.cs index e46a9108..5d8093b9 100644 --- a/Disco.Services/Logging/ReadLogContext.cs +++ b/Disco.Services/Logging/ReadLogContext.cs @@ -29,14 +29,14 @@ namespace Disco.Services.Logging return true; } - public List Query(DiscoDataContext DiscoContext) + public List Query(DiscoDataContext Database) { List results = new List(); // Validate Options this.Validate(); - var relevantLogFiles = RelevantLogFiles(DiscoContext); + var relevantLogFiles = RelevantLogFiles(Database); relevantLogFiles.Reverse(); foreach (var logFile in relevantLogFiles) { @@ -73,10 +73,10 @@ namespace Disco.Services.Logging } } - private List> RelevantLogFiles(DiscoDataContext DiscoContext) + private List> RelevantLogFiles(DiscoDataContext Database) { List> relevantFiles = new List>(); - var logDirectoryBase = LogContext.LogFileBasePath(DiscoContext); + var logDirectoryBase = LogContext.LogFileBasePath(Database); var logDirectoryBaseInfo = new DirectoryInfo(logDirectoryBase); var endDate = this.End.HasValue ? this.End.Value : DateTime.Now; var endDateYear = endDate.Year.ToString(); @@ -91,7 +91,7 @@ namespace Disco.Services.Logging var queryDate = this.Start.Value.Date; while (queryDate <= endDate) { - var fileName = LogContext.LogFilePath(DiscoContext, queryDate, false); + var fileName = LogContext.LogFilePath(Database, queryDate, false); if (File.Exists(fileName)) relevantFiles.Add(new Tuple(fileName, LogFileDate(fileName).Value)); diff --git a/Disco.Services/Plugins/CommunityInterop/PluginLibraryUpdateTask.cs b/Disco.Services/Plugins/CommunityInterop/PluginLibraryUpdateTask.cs index e3531cea..756b69a9 100644 --- a/Disco.Services/Plugins/CommunityInterop/PluginLibraryUpdateTask.cs +++ b/Disco.Services/Plugins/CommunityInterop/PluginLibraryUpdateTask.cs @@ -48,13 +48,13 @@ namespace Disco.Services.Plugins.CommunityInterop Status.UpdateStatus(1, "Updating Plugin Library Catalogue", "Building Request"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - catalogueFile = Plugins.CatalogueFile(dbContext); + catalogueFile = Plugins.CatalogueFile(database); updateRequestBody = new PluginLibraryUpdateRequest() { - DeploymentId = dbContext.DiscoConfiguration.DeploymentId, + DeploymentId = database.DiscoConfiguration.DeploymentId, HostVersion = typeof(Plugins).Assembly.GetName().Version.ToString(4) }; } @@ -111,13 +111,13 @@ namespace Disco.Services.Plugins.CommunityInterop Status.UpdateStatus(50, "Updating Plugin Library Compatibility", "Building Request"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - compatibilityFile = Plugins.CompatibilityFile(dbContext); + compatibilityFile = Plugins.CompatibilityFile(database); compatRequestBody = new PluginLibraryCompatibilityRequest() { - DeploymentId = dbContext.DiscoConfiguration.DeploymentId, + DeploymentId = database.DiscoConfiguration.DeploymentId, HostVersion = typeof(Plugins).Assembly.GetName().Version.ToString(4) }; } @@ -200,7 +200,7 @@ namespace Disco.Services.Plugins.CommunityInterop } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Random time between midday and midnight. var rnd = new Random(); diff --git a/Disco.Services/Plugins/Features/CertificateProvider/CertificateProviderFeature.cs b/Disco.Services/Plugins/Features/CertificateProvider/CertificateProviderFeature.cs index 2a5d58df..9badac55 100644 --- a/Disco.Services/Plugins/Features/CertificateProvider/CertificateProviderFeature.cs +++ b/Disco.Services/Plugins/Features/CertificateProvider/CertificateProviderFeature.cs @@ -13,6 +13,6 @@ namespace Disco.Services.Plugins.Features.CertificateProvider { // Certificate Plugin Requirements public abstract string CertificateProviderId { get; } - public abstract Tuple> AllocateCertificate(DiscoDataContext dbContext, Device Device); + public abstract Tuple> AllocateCertificate(DiscoDataContext Database, Device Device); } } diff --git a/Disco.Services/Plugins/Features/WarrantyProvider/WarrantyProviderFeature.cs b/Disco.Services/Plugins/Features/WarrantyProvider/WarrantyProviderFeature.cs index 1ec10e17..ec670b43 100644 --- a/Disco.Services/Plugins/Features/WarrantyProvider/WarrantyProviderFeature.cs +++ b/Disco.Services/Plugins/Features/WarrantyProvider/WarrantyProviderFeature.cs @@ -16,14 +16,14 @@ namespace Disco.Services.Plugins.Features.WarrantyProvider // Warranty Plugin Requirements public abstract string WarrantyProviderId { get; } public abstract Type SubmitJobViewType { get; } - public abstract dynamic SubmitJobViewModel(DiscoDataContext dbContext, Controller controller, Job Job, OrganisationAddress Address, User TechUser); - public abstract Dictionary SubmitJobParseProperties(DiscoDataContext dbContext, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription); - public abstract Dictionary SubmitJobDiscloseInfo(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary WarrantyProviderProperties); - public abstract string SubmitJob(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary WarrantyProviderProperties); + public abstract dynamic SubmitJobViewModel(DiscoDataContext Database, Controller controller, Job Job, OrganisationAddress Address, User TechUser); + public abstract Dictionary SubmitJobParseProperties(DiscoDataContext Database, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription); + public abstract Dictionary SubmitJobDiscloseInfo(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary WarrantyProviderProperties); + public abstract string SubmitJob(DiscoDataContext Database, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary WarrantyProviderProperties); public abstract Type JobDetailsViewType { get; } public bool JobDetailsSupported { get { return this.JobDetailsViewType != null; } } - public abstract dynamic JobDetailsViewModel(DiscoDataContext dbContext, Controller controller, Job Job); + public abstract dynamic JobDetailsViewModel(DiscoDataContext Database, Controller controller, Job Job); public static PluginFeatureManifest FindPluginFeature(string PluginIdOrWarrantyProviderId) { diff --git a/Disco.Services/Plugins/InstallPluginTask.cs b/Disco.Services/Plugins/InstallPluginTask.cs index a0fdd8c6..afe36b8d 100644 --- a/Disco.Services/Plugins/InstallPluginTask.cs +++ b/Disco.Services/Plugins/InstallPluginTask.cs @@ -95,12 +95,12 @@ namespace Disco.Services.Plugins if (Plugins.GetPlugins().FirstOrDefault(p => p.Id == packageManifest.Id) != null) throw new InvalidOperationException(string.Format("The '{0} [{1}]' Plugin is already installed, please uninstall any existing versions before trying again", packageManifest.Name, packageManifest.Id)); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - string packagePath = Path.Combine(dbContext.DiscoConfiguration.PluginsLocation, packageManifest.Id); + string packagePath = Path.Combine(database.DiscoConfiguration.PluginsLocation, packageManifest.Id); // Check for Compatibility - var compatibilityData = Plugins.LoadCompatibilityData(dbContext); + var compatibilityData = Plugins.LoadCompatibilityData(database); var pluginCompatibility = compatibilityData.Plugins.FirstOrDefault(i => i.Id.Equals(packageManifest.Id, StringComparison.InvariantCultureIgnoreCase) && packageManifest.Version == Version.Parse(i.Version)); if (pluginCompatibility != null && !pluginCompatibility.Compatible) throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", packageManifest.Id, packageManifest.VersionFormatted, pluginCompatibility.Reason)); @@ -144,11 +144,11 @@ namespace Disco.Services.Plugins // Install Plugin this.Status.UpdateStatus(80, "Initial Package Configuration"); - packageManifest.InstallPlugin(dbContext, this.Status); + packageManifest.InstallPlugin(database, this.Status); // Initialize Plugin this.Status.UpdateStatus(98, "Initializing Plugin for Use"); - packageManifest.InitializePlugin(dbContext); + packageManifest.InitializePlugin(database); // Add Plugin Manifest to Host Environment Plugins.AddPlugin(packageManifest); diff --git a/Disco.Services/Plugins/Plugin.cs b/Disco.Services/Plugins/Plugin.cs index 1296467b..68ad7ac3 100644 --- a/Disco.Services/Plugins/Plugin.cs +++ b/Disco.Services/Plugins/Plugin.cs @@ -14,10 +14,10 @@ namespace Disco.Services.Plugins #region Lifecycle // Events/Triggers for Custom Plugin Initialization (Optional) - public virtual void Install(DiscoDataContext dbContext, ScheduledTaskStatus Status) { return; } - public virtual void Initialize(DiscoDataContext dbContext) { return; } - public virtual void Uninstall(DiscoDataContext dbContext, bool UninstallData, ScheduledTaskStatus Status) { return; } - public virtual void AfterUpdate(DiscoDataContext dbContext, PluginManifest PreviousManifest) { return; } + public virtual void Install(DiscoDataContext Database, ScheduledTaskStatus Status) { return; } + public virtual void Initialize(DiscoDataContext Database) { return; } + public virtual void Uninstall(DiscoDataContext Database, bool UninstallData, ScheduledTaskStatus Status) { return; } + public virtual void AfterUpdate(DiscoDataContext Database, PluginManifest PreviousManifest) { return; } #endregion public virtual void Dispose() diff --git a/Disco.Services/Plugins/PluginConfigurationHandler.cs b/Disco.Services/Plugins/PluginConfigurationHandler.cs index 25964f7a..39fd7aab 100644 --- a/Disco.Services/Plugins/PluginConfigurationHandler.cs +++ b/Disco.Services/Plugins/PluginConfigurationHandler.cs @@ -12,8 +12,8 @@ namespace Disco.Services.Plugins { public PluginManifest Manifest { get; set; } - public abstract PluginConfigurationHandlerGetResponse Get(DiscoDataContext dbContext, Controller controller); - public abstract bool Post(DiscoDataContext dbContext, FormCollection form, Controller controller); + public abstract PluginConfigurationHandlerGetResponse Get(DiscoDataContext Database, Controller controller); + public abstract bool Post(DiscoDataContext Database, FormCollection form, Controller controller); public virtual void Dispose() { diff --git a/Disco.Services/Plugins/PluginFeature.cs b/Disco.Services/Plugins/PluginFeature.cs index 58bfc5cf..35cc8508 100644 --- a/Disco.Services/Plugins/PluginFeature.cs +++ b/Disco.Services/Plugins/PluginFeature.cs @@ -12,7 +12,7 @@ namespace Disco.Services.Plugins public PluginFeatureManifest Manifest {get; internal set;} // Allow Custom Initialization (Optional) - public virtual void Initialize(DiscoDataContext dbContext) { return; } + public virtual void Initialize(DiscoDataContext Database) { return; } public virtual void Dispose() { diff --git a/Disco.Services/Plugins/PluginFeatureManifest.cs b/Disco.Services/Plugins/PluginFeatureManifest.cs index c9f47b25..1f6c7b0d 100644 --- a/Disco.Services/Plugins/PluginFeatureManifest.cs +++ b/Disco.Services/Plugins/PluginFeatureManifest.cs @@ -26,7 +26,7 @@ namespace Disco.Services.Plugins [JsonIgnore] public Type CategoryType { get; private set; } - internal bool Initialize(DiscoDataContext dbContext, PluginManifest pluginManifest) + internal bool Initialize(DiscoDataContext Database, PluginManifest pluginManifest) { this.PluginManifest = pluginManifest; @@ -38,7 +38,7 @@ namespace Disco.Services.Plugins using (var instance = this.CreateInstance()) { - instance.Initialize(dbContext); + instance.Initialize(Database); } PluginsLog.LogInitializedPluginFeature(this.PluginManifest, this); diff --git a/Disco.Services/Plugins/PluginManifest.cs b/Disco.Services/Plugins/PluginManifest.cs index d6f16ade..8488a1ee 100644 --- a/Disco.Services/Plugins/PluginManifest.cs +++ b/Disco.Services/Plugins/PluginManifest.cs @@ -284,7 +284,7 @@ namespace Disco.Services.Plugins { return JsonConvert.SerializeObject(this, Formatting.Indented, new VersionConverter()); } - private bool InitializePluginEnvironment(DiscoDataContext dbContext) + private bool InitializePluginEnvironment(DiscoDataContext Database) { if (!environmentInitalized) { @@ -316,58 +316,58 @@ namespace Disco.Services.Plugins this.WebHandlerType = this.PluginAssembly.GetType(this.WebHandlerTypeName, true, true); // Update non-static values - this.StorageLocation = Path.Combine(dbContext.DiscoConfiguration.PluginStorageLocation, this.Id); + this.StorageLocation = Path.Combine(Database.DiscoConfiguration.PluginStorageLocation, this.Id); environmentInitalized = true; } return true; } - internal bool AfterPluginUpdate(DiscoDataContext dbContext, PluginManifest PreviousManifest) + internal bool AfterPluginUpdate(DiscoDataContext Database, PluginManifest PreviousManifest) { // Initialize Plugin - InitializePluginEnvironment(dbContext); + InitializePluginEnvironment(Database); using (var pluginInstance = this.CreateInstance()) { - pluginInstance.AfterUpdate(dbContext, PreviousManifest); + pluginInstance.AfterUpdate(Database, PreviousManifest); } return true; } - internal bool UninstallPlugin(DiscoDataContext dbContext, bool UninstallData, ScheduledTaskStatus Status) + internal bool UninstallPlugin(DiscoDataContext Database, bool UninstallData, ScheduledTaskStatus Status) { // Initialize Plugin - InitializePluginEnvironment(dbContext); + InitializePluginEnvironment(Database); using (var pluginInstance = this.CreateInstance()) { - pluginInstance.Uninstall(dbContext, UninstallData, Status); + pluginInstance.Uninstall(Database, UninstallData, Status); } return true; } - internal bool InstallPlugin(DiscoDataContext dbContext, ScheduledTaskStatus Status) + internal bool InstallPlugin(DiscoDataContext Database, ScheduledTaskStatus Status) { // Initialize Plugin - InitializePluginEnvironment(dbContext); + InitializePluginEnvironment(Database); using (var pluginInstance = this.CreateInstance()) { - pluginInstance.Install(dbContext, Status); + pluginInstance.Install(Database, Status); } return true; } - internal bool InitializePlugin(DiscoDataContext dbContext) + internal bool InitializePlugin(DiscoDataContext Database) { // Initialize Plugin - InitializePluginEnvironment(dbContext); + InitializePluginEnvironment(Database); // Initialize Plugin using (var pluginInstance = this.CreateInstance()) { - pluginInstance.Initialize(dbContext); + pluginInstance.Initialize(Database); } PluginsLog.LogInitializedPlugin(this); @@ -376,7 +376,7 @@ namespace Disco.Services.Plugins { foreach (var feature in Features) { - feature.Initialize(dbContext, this); + feature.Initialize(Database, this); } } else diff --git a/Disco.Services/Plugins/Plugins.cs b/Disco.Services/Plugins/Plugins.cs index 55aec941..b1e1d3be 100644 --- a/Disco.Services/Plugins/Plugins.cs +++ b/Disco.Services/Plugins/Plugins.cs @@ -250,18 +250,18 @@ namespace Disco.Services.Plugins throw new InvalidOperationException(string.Format("Unknown Plugin Feature Category Type: [{0}]", FeatureCategoryType.Name)); } - public static string CatalogueFile(DiscoDataContext dbContext) + public static string CatalogueFile(DiscoDataContext Database) { - return Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, "Catalogue.json"); + return Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, "Catalogue.json"); } - public static string CompatibilityFile(DiscoDataContext dbContext) + public static string CompatibilityFile(DiscoDataContext Database) { - return Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, "Compatibility.json"); + return Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, "Compatibility.json"); } - public static PluginLibraryUpdateResponse LoadCatalogue(DiscoDataContext dbContext) + public static PluginLibraryUpdateResponse LoadCatalogue(DiscoDataContext Database) { - var catalogueFile = CatalogueFile(dbContext); + var catalogueFile = CatalogueFile(Database); if (!File.Exists(catalogueFile)) return null; @@ -269,13 +269,13 @@ namespace Disco.Services.Plugins return JsonConvert.DeserializeObject(File.ReadAllText(catalogueFile)); } - public static PluginLibraryCompatibilityResponse LoadCompatibilityData(DiscoDataContext dbContext) + public static PluginLibraryCompatibilityResponse LoadCompatibilityData(DiscoDataContext Database) { var pluginAssembly = typeof(Plugins).Assembly; Version hostVersion = pluginAssembly.GetName().Version; PluginLibraryCompatibilityResponse Data = null; var localCompatFile = Path.Combine(Path.GetDirectoryName(pluginAssembly.Location), "ReleasePluginCompatibility.json"); - var serverCompatFile = CompatibilityFile(dbContext); + var serverCompatFile = CompatibilityFile(Database); if (File.Exists(localCompatFile)) { @@ -325,7 +325,7 @@ namespace Disco.Services.Plugins return Data; } - public static void InitalizePlugins(DiscoDataContext dbContext) + public static void InitalizePlugins(DiscoDataContext Database) { if (_PluginManifests == null) { @@ -334,10 +334,10 @@ namespace Disco.Services.Plugins if (_PluginManifests == null) { Version hostVersion = typeof(Plugins).Assembly.GetName().Version; - var compatibilityData = new Lazy(() => LoadCompatibilityData(dbContext)); + var compatibilityData = new Lazy(() => LoadCompatibilityData(Database)); Dictionary loadedPlugins = new Dictionary(); - PluginPath = dbContext.DiscoConfiguration.PluginsLocation; + PluginPath = Database.DiscoConfiguration.PluginsLocation; AppDomain appDomain = AppDomain.CurrentDomain; @@ -367,7 +367,7 @@ namespace Disco.Services.Plugins if (File.Exists(updatePackagePath)) { // Update Plugin - pluginManifest = UpdatePlugin(dbContext, pluginManifest, updatePackagePath, compatibilityData.Value); + pluginManifest = UpdatePlugin(Database, pluginManifest, updatePackagePath, compatibilityData.Value); } if (pluginManifest != null) @@ -382,7 +382,7 @@ namespace Disco.Services.Plugins if (pluginManifest.HostVersionMax != null && pluginManifest.HostVersionMax < hostVersion) throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] does not support this version of Disco (Support expired as of v{2})", pluginManifest.Id, pluginManifest.VersionFormatted, pluginManifest.HostVersionMax.ToString())); - pluginManifest.InitializePlugin(dbContext); + pluginManifest.InitializePlugin(Database); loadedPlugins[pluginManifest.Id] = pluginManifest; } } @@ -414,7 +414,7 @@ namespace Disco.Services.Plugins // Check for Data Removal bool DataUninstalled = false; - string pluginStorageLocation = Path.Combine(dbContext.DiscoConfiguration.PluginStorageLocation, uninstallManifest.Id); + string pluginStorageLocation = Path.Combine(Database.DiscoConfiguration.PluginStorageLocation, uninstallManifest.Id); string pluginManifestUninstallDataFilename = Path.Combine(pluginStorageLocation, "manifest.uninstall.json"); if (File.Exists(pluginManifestUninstallDataFilename)) @@ -443,13 +443,13 @@ namespace Disco.Services.Plugins _PluginAssemblyManifests = _PluginManifests.Values.ToDictionary(p => p.PluginAssembly, p => p); } - public static PluginManifest UpdatePlugin(DiscoDataContext dbContext, PluginManifest ExistingManifest, String UpdatePluginPackageFilePath, PluginLibraryCompatibilityResponse CompatibilityData = null) + public static PluginManifest UpdatePlugin(DiscoDataContext Database, PluginManifest ExistingManifest, String UpdatePluginPackageFilePath, PluginLibraryCompatibilityResponse CompatibilityData = null) { PluginManifest updatedManifest; using (var packageStream = File.OpenRead(UpdatePluginPackageFilePath)) { - updatedManifest = UpdatePlugin(dbContext, ExistingManifest, packageStream, CompatibilityData); + updatedManifest = UpdatePlugin(Database, ExistingManifest, packageStream, CompatibilityData); } // Remove Update after processing @@ -458,7 +458,7 @@ namespace Disco.Services.Plugins return updatedManifest; } - public static PluginManifest UpdatePlugin(DiscoDataContext dbContext, PluginManifest ExistingManifest, Stream UpdatePluginPackage, PluginLibraryCompatibilityResponse CompatibilityData = null) + public static PluginManifest UpdatePlugin(DiscoDataContext Database, PluginManifest ExistingManifest, Stream UpdatePluginPackage, PluginLibraryCompatibilityResponse CompatibilityData = null) { using (MemoryStream packageStream = new MemoryStream()) { @@ -495,12 +495,12 @@ namespace Disco.Services.Plugins // Check Compatibility if (CompatibilityData == null) - CompatibilityData = LoadCompatibilityData(dbContext); + CompatibilityData = LoadCompatibilityData(Database); var pluginCompatibility = CompatibilityData.Plugins.FirstOrDefault(i => i.Id.Equals(packageManifest.Id, StringComparison.InvariantCultureIgnoreCase) && packageManifest.Version == Version.Parse(i.Version)); if (pluginCompatibility != null && !pluginCompatibility.Compatible) throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", packageManifest.Id, packageManifest.VersionFormatted, pluginCompatibility.Reason)); - string packagePath = Path.Combine(dbContext.DiscoConfiguration.PluginsLocation, packageManifest.Id); + string packagePath = Path.Combine(Database.DiscoConfiguration.PluginsLocation, packageManifest.Id); // Force Delete of Existing Folder if (Directory.Exists(packagePath)) @@ -530,7 +530,7 @@ namespace Disco.Services.Plugins packageManifest = PluginManifest.FromPluginManifestFile(Path.Combine(packagePath, "manifest.json")); // Trigger AfterPluginUpdate - packageManifest.AfterPluginUpdate(dbContext, ExistingManifest); + packageManifest.AfterPluginUpdate(Database, ExistingManifest); PluginsLog.LogAfterUpdate(ExistingManifest, packageManifest); diff --git a/Disco.Services/Plugins/UninstallPluginTask.cs b/Disco.Services/Plugins/UninstallPluginTask.cs index 3d4f8628..c3fd1e1c 100644 --- a/Disco.Services/Plugins/UninstallPluginTask.cs +++ b/Disco.Services/Plugins/UninstallPluginTask.cs @@ -29,9 +29,9 @@ namespace Disco.Services.Plugins if (!File.Exists(manifestFileLocation)) throw new FileNotFoundException("Plugin Manifest File Not Found", manifestFileLocation); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - manifest.UninstallPlugin(dbContext, UninstallData, this.Status); + manifest.UninstallPlugin(database, UninstallData, this.Status); } string manifestUninstallFileLocation = Path.Combine(manifest.PluginLocation, "manifest.uninstall.json"); diff --git a/Disco.Services/Plugins/UpdatePluginTask.cs b/Disco.Services/Plugins/UpdatePluginTask.cs index d64a3e4a..1b2320d8 100644 --- a/Disco.Services/Plugins/UpdatePluginTask.cs +++ b/Disco.Services/Plugins/UpdatePluginTask.cs @@ -32,10 +32,10 @@ namespace Disco.Services.Plugins List> updatePlugins; - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - catalogue = Plugins.LoadCatalogue(dbContext); - pluginPackagesLocation = dbContext.DiscoConfiguration.PluginPackagesLocation; + catalogue = Plugins.LoadCatalogue(database); + pluginPackagesLocation = database.DiscoConfiguration.PluginPackagesLocation; } if (!string.IsNullOrEmpty(pluginId)) @@ -82,10 +82,10 @@ namespace Disco.Services.Plugins Plugins.RestartApp(1500); } - public static List OfflineInstalledPlugins(DiscoDataContext dbContext) + public static List OfflineInstalledPlugins(DiscoDataContext Database) { - string pluginsLocation = dbContext.DiscoConfiguration.PluginsLocation; - string pluginsStorageLocation = dbContext.DiscoConfiguration.PluginStorageLocation; + string pluginsLocation = Database.DiscoConfiguration.PluginsLocation; + string pluginsStorageLocation = Database.DiscoConfiguration.PluginStorageLocation; List installedPluginManifests = new List(); @@ -121,13 +121,13 @@ namespace Disco.Services.Plugins List> updatePlugins = new List>(); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { - pluginPackagesLocation = dbContext.DiscoConfiguration.PluginPackagesLocation; - installedPluginManifests = OfflineInstalledPlugins(dbContext); + pluginPackagesLocation = database.DiscoConfiguration.PluginPackagesLocation; + installedPluginManifests = OfflineInstalledPlugins(database); if (installedPluginManifests.Count > 0) - pluginCatalogue = Plugins.LoadCatalogue(dbContext); + pluginCatalogue = Plugins.LoadCatalogue(database); } if (pluginCatalogue != null && installedPluginManifests.Count > 0) @@ -231,15 +231,15 @@ namespace Disco.Services.Plugins Status.UpdateStatus(20, string.Format("{0} [{1} v{2}] by {3}", updateManifest.Name, updateManifest.Id, updateManifest.Version.ToString(4), updateManifest.Author), "Initializing Update Environment"); - using (DiscoDataContext dbContext = new DiscoDataContext()) + using (DiscoDataContext database = new DiscoDataContext()) { // Check for Compatibility - var compatibilityData = Plugins.LoadCompatibilityData(dbContext); + var compatibilityData = Plugins.LoadCompatibilityData(database); var pluginCompatibility = compatibilityData.Plugins.FirstOrDefault(i => i.Id.Equals(updateManifest.Id, StringComparison.InvariantCultureIgnoreCase) && updateManifest.Version == Version.Parse(i.Version)); if (pluginCompatibility != null && !pluginCompatibility.Compatible) throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", updateManifest.Id, updateManifest.VersionFormatted, pluginCompatibility.Reason)); - var updatePluginPath = Path.Combine(dbContext.DiscoConfiguration.PluginsLocation, string.Format("{0}.discoPlugin", updateManifest.Id)); + var updatePluginPath = Path.Combine(database.DiscoConfiguration.PluginsLocation, string.Format("{0}.discoPlugin", updateManifest.Id)); File.Move(packageTempFilePath, updatePluginPath); if (existingManifest != null) diff --git a/Disco.Services/Properties/AssemblyInfo.cs b/Disco.Services/Properties/AssemblyInfo.cs index 55da51f6..640e3cfa 100644 --- a/Disco.Services/Properties/AssemblyInfo.cs +++ b/Disco.Services/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2249")] -[assembly: AssemblyFileVersion("1.2.0725.2249")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1541")] +[assembly: AssemblyFileVersion("1.2.1001.1541")] \ No newline at end of file diff --git a/Disco.Services/Tasks/ScheduledTask.cs b/Disco.Services/Tasks/ScheduledTask.cs index dc4dc4e4..f5856a09 100644 --- a/Disco.Services/Tasks/ScheduledTask.cs +++ b/Disco.Services/Tasks/ScheduledTask.cs @@ -9,7 +9,7 @@ namespace Disco.Services.Tasks { public abstract class ScheduledTask : IJob { - public virtual void InitalizeScheduledTask(DiscoDataContext dbContext) { return; } + public virtual void InitalizeScheduledTask(DiscoDataContext Database) { return; } internal protected ScheduledTaskStatus Status { get; private set; } internal protected IJobExecutionContext ExecutionContext { get; private set; } diff --git a/Disco.Services/Tasks/ScheduledTasks.cs b/Disco.Services/Tasks/ScheduledTasks.cs index c654d4dd..293b2211 100644 --- a/Disco.Services/Tasks/ScheduledTasks.cs +++ b/Disco.Services/Tasks/ScheduledTasks.cs @@ -16,7 +16,7 @@ namespace Disco.Services.Tasks private static object _RunningTasksLock = new object(); private static List _RunningTasks = new List(); - public static void InitalizeScheduledTasks(DiscoDataContext dbContext, ISchedulerFactory SchedulerFactory, bool InitiallySchedule) + public static void InitalizeScheduledTasks(DiscoDataContext database, ISchedulerFactory SchedulerFactory, bool InitiallySchedule) { ScheduledTasksLog.LogInitializingScheduledTasks(); @@ -43,7 +43,7 @@ namespace Disco.Services.Tasks ScheduledTask instance = (ScheduledTask)Activator.CreateInstance(scheduledTaskType); try { - instance.InitalizeScheduledTask(dbContext); + instance.InitalizeScheduledTask(database); } catch (Exception ex) { diff --git a/Disco.Services/Users/Cache.cs b/Disco.Services/Users/Cache.cs new file mode 100644 index 00000000..7523b23f --- /dev/null +++ b/Disco.Services/Users/Cache.cs @@ -0,0 +1,176 @@ +using Disco.Data.Repository; +using Disco.Models.Repository; +using Disco.Services.Authorization; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Users +{ + internal static class Cache + { + private static ConcurrentDictionary> _Cache = new ConcurrentDictionary>(); + private const long CacheTimeoutTicks = 6000000000; // 10 Minutes + + internal static AuthorizationToken GetAuthorization(string UserId, DiscoDataContext Database, bool ForceRefresh) + { + Tuple record = Get(UserId, Database, ForceRefresh); + + if (record == null) + return null; + else + return record.Item2; + } + internal static AuthorizationToken GetAuthorization(string UserId, bool ForceRefresh) + { + Tuple record = Get(UserId, ForceRefresh); + + if (record == null) + return null; + else + return record.Item2; + } + internal static AuthorizationToken GetAuthorization(string UserId, DiscoDataContext Database) + { + return GetAuthorization(UserId, Database, false); + } + internal static AuthorizationToken GetAuthorization(string UserId) + { + return GetAuthorization(UserId, false); + } + + internal static User GetUser(string UserId, DiscoDataContext Database, bool ForceRefresh) + { + Tuple record = Get(UserId, Database, ForceRefresh); + + if (record == null) + return null; + else + return record.Item1; + } + internal static User GetUser(string UserId, bool ForceRefresh) + { + Tuple record = Get(UserId, ForceRefresh); + + if (record == null) + return null; + else + return record.Item1; + } + internal static User GetUser(string UserId, DiscoDataContext Database) + { + return GetUser(UserId, Database, false); + } + internal static User GetUser(string UserId) + { + return GetUser(UserId, false); + } + + internal static Tuple Get(string UserId, DiscoDataContext Database, bool ForceRefresh) + { + Tuple record = null; + + // Check Cache + if (!ForceRefresh) + record = TryUserCache(UserId); + + if (record == null) + { + var importedUser = UserService.ImportUser(Database, UserId); + record = SetValue(UserId, importedUser); + } + + return record; + } + internal static Tuple Get(string UserId, DiscoDataContext Database) + { + return Get(UserId, Database, false); + } + internal static Tuple Get(string UserId, bool ForceRefresh) + { + // Check Cache + Tuple record = null; + + if (!ForceRefresh) + record = TryUserCache(UserId); + + if (record == null) + { + // Load from Repository + using (DiscoDataContext database = new DiscoDataContext()) + { + record = Get(UserId, database, true); + } + } + return record; + } + internal static Tuple Get(string UserId) + { + return Get(UserId, false); + } + + internal static Tuple TryUserCache(string UserId) + { + var cache = _Cache; + + string userId = UserId.ToLower(); + Tuple record; + if (cache.TryGetValue(userId, out record)) + { + if (record.Item3 > DateTime.Now) + return record; + else + cache.TryRemove(userId, out record); + } + return null; + } + + internal static Tuple SetValue(string UserId, Tuple Record) + { + var cache = _Cache; + + string userId = UserId.ToLower(); + Tuple record = new Tuple(Record.Item1, Record.Item2, DateTime.Now.AddTicks(CacheTimeoutTicks)); + if (cache.ContainsKey(userId)) + { + Tuple oldRecord; + if (cache.TryGetValue(userId, out oldRecord)) + { + cache.TryUpdate(userId, record, oldRecord); + return record; + } + } + cache.TryAdd(userId, record); + return record; + } + + internal static bool InvalidateRecord(string UserId) + { + Tuple userRecord; + return _Cache.TryRemove(UserId, out userRecord); + } + + internal static void CleanStaleCache() + { + var cache = _Cache; + + var userIds = cache.Keys.ToArray(); + foreach (string userId in userIds) + { + Tuple record; + if (cache.TryGetValue(userId, out record)) + { + if (record.Item3 <= DateTime.Now) + cache.TryRemove(userId, out record); + } + } + } + internal static void FlushCache() + { + _Cache = new ConcurrentDictionary>(); + } + } +} diff --git a/Disco.BI/BI/UserBI/UserCachePruneTask.cs b/Disco.Services/Users/CacheCleanTask.cs similarity index 90% rename from Disco.BI/BI/UserBI/UserCachePruneTask.cs rename to Disco.Services/Users/CacheCleanTask.cs index a758d26a..6c7bfd08 100644 --- a/Disco.BI/BI/UserBI/UserCachePruneTask.cs +++ b/Disco.Services/Users/CacheCleanTask.cs @@ -7,9 +7,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Disco.BI.UserBI +namespace Disco.Services.Users { - public class UserCachePruneTask : ScheduledTask + public class CacheCleanTask : ScheduledTask { public override string TaskName { get { return "User Cache - Clean Stale Cache"; } } @@ -17,7 +17,7 @@ namespace Disco.BI.UserBI public override bool CancelInitiallySupported { get { return false; } } public override bool LogExceptionsOnly { get { return true; } } - public override void InitalizeScheduledTask(DiscoDataContext dbContext) + public override void InitalizeScheduledTask(DiscoDataContext Database) { // Run @ every 15mins @@ -36,7 +36,7 @@ namespace Disco.BI.UserBI protected override void ExecuteTask() { - UserCache.CleanStaleCache(); + Cache.CleanStaleCache(); } } } diff --git a/Disco.Services/Users/Searching.cs b/Disco.Services/Users/Searching.cs new file mode 100644 index 00000000..bef5adbd --- /dev/null +++ b/Disco.Services/Users/Searching.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Users +{ + public static class Searching + { + + } +} diff --git a/Disco.Services/Users/UserService.cs b/Disco.Services/Users/UserService.cs new file mode 100644 index 00000000..ae69628e --- /dev/null +++ b/Disco.Services/Users/UserService.cs @@ -0,0 +1,257 @@ +using Disco.Data.Repository; +using Disco.Models.Interop.ActiveDirectory; +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Authorization.Roles; +using Disco.Services.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Data.Entity.Infrastructure; +using System.DirectoryServices.ActiveDirectory; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Web; + +namespace Disco.Services.Users +{ + public static class UserService + { + private const string _cacheHttpRequestKey = "Disco_CurrentUserToken"; + private static Func _GetActiveDirectoryUserAccount; + private static Func _GetActiveDirectoryMachineAccount; + + public static void Initialize(DiscoDataContext Database, + Func GetActiveDirectoryUserAccount, + Func GetActiveDirectoryMachineAccount) + { + _GetActiveDirectoryUserAccount = GetActiveDirectoryUserAccount; + _GetActiveDirectoryMachineAccount = GetActiveDirectoryMachineAccount; + + Authorization.Roles.RoleCache.Initialize(Database); + } + + public static string CurrentUserId + { + get + { + // Check for ASP.NET + if (HttpContext.Current != null) + { + if (HttpContext.Current.Request.IsAuthenticated) + return HttpContext.Current.User.Identity.Name; + else + return null; + } + + // User default User + return System.Security.Principal.WindowsIdentity.GetCurrent().Name; + } + } + + private static Tuple CurrentUserToken + { + get + { + Tuple token = null; + + if (HttpContext.Current != null) + { + if (HttpContext.Current.Request.IsAuthenticated) + token = (Tuple)HttpContext.Current.Items[_cacheHttpRequestKey]; + else + return null; // Not Authenticated + } + + if (token == null) + { + var userId = CurrentUserId; + + if (userId != null) + { + token = Cache.Get(userId); + + if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) + HttpContext.Current.Items[_cacheHttpRequestKey] = token; + } + } + + return token; + } + } + public static User CurrentUser + { + get + { + var token = CurrentUserToken; + + if (token == null) + return null; + else + return token.Item1; + } + } + public static AuthorizationToken CurrentAuthorization + { + get + { + var token = CurrentUserToken; + + if (token == null) + return null; + else + return token.Item2; + } + } + + public static User GetUser(string UserId) + { + return Cache.GetUser(UserId); + } + public static User GetUser(string UserId, DiscoDataContext Database) + { + return Cache.GetUser(UserId, Database); + } + public static User GetUser(string UserId, DiscoDataContext Database, bool ForceRefresh) + { + return Cache.GetUser(UserId, Database, ForceRefresh); + } + + public static AuthorizationToken GetAuthorization(string UserId) + { + return Cache.GetAuthorization(UserId); + } + public static AuthorizationToken GetAuthorization(string UserId, DiscoDataContext Database) + { + return Cache.GetAuthorization(UserId, Database); + } + public static AuthorizationToken GetAuthorization(string UserId, DiscoDataContext Database, bool ForceRefresh) + { + return Cache.GetAuthorization(UserId, Database, ForceRefresh); + } + + public static bool InvalidateCachedUser(string UserId) + { + return Cache.InvalidateRecord(UserId); + } + + + + public static int CreateAuthorizationRole(DiscoDataContext Database, AuthorizationRole Role) + { + if (Role == null) + throw new ArgumentNullException("Role"); + + if (string.IsNullOrWhiteSpace(Role.ClaimsJson)) + Role.ClaimsJson = JsonConvert.SerializeObject(new RoleClaims()); + + Database.AuthorizationRoles.Add(Role); + Database.SaveChanges(); + + // Add to Cache + RoleCache.AddRole(Role); + + // Flush User Cache + Cache.FlushCache(); + + return Role.Id; + } + public static void DeleteAuthorizationRole(DiscoDataContext Database, AuthorizationRole Role) + { + if (Role == null) + throw new ArgumentNullException("Role"); + + Database.AuthorizationRoles.Remove(Role); + Database.SaveChanges(); + + // Remove from Role Cache + RoleCache.RemoveRole(Role); + + // Flush User Cache + Cache.FlushCache(); + } + public static void UpdateAuthorizationRole(DiscoDataContext Database, AuthorizationRole Role) + { + if (Role == null) + throw new ArgumentNullException("Role"); + if (Database == null) + throw new ArgumentNullException("Database"); + + Database.SaveChanges(); + + // Update Role Cache + RoleCache.UpdateRole(Role); + + // Flush User Cache + Cache.FlushCache(); + } + + internal static Tuple ImportUser(DiscoDataContext Database, string UserId) + { + if (_GetActiveDirectoryUserAccount == null) + throw new InvalidOperationException("UserServer has not been Initialized"); + if (string.IsNullOrEmpty(UserId)) + throw new ArgumentNullException("UserId is required", "UserId"); + + if (UserId.EndsWith("$")) + { + // Machine Account + var adAccount = _GetActiveDirectoryMachineAccount(UserId, null); + + if (adAccount == null) + return null; + + var user = adAccount.ToRepositoryUser(); + var token = AuthorizationToken.BuildComputerAccountToken(user); + + return new Tuple(user, token); + } + else + { + // User Account + + ActiveDirectoryUserAccount adAccount; + try + { + adAccount = _GetActiveDirectoryUserAccount(UserId, null); + + if (adAccount == null) + throw new ArgumentException(string.Format("Invalid Username: '{0}'; User doesn't in AD", UserId), "Username"); + } + catch (COMException ex) + { + // If "Server is not operational" then Try Cache + if (ex.ErrorCode == -2147016646) + SystemLog.LogException("Server is not operational; Primary Domain Controller Down?", ex); + + throw ex; + } + catch (ActiveDirectoryOperationException ex) + { + // Try From Cache... + SystemLog.LogException("Primary Domain Controller Down?", ex); + throw ex; + } + + var user = adAccount.ToRepositoryUser(); + + // Update Repository + User existingUser = Database.Users.Find(user.Id); + if (existingUser == null) + Database.Users.Add(user); + else + { + existingUser.UpdateSelf(user); + user = existingUser; + } + Database.SaveChanges(); + + var token = AuthorizationToken.BuildToken(user, adAccount.Groups); + + return new Tuple(user, token); + } + } + } +} diff --git a/Disco.Services/Web/AuthorizedController.cs b/Disco.Services/Web/AuthorizedController.cs new file mode 100644 index 00000000..a04b83f2 --- /dev/null +++ b/Disco.Services/Web/AuthorizedController.cs @@ -0,0 +1,32 @@ +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web.Mvc; + +namespace Disco.Services.Web +{ + [DiscoAuthorize] + public abstract class AuthorizedController : Controller + { + public AuthorizationToken Authorization + { + get + { + return UserService.CurrentAuthorization; + } + } + + public User CurrentUser + { + get + { + return UserService.CurrentUser; + } + } + } +} diff --git a/Disco.Services/Web/AuthorizedDatabaseController.cs b/Disco.Services/Web/AuthorizedDatabaseController.cs new file mode 100644 index 00000000..3133912c --- /dev/null +++ b/Disco.Services/Web/AuthorizedDatabaseController.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Disco.Services.Authorization; +using Disco.Models.Repository; +using Disco.Services.Users; + +namespace Disco.Services.Web +{ + [DiscoAuthorize] + public abstract class AuthorizedDatabaseController : DatabaseController + { + public AuthorizationToken Authorization + { + get + { + return UserService.CurrentAuthorization; + } + } + + public User CurrentUser + { + get + { + return UserService.CurrentUser; + } + } + } +} diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/Bundle.cs b/Disco.Services/Web/Bundles/Bundle.cs similarity index 98% rename from Disco.Web.Extensions/MvcExtensions/Bundles/Bundle.cs rename to Disco.Services/Web/Bundles/Bundle.cs index 2f206b55..f9f1738a 100644 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/Bundle.cs +++ b/Disco.Services/Web/Bundles/Bundle.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading.Tasks; using System.Web; -namespace Disco.Web.Extensions.MvcExtensions.Bundles +namespace Disco.Services.Web.Bundles { public class Bundle { diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleExtensions.cs b/Disco.Services/Web/Bundles/BundleExtensions.cs similarity index 96% rename from Disco.Web.Extensions/MvcExtensions/Bundles/BundleExtensions.cs rename to Disco.Services/Web/Bundles/BundleExtensions.cs index 14a1aa61..8f16d940 100644 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleExtensions.cs +++ b/Disco.Services/Web/Bundles/BundleExtensions.cs @@ -1,12 +1,13 @@ -using System; +using Disco.Services.Web.Bundles; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Threading.Tasks; using System.Web; using System.Web.Mvc; -using Disco.Web.Extensions.MvcExtensions.Bundles; -namespace Disco.Web.Extensions +namespace Disco.Services.Web { public static class BundleExtensions { diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleHandler.cs b/Disco.Services/Web/Bundles/BundleHandler.cs similarity index 95% rename from Disco.Web.Extensions/MvcExtensions/Bundles/BundleHandler.cs rename to Disco.Services/Web/Bundles/BundleHandler.cs index 7b30da64..f4b6af82 100644 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleHandler.cs +++ b/Disco.Services/Web/Bundles/BundleHandler.cs @@ -5,13 +5,13 @@ using System.Text; using System.Threading.Tasks; using System.Web; -namespace Disco.Web.Extensions.MvcExtensions.Bundles +namespace Disco.Services.Web.Bundles { internal sealed class BundleHandler : IHttpHandler { public Bundle RequestBundle { get; private set; } public string BundleVirtualPath { get; private set; } - + public BundleHandler(Bundle requestBundle, string bundleVirtualPath) { this.RequestBundle = requestBundle; diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleModule.cs b/Disco.Services/Web/Bundles/BundleModule.cs similarity index 81% rename from Disco.Web.Extensions/MvcExtensions/Bundles/BundleModule.cs rename to Disco.Services/Web/Bundles/BundleModule.cs index 5707c09d..0bfcf4be 100644 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleModule.cs +++ b/Disco.Services/Web/Bundles/BundleModule.cs @@ -1,16 +1,16 @@ -using System; +using Microsoft.Web.Infrastructure.DynamicModuleHelper; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; -using Microsoft.Web.Infrastructure.DynamicModuleHelper; -[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Disco.Web.Extensions.MvcExtensions.Bundles.BundleModule), "PreApplicationStart")] +[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Disco.Services.Web.Bundles.BundleModule), "PreApplicationStart")] -namespace Disco.Web.Extensions.MvcExtensions.Bundles +namespace Disco.Services.Web.Bundles { - public class BundleModule :IHttpModule + public class BundleModule : IHttpModule { public void Init(HttpApplication context) { diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleTable.cs b/Disco.Services/Web/Bundles/BundleTable.cs similarity index 96% rename from Disco.Web.Extensions/MvcExtensions/Bundles/BundleTable.cs rename to Disco.Services/Web/Bundles/BundleTable.cs index b6cc9e58..bee13e15 100644 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleTable.cs +++ b/Disco.Services/Web/Bundles/BundleTable.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading.Tasks; using System.Web; -namespace Disco.Web.Extensions.MvcExtensions.Bundles +namespace Disco.Services.Web.Bundles { public static class BundleTable { @@ -41,7 +41,7 @@ namespace Disco.Web.Extensions.MvcExtensions.Bundles public static string ResolveBundleUrl(string BundleUrl) { var bundle = GetBundleFor(BundleUrl); - + if (bundle == null) throw new ArgumentException(string.Format("Unknown Bundle Url: {0}", BundleUrl), "BundleUrl"); diff --git a/Disco.Web.Extensions/MvcExtensions/dbController.cs b/Disco.Services/Web/DatabaseController.cs similarity index 50% rename from Disco.Web.Extensions/MvcExtensions/dbController.cs rename to Disco.Services/Web/DatabaseController.cs index 33481613..9380034d 100644 --- a/Disco.Web.Extensions/MvcExtensions/dbController.cs +++ b/Disco.Services/Web/DatabaseController.cs @@ -1,34 +1,35 @@ -using System; +using Disco.Data.Repository; +using System; using System.Collections.Generic; using System.Linq; -using System.Web; +using System.Text; +using System.Threading.Tasks; using System.Web.Mvc; -using Disco.Data.Repository; -namespace Disco.Web +namespace Disco.Services.Web { [OutputCache(Duration = 0, Location = System.Web.UI.OutputCacheLocation.None)] - public class dbController : Controller + public abstract class DatabaseController : Controller { - protected DiscoDataContext dbContext; + protected DiscoDataContext Database; protected override void OnActionExecuting(ActionExecutingContext filterContext) { - this.dbContext = new DiscoDataContext(); - this.dbContext.Configuration.LazyLoadingEnabled = false; + this.Database = new DiscoDataContext(); + this.Database.Configuration.LazyLoadingEnabled = false; base.OnActionExecuting(filterContext); } protected override void Dispose(bool disposing) { - if (this.dbContext != null) + if (this.Database != null) { - this.dbContext.Dispose(); - this.dbContext = null; + this.Database.Dispose(); + this.Database = null; } base.Dispose(disposing); } } -} \ No newline at end of file +} diff --git a/Disco.Services/Web/WebViewPage.cs b/Disco.Services/Web/WebViewPage.cs new file mode 100644 index 00000000..2fbada25 --- /dev/null +++ b/Disco.Services/Web/WebViewPage.cs @@ -0,0 +1,32 @@ +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Users; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Disco.Services.Web +{ + public abstract class WebViewPage : System.Web.Mvc.WebViewPage + { + + public AuthorizationToken Authorization + { + get + { + return UserService.CurrentAuthorization; + } + } + + public User CurrentUser + { + get + { + return UserService.CurrentUser; + } + } + + } +} diff --git a/Disco.Web.Extensions/DataModelExtension/DeviceModelExtensions.cs b/Disco.Web.Extensions/DataModelExtension/DeviceModelExtensions.cs index ff4c1259..ea38546c 100644 --- a/Disco.Web.Extensions/DataModelExtension/DeviceModelExtensions.cs +++ b/Disco.Web.Extensions/DataModelExtension/DeviceModelExtensions.cs @@ -23,7 +23,7 @@ namespace Disco.Web.Extensions } if (IncludeNoModelItem) - items.Insert(0, new SelectListItem() { Value = string.Empty, Text = "Unknown", Selected = !SelectedId.HasValue }); + items.Insert(0, new SelectListItem() { Value = string.Empty, Text = "", Selected = !SelectedId.HasValue }); return items; } diff --git a/Disco.Web.Extensions/Disco.Web.Extensions.csproj b/Disco.Web.Extensions/Disco.Web.Extensions.csproj index 98714a3c..df36a390 100644 --- a/Disco.Web.Extensions/Disco.Web.Extensions.csproj +++ b/Disco.Web.Extensions/Disco.Web.Extensions.csproj @@ -95,14 +95,6 @@ - - - - - - - - @@ -134,7 +126,7 @@ - + diff --git a/Disco.Web.Extensions/MvcExtensions/AuthorizeDiscoUsersAttribute.cs b/Disco.Web.Extensions/MvcExtensions/AuthorizeDiscoUsersAttribute.cs deleted file mode 100644 index eab47f3b..00000000 --- a/Disco.Web.Extensions/MvcExtensions/AuthorizeDiscoUsersAttribute.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Disco.BI.UserBI; -using Disco.Models.Repository; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Mvc; - -namespace Disco.Web -{ - public class AuthorizeDiscoUsersAttribute : AuthorizeAttribute - { - string[] authorizedTypes; - - public AuthorizeDiscoUsersAttribute(params string[] AuthorizedUserTypes) - { - if (AuthorizedUserTypes == null) - throw new ArgumentNullException("AuthorizedUserTypes"); - if (AuthorizedUserTypes.Length == 0) - throw new ArgumentOutOfRangeException("AuthorizedUserTypes", "At least one Authorized User Type must be specified"); - - authorizedTypes = AuthorizedUserTypes; - } - - protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) - { - if (httpContext == null) - { - throw new ArgumentNullException("httpContext"); - } - - var DiscoUser = UserCache.CurrentUser; - - if (DiscoUser != null && authorizedTypes.Contains(DiscoUser.Type)) - return true; - - return false; - } - } -} diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleUnordered.cs b/Disco.Web.Extensions/MvcExtensions/Bundles/BundleUnordered.cs deleted file mode 100644 index ddd34314..00000000 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/BundleUnordered.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Optimization; - -namespace Disco.Web.Extensions.MvcExtensions.Bundles -{ - public class BundleUnordered : IBundleOrderer - { - public IEnumerable OrderFiles(BundleContext context, IEnumerable files) - { - return files; - } - } -} diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/JsJoin.cs b/Disco.Web.Extensions/MvcExtensions/Bundles/JsJoin.cs deleted file mode 100644 index 1676752f..00000000 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/JsJoin.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web.Optimization; -using System.IO; - -namespace Disco.Web.Extensions.MvcExtensions.Bundles -{ - public class JsJoin : IBundleTransform - { - internal static string JsContentType; - static JsJoin() - { - JsContentType = "text/javascript"; - } - - public void Process(BundleContext context, BundleResponse response) - { - if (context == null) - throw new ArgumentNullException("context"); - if (response == null) - throw new ArgumentNullException("response"); - - // Not Needed - the new Transforms pipeline has already loaded the content - //if (!context.EnableInstrumentation && string.IsNullOrEmpty(response.Content)) - //{ - // try - // { - // StringBuilder bundleContent = new StringBuilder(); - // foreach (FileInfo file in response.Files) - // { - // string fileContent = File.ReadAllText(file.FullName); - - // bundleContent.AppendLine(fileContent); - // } - - // response.Content = bundleContent.ToString(); - // } - // catch (Exception ex) - // { - // GenerateErrorResponse(response, new string[] { ex.GetType().Name, ex.Message, ex.StackTrace }); - // } - //} - - response.ContentType = JsContentType; - } - - internal static void GenerateErrorResponse(BundleResponse bundle, ICollection errors) - { - StringBuilder builder = new StringBuilder(); - builder.Append("/* "); - builder.Append("Bundle creation failed [JsJoin].").Append("\r\n"); - foreach (string str in errors) - { - builder.Append(str).Append("\r\n"); - } - builder.Append(" */\r\n"); - bundle.Content = builder.ToString(); - } - - } -} diff --git a/Disco.Web.Extensions/MvcExtensions/Bundles/LessCompile.cs b/Disco.Web.Extensions/MvcExtensions/Bundles/LessCompile.cs deleted file mode 100644 index 19c9778d..00000000 --- a/Disco.Web.Extensions/MvcExtensions/Bundles/LessCompile.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.IO; -using System.Web; -using dotless.Core; -using dotless.Core.configuration; -using System.Web.Optimization; - -namespace Disco.Web.Extensions.MvcExtensions.Bundles -{ - public class LessCompile : IBundleTransform - { - internal static string CssContentType; - internal static readonly ILessEngine Instance; - - static LessCompile() - { - CssContentType = "text/css"; - Instance = new EngineFactory(new DotlessConfiguration() - { - CacheEnabled = false, - MinifyOutput = true - }).GetEngine(); - } - - public void Process(BundleContext context, BundleResponse response) - { - if (context == null) - throw new ArgumentNullException("context"); - if (response == null) - throw new ArgumentNullException("response"); - - if (!context.EnableInstrumentation) - { - - try - { - StringBuilder bundleContent = new StringBuilder(); - Uri appRootPath = new Uri(HttpContext.Current.Request.PhysicalApplicationPath); - - var restoreEnvironmentCurrentDirectory = Environment.CurrentDirectory; - - foreach (FileInfo file in response.Files) - { - string fileContent = File.ReadAllText(file.FullName); - Uri fileRootPath = new Uri(file.DirectoryName + "/"); - - // Less Compile - - Environment.CurrentDirectory = file.DirectoryName; - fileContent = Instance.TransformToCss(fileContent, file.FullName); - - // Embed Images - fileContent = EmbedCssImages(fileContent, fileRootPath, appRootPath); - bundleContent.Append(fileContent); - } - - if (!Environment.CurrentDirectory.Equals(restoreEnvironmentCurrentDirectory)) - Environment.CurrentDirectory = restoreEnvironmentCurrentDirectory; - - response.Content = bundleContent.ToString(); - } - catch (Exception ex) - { - GenerateErrorResponse(response, new string[] { ex.GetType().Name, ex.Message, ex.StackTrace }); - } - } - response.ContentType = CssContentType; - } - - private static string EmbedCssImages(string cssContent, Uri fileRootPath, Uri appRootPath) - { - return Regex.Replace(cssContent, "url\\((.*?)\\)", m => - { - var cssFilename = m.Groups[1].Value.Trim(new char[] { '\'', '"' }); - Uri fileUri; - if (cssFilename.StartsWith("/")) - fileUri = new Uri(appRootPath, cssFilename); - else - fileUri = new Uri(fileRootPath, cssFilename); - if (File.Exists(fileUri.LocalPath)) - { - var fileInfo = new FileInfo(fileUri.LocalPath); - // Ensure File is < 250kb - if (fileInfo.Length < 256000) - { - string contentType = null; - switch (fileInfo.Extension) - { - case ".png": - contentType = "image/png"; - break; - case ".gif": - contentType = "image/gif"; - break; - case ".jpg": - case ".jpeg": - contentType = "image/jpeg"; - break; - default: - return m.Value; - } - StringBuilder sb = new StringBuilder(); - sb.Append("url(data:"); - sb.Append(contentType); - sb.Append(";base64,"); - sb.Append(Convert.ToBase64String(File.ReadAllBytes(fileInfo.FullName))); - sb.Append(")"); - return sb.ToString(); - } - else - { - return string.Format("url(/{0})", appRootPath.MakeRelativeUri(fileUri).ToString()); - } - } - else - { - throw new FileNotFoundException(string.Format("Unable to embed css image, file not found: '{0}' at '{1}'", cssFilename, fileUri.AbsolutePath), cssFilename); - } - }); - } - - internal static void GenerateErrorResponse(BundleResponse bundle, ICollection errors) - { - StringBuilder builder = new StringBuilder(); - builder.Append("/* "); - builder.Append("Bundle creation failed [LessCompile].").Append("\r\n"); - foreach (string str in errors) - { - builder.Append(str).Append("\r\n"); - } - builder.Append(" */\r\n"); - bundle.Content = builder.ToString(); - } - - } -} diff --git a/Disco.Web.Extensions/MvcExtensions/dbAdminController.cs b/Disco.Web.Extensions/MvcExtensions/dbAdminController.cs deleted file mode 100644 index 3cd49070..00000000 --- a/Disco.Web.Extensions/MvcExtensions/dbAdminController.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; - -namespace Disco.Web -{ - [AuthorizeDiscoUsersAttribute(Disco.Models.Repository.User.Types.Admin)] - public class dbAdminController : dbController - { - } -} \ No newline at end of file diff --git a/Disco.Web.Extensions/Properties/AssemblyInfo.cs b/Disco.Web.Extensions/Properties/AssemblyInfo.cs index 540c11f4..c4dc0895 100644 --- a/Disco.Web.Extensions/Properties/AssemblyInfo.cs +++ b/Disco.Web.Extensions/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0725.2249")] -[assembly: AssemblyFileVersion("1.2.0725.2249")] \ No newline at end of file +[assembly: AssemblyVersion("1.2.1001.1541")] +[assembly: AssemblyFileVersion("1.2.1001.1541")] \ No newline at end of file diff --git a/Disco.Web/App_Code/AjaxHelpers.cshtml b/Disco.Web/App_Code/AjaxHelpers.cshtml index d14f1fc1..2f49ec43 100644 --- a/Disco.Web/App_Code/AjaxHelpers.cshtml +++ b/Disco.Web/App_Code/AjaxHelpers.cshtml @@ -1,7 +1,7 @@ @* Generator: WebPagesHelper *@ @using Disco.BI.Extensions; @using Disco.Web; -@using Disco.Web.Extensions; +@using Disco.Services.Web; @helper AjaxLoader(string id = null) { Html.GetPageHelper().BundleDeferred("~/ClientScripts/Modules/Disco-AjaxHelperIcons"); diff --git a/Disco.Web/App_Code/AjaxHelpers.generated.cs b/Disco.Web/App_Code/AjaxHelpers.generated.cs index b08b4731..280d7a4b 100644 --- a/Disco.Web/App_Code/AjaxHelpers.generated.cs +++ b/Disco.Web/App_Code/AjaxHelpers.generated.cs @@ -2,7 +2,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18033 +// Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -30,14 +30,14 @@ namespace Disco.Web #line default #line hidden - #line 3 "..\..\App_Code\AjaxHelpers.cshtml" - using Disco.Web; + #line 4 "..\..\App_Code\AjaxHelpers.cshtml" + using Disco.Services.Web; #line default #line hidden - #line 4 "..\..\App_Code\AjaxHelpers.cshtml" - using Disco.Web.Extensions; + #line 3 "..\..\App_Code\AjaxHelpers.cshtml" + using Disco.Web; #line default #line hidden diff --git a/Disco.Web/App_Code/CommonHelpers.cshtml b/Disco.Web/App_Code/CommonHelpers.cshtml index 1e0e196a..8ecdcf5b 100644 --- a/Disco.Web/App_Code/CommonHelpers.cshtml +++ b/Disco.Web/App_Code/CommonHelpers.cshtml @@ -4,7 +4,7 @@ @using Disco.Web; @using System.Web.Mvc @using System.Web.Mvc.Html; -@using Disco.Web.Extensions; +@using Disco.Services.Web; @helper FriendlyDate(DateTime d, string ElementId = null) { @d.ToFuzzy() diff --git a/Disco.Web/App_Code/CommonHelpers.generated.cs b/Disco.Web/App_Code/CommonHelpers.generated.cs index e480b8a2..d52f57ee 100644 --- a/Disco.Web/App_Code/CommonHelpers.generated.cs +++ b/Disco.Web/App_Code/CommonHelpers.generated.cs @@ -2,7 +2,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18033 +// Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -48,14 +48,14 @@ namespace Disco.Web #line default #line hidden - #line 4 "..\..\App_Code\CommonHelpers.cshtml" - using Disco.Web; + #line 7 "..\..\App_Code\CommonHelpers.cshtml" + using Disco.Services.Web; #line default #line hidden - #line 7 "..\..\App_Code\CommonHelpers.cshtml" - using Disco.Web.Extensions; + #line 4 "..\..\App_Code\CommonHelpers.cshtml" + using Disco.Web; #line default #line hidden diff --git a/Disco.Web/App_Start/AppConfig.cs b/Disco.Web/App_Start/AppConfig.cs index 87c6d4c8..3b6a6620 100644 --- a/Disco.Web/App_Start/AppConfig.cs +++ b/Disco.Web/App_Start/AppConfig.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Web; using Disco.Data.Repository; +using System.Threading; +using System.Reflection; namespace Disco.Web { @@ -25,39 +27,50 @@ namespace Disco.Web return true; } - public static void InitalizeEnvironment(DiscoDataContext dbContext) + private static void InitalizeEnvironment(DiscoDataContext Database) { // Initialize Logging - Disco.Services.Logging.LogContext.Initalize(dbContext, DiscoApplication.SchedulerFactory); + Disco.Services.Logging.LogContext.Initalize(Database, DiscoApplication.SchedulerFactory); // Load Organisation Name - DiscoApplication.OrganisationName = dbContext.DiscoConfiguration.OrganisationName; - DiscoApplication.MultiSiteMode = dbContext.DiscoConfiguration.MultiSiteMode; + DiscoApplication.OrganisationName = Database.DiscoConfiguration.OrganisationName; + DiscoApplication.MultiSiteMode = Database.DiscoConfiguration.MultiSiteMode; // Setup Global Proxy - DiscoApplication.SetGlobalProxy(dbContext.DiscoConfiguration.ProxyAddress, - dbContext.DiscoConfiguration.ProxyPort, - dbContext.DiscoConfiguration.ProxyUsername, - dbContext.DiscoConfiguration.ProxyPassword); + DiscoApplication.SetGlobalProxy(Database.DiscoConfiguration.ProxyAddress, + Database.DiscoConfiguration.ProxyPort, + Database.DiscoConfiguration.ProxyUsername, + Database.DiscoConfiguration.ProxyPassword); + + // Initialize User Service Interop + Disco.Services.Users.UserService.Initialize(Database, + (UserId, AdditionalProperties) => Disco.BI.Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(UserId, AdditionalProperties), + (UserId, AdditionalProperties) => Disco.BI.Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(UserId, null, null, AdditionalProperties)); + + } + + public static void InitalizeNormalEnvironment(DiscoDataContext Database) + { + InitalizeEnvironment(Database); // Initialize Expressions BI.Expressions.Expression.InitializeExpressions(); // Initialize Warranty Providers Plugins - Disco.Services.Plugins.Plugins.InitalizePlugins(dbContext); + Disco.Services.Plugins.Plugins.InitalizePlugins(Database); // Initialize Scheduled Tasks - Disco.Services.Tasks.ScheduledTasks.InitalizeScheduledTasks(dbContext, DiscoApplication.SchedulerFactory, true); + Disco.Services.Tasks.ScheduledTasks.InitalizeScheduledTasks(Database, DiscoApplication.SchedulerFactory, true); // Schedule Immediate Check for Update (if never updated, or last updated over 2 days ago) - if (dbContext.DiscoConfiguration.UpdateLastCheck == null || - dbContext.DiscoConfiguration.UpdateLastCheck.ResponseTimestamp < DateTime.Now.AddDays(-2)) + if (Database.DiscoConfiguration.UpdateLastCheck == null || + Database.DiscoConfiguration.UpdateLastCheck.ResponseTimestamp < DateTime.Now.AddDays(-2)) { Disco.BI.Interop.Community.UpdateCheckTask.ScheduleNow(); } // Setup Attachment Monitor - DiscoApplication.DocumentDropBoxMonitor = new BI.DocumentTemplateBI.Importer.DocumentDropBoxMonitor(dbContext, DiscoApplication.SchedulerFactory, HttpContext.Current.Cache); + DiscoApplication.DocumentDropBoxMonitor = new BI.DocumentTemplateBI.Importer.DocumentDropBoxMonitor(Database, DiscoApplication.SchedulerFactory, HttpContext.Current.Cache); DiscoApplication.DocumentDropBoxMonitor.StartWatching(); DiscoApplication.DocumentDropBoxMonitor.ScheduleCurrentFiles(10); @@ -66,27 +79,16 @@ namespace Disco.Web Disco.BI.Interop.SignalRHandlers.RepositoryMonitorNotifications.Initialize(); } - public static void InitializeUpdateEnvironment(DiscoDataContext dbContext, Version PreviousVersion) + public static void InitializeUpdateEnvironment(DiscoDataContext Database, Version PreviousVersion) { - // Initialize Logging - Disco.Services.Logging.LogContext.Initalize(dbContext, DiscoApplication.SchedulerFactory); - - // Load Organisation Name - DiscoApplication.OrganisationName = dbContext.DiscoConfiguration.OrganisationName; - DiscoApplication.MultiSiteMode = dbContext.DiscoConfiguration.MultiSiteMode; - - // Setup Global Proxy - DiscoApplication.SetGlobalProxy(dbContext.DiscoConfiguration.ProxyAddress, - dbContext.DiscoConfiguration.ProxyPort, - dbContext.DiscoConfiguration.ProxyUsername, - dbContext.DiscoConfiguration.ProxyPassword); + InitalizeEnvironment(Database); // Initialize Scheduled Tasks - Disco.Services.Tasks.ScheduledTasks.InitalizeScheduledTasks(dbContext, DiscoApplication.SchedulerFactory, true); + Disco.Services.Tasks.ScheduledTasks.InitalizeScheduledTasks(Database, DiscoApplication.SchedulerFactory, true); // Import MAC Address Migration if (PreviousVersion != null && PreviousVersion < new Version(1, 2, 910, 0)) - Disco.BI.DeviceBI.Migration.LogMacAddressImporting.SetRequired(dbContext); + Disco.BI.DeviceBI.Migration.LogMacAddressImporting.SetRequired(Database); } public static void DisposeEnvironment() diff --git a/Disco.Web/App_Start/BundleConfig.cs b/Disco.Web/App_Start/BundleConfig.cs index 3ac682ea..c742dcf3 100644 --- a/Disco.Web/App_Start/BundleConfig.cs +++ b/Disco.Web/App_Start/BundleConfig.cs @@ -1,9 +1,6 @@ -using System.IO; +using Disco.Services.Web.Bundles; +using System.IO; using System.Web; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Disco.Web.Extensions.MvcExtensions.Bundles; namespace Disco.Web { @@ -23,6 +20,7 @@ namespace Disco.Web BundleTable.Add(new Bundle("~/Style/Credits", Links.ClientSource.Style.Credits_min_css)); BundleTable.Add(new Bundle("~/Style/InitialConfig", Links.ClientSource.Style.InitialConfig_min_css)); BundleTable.Add(new Bundle("~/Style/jQueryUI/dynatree", Links.ClientSource.Style.jQueryUI.dynatree.ui_dynatree_min_css)); + BundleTable.Add(new Bundle("~/Style/Fancytree", Links.ClientSource.Style.Fancytree.ui_fancytree_min_css)); BundleTable.Add(new Bundle("~/Style/Shadowbox", Links.ClientSource.Style.Shadowbox_min_css)); BundleTable.Add(new Bundle("~/Style/Timeline", Links.ClientSource.Style.Timeline_min_css)); diff --git a/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs b/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs new file mode 100644 index 00000000..d7079acd --- /dev/null +++ b/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs @@ -0,0 +1,233 @@ +using Disco.BI.Extensions; +using Disco.BI.Interop.ActiveDirectory; +using Disco.Models.Interop.ActiveDirectory; +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Users; +using Disco.Services.Web; +using System; +using System.Linq; +using System.Web.Mvc; + +namespace Disco.Web.Areas.API.Controllers +{ + [DiscoAuthorize(Claims.DiscoAdminAccount)] + public partial class AuthorizationRoleController : AuthorizedDatabaseController + { + + #region Properties + + const string pName = "name"; + + public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false) + { + try + { + if (id < 0) + throw new ArgumentOutOfRangeException("id"); + if (string.IsNullOrEmpty(key)) + throw new ArgumentNullException("key"); + var authorizationRole = Database.AuthorizationRoles.Find(id); + if (authorizationRole != null) + { + switch (key.ToLower()) + { + case pName: + UpdateName(authorizationRole, value); + break; + default: + throw new Exception("Invalid Update Key"); + } + } + else + { + return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet); + } + if (redirect) + return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id)); + else + return Json("OK", JsonRequestBehavior.AllowGet); + } + catch (Exception ex) + { + if (redirect) + throw; + else + return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + } + } + + private void UpdateName(AuthorizationRole AuthorizationRole, string Name) + { + if (string.IsNullOrWhiteSpace(Name)) + throw new ArgumentNullException("Name", "Authorization Role Name is required"); + else + { + if (AuthorizationRole.Name != Name) + { + // Check for Duplicates + var d = Database.AuthorizationRoles.Where(db => db.Id != AuthorizationRole.Id && db.Name == Name).Count(); + if (d > 0) + { + throw new Exception("An Authorization Role with that name already exists"); + } + + AuthorizationRole.Name = Name; + UserService.UpdateAuthorizationRole(Database, AuthorizationRole); + } + } + } + + private void UpdateClaims(AuthorizationRole AuthorizationRole, string[] ClaimKeys) + { + var claims = Claims.BuildClaims(ClaimKeys); + AuthorizationRole.SetClaims(claims); + + UserService.UpdateAuthorizationRole(Database, AuthorizationRole); + } + + private void UpdateSubjects(AuthorizationRole AuthorizationRole, string[] Subjects) + { + string subjectIds = null; + + // Validate Subjects + if (Subjects != null && Subjects.Length > 0) + { + var subjects = Subjects.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).Select(s => new Tuple(s, ActiveDirectory.GetObject(s))).ToList(); + var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); + + if (invalidSubjects.Count > 0) + throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects"); + + subjectIds = string.Join(",", subjects.Select(s => s.Item2.SamAccountName).OrderBy(s => s)); + + if (string.IsNullOrEmpty(subjectIds)) + subjectIds = null; + } + + if (AuthorizationRole.SubjectIds != subjectIds) + { + AuthorizationRole.SubjectIds = subjectIds; + UserService.UpdateAuthorizationRole(Database, AuthorizationRole); + } + } + + public virtual ActionResult UpdateName(int id, string RoleName = null, bool redirect = false) + { + return Update(id, pName, RoleName, redirect); + } + + public virtual ActionResult UpdateClaims(int id, string[] ClaimKeys = null, bool redirect = false) + { + try + { + if (id < 0) + throw new ArgumentOutOfRangeException("id"); + + var authorizationRole = Database.AuthorizationRoles.Find(id); + if (authorizationRole != null) + { + UpdateClaims(authorizationRole, ClaimKeys); + } + else + { + return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet); + } + if (redirect) + return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id)); + else + return Json("OK", JsonRequestBehavior.AllowGet); + } + catch (Exception ex) + { + if (redirect) + throw; + else + return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + } + } + + public virtual ActionResult UpdateSubjects(int id, string[] Subjects = null, bool redirect = false) + { + try + { + if (id < 0) + throw new ArgumentOutOfRangeException("id"); + + var authorizationRole = Database.AuthorizationRoles.Find(id); + if (authorizationRole != null) + { + UpdateSubjects(authorizationRole, Subjects); + } + else + { + return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet); + } + if (redirect) + return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id)); + else + return Json("OK", JsonRequestBehavior.AllowGet); + } + catch (Exception ex) + { + if (redirect) + throw; + else + return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + } + } + + #endregion + + #region Actions + + public virtual ActionResult Delete(int id, Nullable redirect = false) + { + try + { + var ar = Database.AuthorizationRoles.Find(id); + if (ar != null) + { + ar.Delete(Database); + Database.SaveChanges(); + + if (redirect.HasValue && redirect.Value) + return RedirectToAction(MVC.Config.AuthorizationRole.Index(null)); + else + return Json("OK", JsonRequestBehavior.AllowGet); + } + throw new Exception("Invalid Authorization Role Id"); + } + catch (Exception ex) + { + if (redirect.HasValue && redirect.Value) + throw; + else + return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + } + } + + #endregion + + public virtual ActionResult SearchSubjects(string term) + { + var groupResults = BI.Interop.ActiveDirectory.ActiveDirectory.SearchGroups(term).Cast(); + var userResults = BI.Interop.ActiveDirectory.ActiveDirectory.SearchUsers(term).Cast(); + + var results = groupResults.Concat(userResults).OrderBy(r => r.SamAccountName) + .Select(r => Models.AuthorizationRole.SubjectItem.FromActiveDirectoryObject(r)).ToList(); + + return Json(results, JsonRequestBehavior.AllowGet); + } + + public virtual ActionResult Subject(string Id) + { + var subject = ActiveDirectory.GetObject(Id); + + if (subject == null || !(subject is ActiveDirectoryUserAccount || subject is ActiveDirectoryGroup)) + return Json(null, JsonRequestBehavior.AllowGet); + else + return Json(Models.AuthorizationRole.SubjectItem.FromActiveDirectoryObject(subject), JsonRequestBehavior.AllowGet); + } + } +} diff --git a/Disco.Web/Areas/API/Controllers/BootstrapperController.cs b/Disco.Web/Areas/API/Controllers/BootstrapperController.cs index 838aa11c..3b004b38 100644 --- a/Disco.Web/Areas/API/Controllers/BootstrapperController.cs +++ b/Disco.Web/Areas/API/Controllers/BootstrapperController.cs @@ -1,23 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; +using System; using System.Web.Mvc; -using Disco.BI.Extensions; namespace Disco.Web.Areas.API.Controllers { - public partial class BootstrapperController : dbAdminController + [DiscoAuthorize(Claims.Config.Enrolment.Configure)] + public partial class BootstrapperController : AuthorizedDatabaseController { - public virtual ActionResult MacSshUsername(string MacSshUsername) { try { if (!string.IsNullOrWhiteSpace(MacSshUsername)) { - dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername; - dbContext.SaveChanges(); + Database.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername; + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); } else @@ -36,8 +34,8 @@ namespace Disco.Web.Areas.API.Controllers { if (!string.IsNullOrWhiteSpace(MacSshPassword)) { - dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword; - dbContext.SaveChanges(); + Database.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword; + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); } else diff --git a/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs b/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs index 4f10fc83..6d164f88 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs @@ -1,19 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; +using Disco.BI.Extensions; using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Web; using Disco.Web.Extensions; +using System; +using System.Collections.Generic; using System.Drawing; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class DeviceBatchController : dbAdminController + public partial class DeviceBatchController : AuthorizedDatabaseController { - const string pName = "name"; const string pPurchaseDate = "purchasedate"; const string pSupplier = "supplier"; @@ -29,15 +28,18 @@ namespace Disco.Web.Areas.API.Controllers const string pInsuranceDetails = "insurancedetails"; const string pComments = "comments"; + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false) { + Authorization.Require(Claims.Config.DeviceBatch.Configure); + try { if (id < 0) throw new ArgumentOutOfRangeException("id"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - var deviceBatch = dbContext.DeviceBatches.Find(id); + var deviceBatch = Database.DeviceBatches.Find(id); if (deviceBatch != null) { switch (key.ToLower()) @@ -107,62 +109,86 @@ namespace Disco.Web.Areas.API.Controllers } #region Update Shortcut Methods + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateName(int id, string BatchName = null, bool redirect = false) { return Update(id, pName, BatchName, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdatePurchaseDate(int id, string PurchaseDate = null, bool redirect = false) { return Update(id, pPurchaseDate, PurchaseDate, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateSupplier(int id, string Supplier = null, bool redirect = false) { return Update(id, pSupplier, Supplier, redirect); } - [ValidateInput(false)] + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)] public virtual ActionResult UpdatePurchaseDetails(int id, string PurchaseDetails = null, bool redirect = false) { return Update(id, pPurchaseDetails, PurchaseDetails, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateUnitCost(int id, string UnitCost = null, bool redirect = false) { return Update(id, pUnitCost, UnitCost, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateUnitQuantity(int id, string UnitQuantity = null, bool redirect = false) { return Update(id, pUnitQuantity, UnitQuantity, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateDefaultDeviceModelId(int id, string DefaultDeviceModelId = null, bool redirect = false) { return Update(id, pDefaultDeviceModelId, DefaultDeviceModelId, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateWarrantyValidUntil(int id, string WarrantyValidUntil = null, bool redirect = false) { return Update(id, pWarrantyValidUntil, WarrantyValidUntil, redirect); } - [ValidateInput(false)] + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)] public virtual ActionResult UpdateWarrantyDetails(int id, string WarrantyDetails = null, bool redirect = false) { return Update(id, pWarrantyDetails, WarrantyDetails, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateInsuredDate(int id, string InsuredDate = null, bool redirect = false) { return Update(id, pInsuredDate, InsuredDate, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateInsuranceSupplier(int id, string InsuranceSupplier = null, bool redirect = false) { return Update(id, pInsuranceSupplier, InsuranceSupplier, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] public virtual ActionResult UpdateInsuredUntil(int id, string InsuredUntil = null, bool redirect = false) { return Update(id, pInsuredUntil, InsuredUntil, redirect); } - [ValidateInput(false)] + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)] public virtual ActionResult UpdateInsuranceDetails(int id, string InsuranceDetails = null, bool redirect = false) { return Update(id, pInsuranceDetails, InsuranceDetails, redirect); } - [ValidateInput(false)] + + [DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)] public virtual ActionResult UpdateComments(int id, string Comments = null, bool redirect = false) { return Update(id, pComments, Comments, redirect); @@ -177,14 +203,14 @@ namespace Disco.Web.Areas.API.Controllers else { // Check for Duplicates - var d = dbContext.DeviceBatches.Where(db => db.Id != deviceBatch.Id && db.Name == Name).Count(); + var d = Database.DeviceBatches.Where(db => db.Id != deviceBatch.Id && db.Name == Name).Count(); if (d > 0) { throw new Exception("A Device Batch with that name already exists"); } deviceBatch.Name = Name; } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdatePurchaseDate(DeviceBatch deviceBatch, string PurchaseDate) { @@ -202,7 +228,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateSupplier(DeviceBatch deviceBatch, string Supplier) { @@ -210,7 +236,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.Supplier = null; else deviceBatch.Supplier = Supplier; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdatePurchaseDetails(DeviceBatch deviceBatch, string PurchaseDetails) { @@ -218,7 +244,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.PurchaseDetails = null; else deviceBatch.PurchaseDetails = PurchaseDetails; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateUnitCost(DeviceBatch deviceBatch, string UnitCost) { @@ -236,7 +262,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Currency Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateUnitQuantity(DeviceBatch deviceBatch, string UnitQuantity) { @@ -254,7 +280,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Number"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateDefaultDeviceModelId(DeviceBatch deviceBatch, string DefaultDeviceModelId) { @@ -263,13 +289,13 @@ namespace Disco.Web.Areas.API.Controllers int bId; if (int.TryParse(DefaultDeviceModelId, out bId)) { - var dm = dbContext.DeviceModels.Find(bId); + var dm = Database.DeviceModels.Find(bId); if (dm != null) { deviceBatch.DefaultDeviceModelId = dm.Id; deviceBatch.DefaultDeviceModel = dm; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } } @@ -280,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.DefaultDeviceModelId = null; deviceBatch.DefaultDeviceModel = null; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Device Model Id"); @@ -301,7 +327,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateWarrantyDetails(DeviceBatch deviceBatch, string WarrantyDetails) { @@ -309,7 +335,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.WarrantyDetails = null; else deviceBatch.WarrantyDetails = WarrantyDetails; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuredDate(DeviceBatch deviceBatch, string InsuredDate) { @@ -327,7 +353,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceSupplier(DeviceBatch deviceBatch, string InsuranceSupplier) { @@ -335,7 +361,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.InsuranceSupplier = null; else deviceBatch.InsuranceSupplier = InsuranceSupplier; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuredUntil(DeviceBatch deviceBatch, string InsuredUntil) { @@ -353,7 +379,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceDetails(DeviceBatch deviceBatch, string InsuranceDetails) { @@ -361,7 +387,7 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.InsuranceDetails = null; else deviceBatch.InsuranceDetails = InsuranceDetails; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateComments(DeviceBatch deviceBatch, string Comments) { @@ -369,21 +395,22 @@ namespace Disco.Web.Areas.API.Controllers deviceBatch.Comments = null; else deviceBatch.Comments = Comments; - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion #region Actions + [DiscoAuthorize(Claims.Config.DeviceBatch.Delete)] public virtual ActionResult Delete(int id, Nullable redirect = false) { try { - var db = dbContext.DeviceBatches.Find(id); + var db = Database.DeviceBatches.Find(id); if (db != null) { - db.Delete(dbContext); - dbContext.SaveChanges(); + db.Delete(Database); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DeviceBatch.Index(null)); else @@ -403,27 +430,32 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Index + + [DiscoAuthorize(Claims.Config.DeviceBatch.Show)] public virtual ActionResult Index(int? id) { if (id.HasValue) { - dbContext.Configuration.ProxyCreationEnabled = false; - DeviceBatch deviceBatch = dbContext.DeviceBatches.FirstOrDefault(db => db.Id == id); + Database.Configuration.ProxyCreationEnabled = false; + DeviceBatch deviceBatch = Database.DeviceBatches.FirstOrDefault(db => db.Id == id); return Json(deviceBatch, JsonRequestBehavior.AllowGet); } else { - var deviceBatches = dbContext.DeviceBatches.ToArray(); + var deviceBatches = Database.DeviceBatches.ToArray(); return Json(deviceBatches, JsonRequestBehavior.AllowGet); } } + #endregion #region Timeline + + [DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Config.DeviceBatch.ShowTimeline)] public virtual ActionResult Timeline() { - var batchesInformation = dbContext.DeviceBatches.Select(db => new + var batchesInformation = Database.DeviceBatches.Select(db => new { Name = db.Name, Comments = db.Comments, @@ -466,13 +498,15 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Exporting + + [DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Device.Actions.Export)] public virtual ActionResult ExportDevices(int id) { - DeviceBatch db = dbContext.DeviceBatches.Find(id); + DeviceBatch db = Database.DeviceBatches.Find(id); if (db == null) throw new ArgumentNullException("id", "Invalid Device Batch Id"); - var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceBatchId == db.Id); + var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceBatchId == db.Id); var export = BI.DeviceBI.Importing.Export.GenerateExport(devices); @@ -480,6 +514,7 @@ namespace Disco.Web.Areas.API.Controllers return File(export, "text/csv", filename); } + #endregion } diff --git a/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs b/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs index dd0bbc5a..678d0606 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs @@ -1,17 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; +using System; using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class DeviceCertificateController : dbAdminController + public partial class DeviceCertificateController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.Config.DeviceCertificate.DownloadCertificates)] public virtual ActionResult Download(int id) { - var wc = dbContext.DeviceCertificates.Find(id); + var wc = Database.DeviceCertificates.Find(id); if (wc == null) { throw new Exception("Invalid Device Certificate Id"); diff --git a/Disco.Web/Areas/API/Controllers/DeviceController.cs b/Disco.Web/Areas/API/Controllers/DeviceController.cs index 06de2472..843c1dea 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceController.cs @@ -1,16 +1,17 @@ -using System; -using System.Collections.Generic; +using Disco.BI.Extensions; +using Disco.BI.Interop.ActiveDirectory; +using Disco.Services.Authorization; +using Disco.Services.Users; +using Disco.Services.Web; +using System; +using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; -using Disco.BI.Extensions; -using Disco.BI; -using Disco.BI.Interop.ActiveDirectory; -using System.IO; namespace Disco.Web.Areas.API.Controllers { - public partial class DeviceController : dbAdminController + public partial class DeviceController : AuthorizedDatabaseController { const string pDeviceProfileId = "deviceprofileid"; @@ -22,7 +23,7 @@ namespace Disco.Web.Areas.API.Controllers public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false) { - dbContext.Configuration.LazyLoadingEnabled = true; + Database.Configuration.LazyLoadingEnabled = true; try { @@ -30,27 +31,33 @@ namespace Disco.Web.Areas.API.Controllers throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - var device = dbContext.Devices.Find(id); + var device = Database.Devices.Find(id); if (device != null) { switch (key.ToLower()) { case pDeviceProfileId: + Authorization.Require(Claims.Device.Properties.DeviceProfile); UpdateDeviceProfileId(device, value); break; case pDeviceBatchId: + Authorization.Require(Claims.Device.Properties.DeviceBatch); UpdateDeviceBatchId(device, value); break; case pAssetNumber: + Authorization.Require(Claims.Device.Properties.AssetNumber); UpdateAssetNumber(device, value); break; case pAssignedUserId: + Authorization.Require(Claims.Device.Actions.AssignUser); UpdateAssignedUserId(device, value); break; case pLocation: + Authorization.Require(Claims.Device.Properties.Location); UpdateLocation(device, value); break; case pAllowUnauthenticatedEnrol: + Authorization.Require(Claims.Device.Actions.AllowUnauthenticatedEnrol); UpdateAllowUnauthenticatedEnrol(device, value); break; default: @@ -76,30 +83,43 @@ namespace Disco.Web.Areas.API.Controllers } #region Update Shortcut Methods + + [DiscoAuthorize(Claims.Device.Properties.DeviceProfile)] public virtual ActionResult UpdateDeviceProfileId(string id, string DeviceProfileId = null, bool redirect = false) { return Update(id, pDeviceProfileId, DeviceProfileId, redirect); } + + [DiscoAuthorize(Claims.Device.Properties.DeviceBatch)] public virtual ActionResult UpdateDeviceBatchId(string id, string DeviceBatchId = null, bool redirect = false) { return Update(id, pDeviceBatchId, DeviceBatchId, redirect); } + + [DiscoAuthorize(Claims.Device.Properties.AssetNumber)] public virtual ActionResult UpdateAssetNumber(string id, string AssetNumber = null, bool redirect = false) { return Update(id, pAssetNumber, AssetNumber, redirect); } + + [DiscoAuthorize(Claims.Device.Properties.Location)] public virtual ActionResult UpdateLocation(string id, string Location = null, bool redirect = false) { return Update(id, pLocation, Location, redirect); } + + [DiscoAuthorize(Claims.Device.Actions.AssignUser)] public virtual ActionResult UpdateAssignedUserId(string id, string AssignedUserId = null, bool redirect = false) { return Update(id, pAssignedUserId, AssignedUserId, redirect); } + + [DiscoAuthorize(Claims.Device.Actions.AllowUnauthenticatedEnrol)] public virtual ActionResult UpdateAllowUnauthenticatedEnrol(string id, string AllowUnauthenticatedEnrol = null, bool redirect = false) { return Update(id, pAllowUnauthenticatedEnrol, AllowUnauthenticatedEnrol, redirect); } + #endregion #region Update Properties @@ -110,7 +130,7 @@ namespace Disco.Web.Areas.API.Controllers int pId; if (int.TryParse(DeviceProfileId, out pId)) { - var p = dbContext.DeviceProfiles.Find(pId); + var p = Database.DeviceProfiles.Find(pId); if (p != null) { device.DeviceProfileId = p.Id; @@ -124,7 +144,7 @@ namespace Disco.Web.Areas.API.Controllers adMachineAccount.SetDescription(device); } - dbContext.SaveChanges(); + Database.SaveChanges(); return; } } @@ -138,13 +158,13 @@ namespace Disco.Web.Areas.API.Controllers int bId; if (int.TryParse(DeviceBatchId, out bId)) { - var b = dbContext.DeviceBatches.Find(bId); + var b = Database.DeviceBatches.Find(bId); if (b != null) { device.DeviceBatchId = b.Id; device.DeviceBatch = b; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } } @@ -155,7 +175,7 @@ namespace Disco.Web.Areas.API.Controllers device.DeviceBatchId = null; device.DeviceBatch = null; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Device Batch Id"); @@ -166,7 +186,7 @@ namespace Disco.Web.Areas.API.Controllers device.AssetNumber = null; else device.AssetNumber = AssetNumber.Trim(); - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateLocation(Disco.Models.Repository.Device device, string Location) { @@ -174,27 +194,24 @@ namespace Disco.Web.Areas.API.Controllers device.Location = null; else device.Location = Location.Trim(); - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateAssignedUserId(Disco.Models.Repository.Device device, string UserId) { - var daus = dbContext.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == device.SerialNumber && m.UnassignedDate == null); + var daus = Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == device.SerialNumber && m.UnassignedDate == null); Disco.Models.Repository.User u = null; if (!string.IsNullOrEmpty(UserId)) { - // Changed 2012-12-13 G# - Stop error when assigning user - Force Refresh - // http://www.discoict.com.au/forum/support/2012/11/error-when-assigning-multiple-devices-to-single-user.aspx - //u = BI.UserBI.UserCache.GetUser(UserId, dbContext); - u = BI.UserBI.UserCache.GetUser(UserId, dbContext, true); - // End Changed 2012-12-13 G# + UserService.GetUser(UserId, Database, true); + if (u == null) { throw new Exception("Invalid Username"); } } - device.AssignDevice(dbContext, u); - dbContext.SaveChanges(); + device.AssignDevice(Database, u); + Database.SaveChanges(); } private void UpdateAllowUnauthenticatedEnrol(Disco.Models.Repository.Device device, string AllowUnauthenticatedEnrol) { @@ -207,23 +224,25 @@ namespace Disco.Web.Areas.API.Controllers if (device.AllowUnauthenticatedEnrol != bAllowUnauthenticatedEnrol) { device.AllowUnauthenticatedEnrol = bAllowUnauthenticatedEnrol; - dbContext.SaveChanges(); + Database.SaveChanges(); } } #endregion #region Device Actions + + [DiscoAuthorize(Claims.Device.Actions.Decommission)] public virtual ActionResult Decommission(string id, int Reason, bool redirect) { - var d = dbContext.Devices.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var d = Database.Devices.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (d != null) { if (d.CanDecommission()) { d.OnDecommission((Disco.Models.Repository.Device.DecommissionReasons)Reason); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Device.Show(id)); else @@ -236,17 +255,19 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Device.Actions.Recommission)] public virtual ActionResult Recommission(string id, bool redirect) { - var d = dbContext.Devices.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var d = Database.Devices.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (d != null) { if (d.CanRecommission()) { d.OnRecommission(); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Device.Show(id)); else @@ -259,17 +280,19 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Device.Actions.Delete)] public virtual ActionResult Delete(string id, bool redirect) { - var j = dbContext.Devices.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var j = Database.Devices.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (j != null) { if (j.CanDelete()) { - j.OnDelete(dbContext); + j.OnDelete(Database); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Device.Index()); else @@ -282,26 +305,28 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet); } + #endregion + [DiscoAuthorize(Claims.Device.Actions.GenerateDocuments)] public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(DocumentTemplateId)) throw new ArgumentNullException("AttachmentTypeId"); - var device = dbContext.Devices.Find(id); + var device = Database.Devices.Find(id); if (device != null) { - var documentTemplate = dbContext.DocumentTemplates.Find(DocumentTemplateId); + var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId); if (documentTemplate != null) { var timeStamp = DateTime.Now; Stream pdf; using (var generationState = Disco.Models.BI.DocumentTemplates.DocumentState.DefaultState()){ - pdf = documentTemplate.GeneratePdf(dbContext, device, DiscoApplication.CurrentUser, timeStamp, generationState); + pdf = documentTemplate.GeneratePdf(Database, device, UserService.CurrentUser, timeStamp, generationState); } - dbContext.SaveChanges(); + Database.SaveChanges(); return File(pdf, "application/pdf", string.Format("{0}_{1}_{2:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, device.SerialNumber, timeStamp)); } else @@ -315,16 +340,17 @@ namespace Disco.Web.Areas.API.Controllers } } + [DiscoAuthorize(Claims.Device.Show)] public virtual ActionResult LastNetworkLogonDate(string id) { - var device = dbContext.Devices.Find(id); + var device = Database.Devices.Find(id); if (device == null) { return HttpNotFound("Invalid Device Serial Number"); } if (device.UpdateLastNetworkLogonDate()) - dbContext.SaveChanges(); + Database.SaveChanges(); var result = new { @@ -337,13 +363,14 @@ namespace Disco.Web.Areas.API.Controllers } #region Device Attachements - [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] + + [DiscoAuthorize(Claims.Device.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentDownload(int id) { - var da = dbContext.DeviceAttachments.Find(id); + var da = Database.DeviceAttachments.Find(id); if (da != null) { - var filePath = da.RepositoryFilename(dbContext); + var filePath = da.RepositoryFilename(Database); if (System.IO.File.Exists(filePath)) { return File(filePath, da.MimeType, da.Filename); @@ -355,13 +382,14 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } - [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] + + [DiscoAuthorize(Claims.Device.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentThumbnail(int id) { - var da = dbContext.DeviceAttachments.Find(id); + var da = Database.DeviceAttachments.Find(id); if (da != null) { - var thumbPath = da.RepositoryThumbnailFilename(dbContext); + var thumbPath = da.RepositoryThumbnailFilename(Database); if (System.IO.File.Exists(thumbPath)) { if (thumbPath.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) @@ -374,9 +402,11 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } + + [DiscoAuthorize(Claims.Device.Actions.AddAttachments)] public virtual ActionResult AttachmentUpload(string id, string Comments) { - var d = dbContext.Devices.Find(id); + var d = Database.Devices.Find(id); if (d != null) { if (Request.Files.Count > 0) @@ -391,18 +421,18 @@ namespace Disco.Web.Areas.API.Controllers var da = new Disco.Models.Repository.DeviceAttachment() { DeviceSerialNumber = d.SerialNumber, - TechUserId = DiscoApplication.CurrentUser.Id, + TechUserId = UserService.CurrentUserId, Filename = file.FileName, MimeType = contentType, Timestamp = DateTime.Now, Comments = Comments }; - dbContext.DeviceAttachments.Add(da); - dbContext.SaveChanges(); + Database.DeviceAttachments.Add(da); + Database.SaveChanges(); - da.SaveAttachment(dbContext, file.InputStream); + da.SaveAttachment(Database, file.InputStream); - da.GenerateThumbnail(dbContext); + da.GenerateThumbnail(Database); return Json(da.Id, JsonRequestBehavior.AllowGet); } @@ -411,9 +441,11 @@ namespace Disco.Web.Areas.API.Controllers } throw new Exception("Invalid Device Serial Number"); } + + [DiscoAuthorize(Claims.Device.ShowAttachments)] public virtual ActionResult Attachment(int id) { - var da = dbContext.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var da = Database.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (da != null) { @@ -427,9 +459,11 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Device.ShowAttachments)] public virtual ActionResult Attachments(string id) { - var d = dbContext.Devices.Include("DeviceAttachments.TechUser").Where(m => m.SerialNumber == id).FirstOrDefault(); + var d = Database.Devices.Include("DeviceAttachments.TechUser").Where(m => m.SerialNumber == id).FirstOrDefault(); if (d != null) { var m = new Models.Attachment.AttachmentsModel() @@ -442,22 +476,21 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid Device Serial Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments)] public virtual ActionResult AttachmentRemove(int id) { - var da = dbContext.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var da = Database.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (da != null) { - // 2012-02-17 G# Remove - 'Delete Own Comments' policy - //if (da.TechUserId == DiscoApplication.CurrentUser.Id) - //{ - da.OnDelete(dbContext); - dbContext.SaveChanges(); + if (da.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase)) + Authorization.RequireAny(Claims.Device.Actions.RemoveAnyAttachments, Claims.Device.Actions.RemoveOwnAttachments); + else + Authorization.Require(Claims.Device.Actions.RemoveAnyAttachments); + + da.OnDelete(Database); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); - //} - //else - //{ - // return Json("You can only delete your own attachments.", JsonRequestBehavior.AllowGet); - //} } return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet); } @@ -465,6 +498,8 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Importing / Exporting + + [DiscoAuthorize(Claims.Device.Actions.Import)] public virtual ActionResult ImportParse(HttpPostedFileBase ImportFile) { if (ImportFile == null || ImportFile.ContentLength == 0) @@ -481,6 +516,7 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Device.Actions.Import)] public virtual ActionResult ImportProcess(string ParseTaskSessionKey) { if (string.IsNullOrWhiteSpace(ParseTaskSessionKey)) @@ -493,10 +529,11 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Device.Actions.Export)] public virtual ActionResult ExportAllDevices() { // Non-Decommissioned Devices - var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue); + var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue); var export = BI.DeviceBI.Importing.Export.GenerateExport(devices); @@ -504,13 +541,14 @@ namespace Disco.Web.Areas.API.Controllers return File(export, "text/csv", filename); } + #endregion + [DiscoAuthorize(Claims.DiscoAdminAccount)] public virtual ActionResult MigrateDeviceMacAddressesFromLog() { var taskStatus = Disco.BI.DeviceBI.Migration.LogMacAddressImporting.ScheduleImmediately(); return RedirectToAction(MVC.Config.Logging.TaskStatus(taskStatus.SessionId)); } - } } diff --git a/Disco.Web/Areas/API/Controllers/DeviceModelController.cs b/Disco.Web/Areas/API/Controllers/DeviceModelController.cs index 0dd59bb1..e24f2dd1 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceModelController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceModelController.cs @@ -1,32 +1,36 @@ -using System; +using Disco.BI.Extensions; +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Plugins; +using Disco.Services.Plugins.Features.WarrantyProvider; +using Disco.Services.Web; +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Models.Repository; -using Disco.Services.Plugins; -using Disco.Services.Plugins.Features.WarrantyProvider; namespace Disco.Web.Areas.API.Controllers { - public partial class DeviceModelController : dbAdminController + public partial class DeviceModelController : AuthorizedDatabaseController { const string pDescription = "description"; const string pDefaultPurchaseDate = "defaultpurchasedate"; const string pDefaultWarrantyProvider = "defaultwarrantyprovider"; + [DiscoAuthorize(Claims.Config.DeviceModel.Configure)] public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false) { + Authorization.Require(Claims.Config.DeviceModel.Configure); + try { if (id < 0) throw new ArgumentOutOfRangeException("id"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - var deviceModel = dbContext.DeviceModels.Find(id); + var deviceModel = Database.DeviceModels.Find(id); if (deviceModel != null) { switch (key.ToLower()) @@ -63,18 +67,25 @@ namespace Disco.Web.Areas.API.Controllers } #region Update Shortcut Methods + + [DiscoAuthorize(Claims.Config.DeviceModel.Configure)] public virtual ActionResult UpdateDescription(int id, string Description = null, bool redirect = false) { return Update(id, pDescription, Description, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceModel.Configure)] public virtual ActionResult UpdateDefaultPurchaseDate(int id, string DefaultPurchaseDate = null, bool redirect = false) { return Update(id, pDefaultPurchaseDate, DefaultPurchaseDate, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceModel.Configure)] public virtual ActionResult UpdateDefaultWarrantyProvider(int id, string DefaultWarrantyProvider = null, bool redirect = false) { return Update(id, pDefaultWarrantyProvider, DefaultWarrantyProvider, redirect); } + #endregion #region Update Properties @@ -84,7 +95,7 @@ namespace Disco.Web.Areas.API.Controllers deviceModel.Description = null; else deviceModel.Description = Description; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateDefaultPurchaseDate(Disco.Models.Repository.DeviceModel deviceModel, string DefaultPurchaseDate) { @@ -104,7 +115,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateDefaultWarrantyProvider(Disco.Models.Repository.DeviceModel deviceModel, string DefaultWarrantyProvider) { @@ -118,7 +129,7 @@ namespace Disco.Web.Areas.API.Controllers var WarrantyProvider = Plugins.GetPluginFeature(DefaultWarrantyProvider, typeof(WarrantyProviderFeature)); deviceModel.DefaultWarrantyProvider = WarrantyProvider.Id; } - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion @@ -128,7 +139,7 @@ namespace Disco.Web.Areas.API.Controllers { if (id.HasValue) { - var m = dbContext.DeviceModels.Find(id.Value); + var m = Database.DeviceModels.Find(id.Value); if (m != null) { // Try From DataStore @@ -156,17 +167,18 @@ namespace Disco.Web.Areas.API.Controllers } return File(Links.ClientSource.Style.Images.DeviceTypes.Unknown_png, "image/png"); } - [HttpPost] + + [DiscoAuthorize(Claims.Config.DeviceModel.Configure), HttpPost] public virtual ActionResult Image(int id, bool redirect, HttpPostedFileBase Image) { if (Image != null && Image.ContentLength > 0) { - var dm = dbContext.DeviceModels.Find(id); + var dm = Database.DeviceModels.Find(id); if (dm != null) { if (dm.ImageImport(Image.InputStream)) { - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Config.DeviceModel.Index(dm.Id)); else @@ -194,15 +206,16 @@ namespace Disco.Web.Areas.API.Controllers #region Actions + [DiscoAuthorize(Claims.Config.DeviceModel.Delete)] public virtual ActionResult Delete(int id, Nullable redirect = false) { try { - var dm = dbContext.DeviceModels.Find(id); + var dm = Database.DeviceModels.Find(id); if (dm != null) { - dm.Delete(dbContext); - dbContext.SaveChanges(); + dm.Delete(Database); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DeviceModel.Index(null)); else @@ -223,9 +236,10 @@ namespace Disco.Web.Areas.API.Controllers #region Device Model Components + [DiscoAuthorize(Claims.Config.DeviceModel.Show)] public virtual ActionResult Component(int id) { - var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); + var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); if (dc != null) { return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet); @@ -233,12 +247,13 @@ namespace Disco.Web.Areas.API.Controllers return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet); } + [DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)] public virtual ActionResult ComponentAdd(int? id, string Description, string Cost) { DeviceModel dm = null; if (id.HasValue) { - dm = dbContext.DeviceModels.Find(id.Value); + dm = Database.DeviceModels.Find(id.Value); if (dm == null) { return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Model Id" }, JsonRequestBehavior.AllowGet); @@ -263,36 +278,40 @@ namespace Disco.Web.Areas.API.Controllers } dc.JobSubTypes = new List(); - dbContext.DeviceComponents.Add(dc); - dbContext.SaveChanges(); + Database.DeviceComponents.Add(dc); + Database.SaveChanges(); return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)] public virtual ActionResult ComponentUpdateJobSubTypes(int id, List JobSubTypes) { - var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); + var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); if (dc != null) { dc.JobSubTypes.Clear(); if (JobSubTypes != null) { - var jsts = dbContext.JobSubTypes.Where(jst => JobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id)); + var jsts = Database.JobSubTypes.Where(jst => JobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id)); foreach (var jst in jsts) { dc.JobSubTypes.Add(jst); } } - dbContext.SaveChanges(); + Database.SaveChanges(); return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet); } return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)] public virtual ActionResult ComponentUpdate(int id, string Description, string Cost) { - var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); + var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); if (dc != null) { decimal cost = 0; @@ -306,20 +325,22 @@ namespace Disco.Web.Areas.API.Controllers dc.Description = Description; dc.Cost = cost; - dbContext.SaveChanges(); + Database.SaveChanges(); return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet); } return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)] public virtual ActionResult ComponentRemove(int id) { - var dc = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => c.Id == id).FirstOrDefault(); + var dc = Database.DeviceComponents.Include("JobSubTypes").Where(c => c.Id == id).FirstOrDefault(); if (dc != null) { dc.JobSubTypes.Clear(); - dbContext.DeviceComponents.Remove(dc); - dbContext.SaveChanges(); + Database.DeviceComponents.Remove(dc); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); } return Json("Invalid Device Component Id", JsonRequestBehavior.AllowGet); @@ -327,21 +348,23 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Index + [DiscoAuthorize(Claims.Config.DeviceModel.Show)] public virtual ActionResult Index() { - var deviceModels = dbContext.DeviceModels.ToArray().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToArray(); + var deviceModels = Database.DeviceModels.ToArray().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToArray(); return Json(deviceModels, JsonRequestBehavior.AllowGet); } #endregion #region Exporting + [DiscoAuthorizeAll(Claims.Config.DeviceModel.Show, Claims.Device.Actions.Export)] public virtual ActionResult ExportDevices(int id) { - DeviceModel dm = dbContext.DeviceModels.Find(id); + DeviceModel dm = Database.DeviceModels.Find(id); if (dm == null) throw new ArgumentNullException("id", "Invalid Device Model Id"); - var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceModelId == dm.Id); + var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceModelId == dm.Id); var export = BI.DeviceBI.Importing.Export.GenerateExport(devices); diff --git a/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs b/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs index 9fb5250a..afb42372 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs @@ -1,16 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Data.Configuration.Modules; +using Disco.BI.Extensions; using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Web; +using System; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class DeviceProfileController : dbAdminController + public partial class DeviceProfileController : AuthorizedDatabaseController { const string pDescription = "description"; @@ -25,15 +23,18 @@ namespace Disco.Web.Areas.API.Controllers const string pEnforceOrganisationalUnit = "enforceorganisationalunit"; const string pProvisionADAccount = "provisionadaccount"; + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult Update(int id, string key, string value = null, Nullable redirect = null) { + Authorization.Require(Claims.Config.DeviceProfile.Configure); + try { if (id < 0) throw new ArgumentOutOfRangeException("id"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - var deviceProfile = dbContext.DeviceProfiles.Find(id); + var deviceProfile = Database.DeviceProfiles.Find(id); if (deviceProfile != null) { switch (key.ToLower()) @@ -60,6 +61,7 @@ namespace Disco.Web.Areas.API.Controllers UpdateDefaultOrganisationAddress(deviceProfile, value); break; case pComputerNameTemplate: + Authorization.Require(Claims.Config.DeviceProfile.ConfigureComputerNameTemplate); UpdateComputerNameTemplate(deviceProfile, value); break; case pEnforceComputerNameConvention: @@ -92,54 +94,75 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + #region Update Shortcut Methods + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateDescription(int id, string Description = null, Nullable redirect = null) { return Update(id, pDescription, Description, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateName(int id, string ProfileName = null, Nullable redirect = null) { return Update(id, pName, ProfileName, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateShortName(int id, string ShortName = null, Nullable redirect = null) { return Update(id, pShortName, ShortName, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateDistributionType(int id, string DistributionType = null, Nullable redirect = null) { return Update(id, pDistributionType, DistributionType, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateCertificateProviderId(int id, string CertificateProviderId = null, Nullable redirect = null) { return Update(id, pCertificateProviderId, CertificateProviderId, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateOrganisationalUnit(int id, string OrganisationalUnit = null, Nullable redirect = null) { return Update(id, pOrganisationalUnit, OrganisationalUnit, redirect); } + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateDefaultOrganisationAddress(int id, string DefaultOrganisationAddress = null, Nullable redirect = null) { return Update(id, pDefaultOrganisationAddress, DefaultOrganisationAddress, redirect); } + + [DiscoAuthorizeAll(Claims.Config.DeviceProfile.Configure, Claims.Config.DeviceProfile.ConfigureComputerNameTemplate)] public virtual ActionResult UpdateComputerNameTemplate(int id, string ComputerNameTemplate = null, Nullable redirect = null) { return Update(id, pComputerNameTemplate, ComputerNameTemplate, redirect); } - // Added 2012-06-14 G# + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateEnforceComputerNameConvention(int id, string EnforceComputerNameConvention = null, Nullable redirect = null) { return Update(id, pEnforceComputerNameConvention, EnforceComputerNameConvention, redirect); } - // Added 2012-06-14 G# + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateEnforceOrganisationalUnit(int id, string EnforceOrganisationalUnit = null, Nullable redirect = null) { return Update(id, pEnforceOrganisationalUnit, EnforceOrganisationalUnit, redirect); } - // Added 2012-06-28 G# + + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult UpdateProvisionADAccount(int id, string ProvisionADAccount = null, Nullable redirect = null) { return Update(id, pProvisionADAccount, ProvisionADAccount, redirect); } + #endregion #region Update Properties @@ -149,7 +172,7 @@ namespace Disco.Web.Areas.API.Controllers deviceProfile.Description = null; else deviceProfile.Description = Description; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateName(Disco.Models.Repository.DeviceProfile deviceProfile, string Name) @@ -158,7 +181,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Profile name cannot be empty"); else deviceProfile.Name = Name; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateShortName(Disco.Models.Repository.DeviceProfile deviceProfile, string ShortName) @@ -167,7 +190,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Profile short name cannot be empty"); else deviceProfile.ShortName = ShortName; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateDistributionType(Disco.Models.Repository.DeviceProfile deviceProfile, string DistributionType) @@ -175,10 +198,8 @@ namespace Disco.Web.Areas.API.Controllers int iDt; if (int.TryParse(DistributionType, out iDt)) { - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //deviceProfile.Configuration(dbContext).DistributionType = (DeviceProfileConfiguration.DeviceProfileDistributionTypes)iDt; deviceProfile.DistributionType = (Disco.Models.Repository.DeviceProfile.DistributionTypes)iDt; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Distribution Type Number"); @@ -199,28 +220,29 @@ namespace Disco.Web.Areas.API.Controllers else deviceProfile.CertificateProviderId = featureManifest.Id; } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateOrganisationalUnit(Disco.Models.Repository.DeviceProfile deviceProfile, string OrganisationalUnit) { if (string.IsNullOrWhiteSpace(OrganisationalUnit)) OrganisationalUnit = null; - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //deviceProfile.Configuration(dbContext).OrganisationalUnit = OrganisationalUnit; + deviceProfile.OrganisationalUnit = OrganisationalUnit; - dbContext.SaveChanges(); + Database.SaveChanges(); } + private void UpdateComputerNameTemplate(Disco.Models.Repository.DeviceProfile deviceProfile, string ComputerNameTemplate) { + Authorization.Require(Claims.Config.DeviceProfile.ConfigureComputerNameTemplate); + if (string.IsNullOrWhiteSpace(ComputerNameTemplate)) throw new Exception("ComputerNameTemplate is Required"); - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //deviceProfile.Configuration(dbContext).ComputerNameTemplate = ComputerNameTemplate; + deviceProfile.ComputerNameTemplate = ComputerNameTemplate; - dbContext.SaveChanges(); + Database.SaveChanges(); deviceProfile.ComputerNameInvalidateCache(); } @@ -237,7 +259,7 @@ namespace Disco.Web.Areas.API.Controllers int daoId; if (int.TryParse(DefaultOrganisationAddress, out daoId)) { - var oa = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId); + var oa = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId); if (oa != null) { deviceProfile.DefaultOrganisationAddress = oa.Id; @@ -254,10 +276,9 @@ namespace Disco.Web.Areas.API.Controllers } - dbContext.SaveChanges(); + Database.SaveChanges(); } - // Added 2012-06-14 G# private void UpdateEnforceComputerNameConvention(Disco.Models.Repository.DeviceProfile deviceProfile, string EnforceComputerNameConvention) { bool bValue; @@ -265,12 +286,12 @@ namespace Disco.Web.Areas.API.Controllers { deviceProfile.EnforceComputerNameConvention = bValue; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Boolean Value"); } - // Added 2012-06-14 G# + private void UpdateEnforceOrganisationalUnit(Disco.Models.Repository.DeviceProfile deviceProfile, string EnforceOrganisationalUnit) { bool bValue; @@ -278,12 +299,12 @@ namespace Disco.Web.Areas.API.Controllers { deviceProfile.EnforceOrganisationalUnit = bValue; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Boolean Value"); } - // Added 2012-06-28 G# + private void UpdateProvisionADAccount(Disco.Models.Repository.DeviceProfile deviceProfile, string ProvisionADAccount) { bool bValue; @@ -291,13 +312,14 @@ namespace Disco.Web.Areas.API.Controllers { deviceProfile.ProvisionADAccount = bValue; - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Boolean Value"); } #endregion + [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] public virtual ActionResult OrganisationalUnits() { var OUs = BI.Interop.ActiveDirectory.ActiveDirectory.GetOrganisationalUnitStructure(); @@ -306,15 +328,16 @@ namespace Disco.Web.Areas.API.Controllers #region Actions + [DiscoAuthorize(Claims.Config.DeviceProfile.Delete)] public virtual ActionResult Delete(int id, Nullable redirect = false) { try { - var dp = dbContext.DeviceProfiles.Find(id); + var dp = Database.DeviceProfiles.Find(id); if (dp != null) { - dp.Delete(dbContext); - dbContext.SaveChanges(); + dp.Delete(Database); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DeviceProfile.Index(null)); else @@ -334,15 +357,17 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Defaults + + [DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)] public virtual ActionResult Default(int id, Nullable redirect = null) { try { - var dp = dbContext.DeviceProfiles.Find(id); + var dp = Database.DeviceProfiles.Find(id); if (dp != null) { - dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = dp.Id; - dbContext.SaveChanges(); + Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = dp.Id; + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DeviceProfile.Index(id)); else @@ -358,6 +383,8 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + + [DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)] public virtual ActionResult DefaultAddDeviceOffline(int id, Nullable redirect = false) { try @@ -365,7 +392,7 @@ namespace Disco.Web.Areas.API.Controllers int defaultValue = 0; if (id > 0) { - var dp = dbContext.DeviceProfiles.Find(id); + var dp = Database.DeviceProfiles.Find(id); if (dp != null) { defaultValue = dp.Id; @@ -375,8 +402,8 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Device Profile Number"); } } - dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = defaultValue; - dbContext.SaveChanges(); + Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = defaultValue; + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DeviceProfile.Index(id)); else @@ -390,16 +417,18 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + #endregion #region Exporting + [DiscoAuthorizeAll(Claims.Config.DeviceProfile.Show, Claims.Device.Actions.Export)] public virtual ActionResult ExportDevices(int id) { - DeviceProfile dp = dbContext.DeviceProfiles.Find(id); + DeviceProfile dp = Database.DeviceProfiles.Find(id); if (dp == null) throw new ArgumentNullException("id", "Invalid Device Profile Id"); - var devices = dbContext.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceProfileId == dp.Id); + var devices = Database.Devices.Where(d => !d.DecommissionedDate.HasValue && d.DeviceProfileId == dp.Id); var export = BI.DeviceBI.Importing.Export.GenerateExport(devices); diff --git a/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs b/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs index e01e5229..e58ad762 100644 --- a/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs +++ b/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs @@ -1,15 +1,18 @@ -using System; +using Disco.BI; +using Disco.BI.Extensions; +using Disco.Models.Repository; +using Disco.Services.Authorization; +using Disco.Services.Users; +using Disco.Services.Web; +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Models.Repository; namespace Disco.Web.Areas.API.Controllers { - public partial class DocumentTemplateController : dbAdminController + public partial class DocumentTemplateController : AuthorizedDatabaseController { const string pDescription = "description"; @@ -17,6 +20,7 @@ namespace Disco.Web.Areas.API.Controllers const string pFilterExpression = "filterexpression"; const string pFlattenForm = "flattenform"; + [DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false) { try @@ -25,7 +29,7 @@ namespace Disco.Web.Areas.API.Controllers throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); if (documentTemplate != null) { switch (key.ToLower()) @@ -37,6 +41,7 @@ namespace Disco.Web.Areas.API.Controllers UpdateScope(documentTemplate, value); break; case pFilterExpression: + Authorization.Require(Claims.Config.DocumentTemplate.ConfigureFilterExpression); UpdateFilterExpression(documentTemplate, value); break; case pFlattenForm: @@ -64,16 +69,16 @@ namespace Disco.Web.Areas.API.Controllers } } - [HttpGet] + [DiscoAuthorize(Claims.Config.DocumentTemplate.Upload), HttpGet] public virtual ActionResult Template(string id) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); if (documentTemplate == null) throw new ArgumentException("Invalid Document Template Id", "id"); - var filename = documentTemplate.RepositoryFilename(dbContext); + var filename = documentTemplate.RepositoryFilename(Database); if (System.IO.File.Exists(filename)) { return File(filename, DocumentTemplate.PdfMimeType, string.Format("{0}.pdf", documentTemplate.Id)); @@ -83,18 +88,19 @@ namespace Disco.Web.Areas.API.Controllers throw new InvalidOperationException("Template not found"); } } - [HttpPost] + + [DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Upload, Claims.Config.DocumentTemplate.Configure), HttpPost] public virtual ActionResult Template(string id, bool redirect, HttpPostedFileBase Template) { try { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); if (documentTemplate == null) throw new ArgumentException("Invalid Document Template Id", "id"); - documentTemplate.SavePdfTemplate(dbContext, Template.InputStream); + documentTemplate.SavePdfTemplate(Database, Template.InputStream); if (redirect) return RedirectToAction(MVC.Config.DocumentTemplate.Index(documentTemplate.Id)); @@ -111,29 +117,34 @@ namespace Disco.Web.Areas.API.Controllers } #region Update Shortcut Methods + [DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult UpdateDescription(string id, string Description = null, bool redirect = false) { return Update(id, pDescription, Description, redirect); } + [DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)] public virtual ActionResult UpdateFilterExpression(string id, string FilterExpression = null, bool redirect = false) { return Update(id, pFilterExpression, FilterExpression, redirect); } + [DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult UpdateFlattenForm(string id, string FlattenForm = null, bool redirect = false) { return Update(id, pFlattenForm, FlattenForm, redirect); } + [DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult UpdateScope(string id, string Scope = null, bool redirect = false) { return Update(id, pScope, Scope, redirect); } + [DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult UpdateSubTypes(string id, List SubTypes = null) { try { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); UpdateSubTypes(documentTemplate, SubTypes); @@ -153,7 +164,7 @@ namespace Disco.Web.Areas.API.Controllers if (!string.IsNullOrWhiteSpace(Description)) { documentTemplate.Description = Description.Trim(); - dbContext.SaveChanges(); + Database.SaveChanges(); return; } throw new Exception("Invalid Description"); @@ -164,7 +175,7 @@ namespace Disco.Web.Areas.API.Controllers { if (Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.ToList().Contains(Scope)) { - dbContext.Configuration.LazyLoadingEnabled = true; + Database.Configuration.LazyLoadingEnabled = true; documentTemplate.Scope = Scope; @@ -175,7 +186,7 @@ namespace Disco.Web.Areas.API.Controllers documentTemplate.JobSubTypes.Remove(st); } - dbContext.SaveChanges(); + Database.SaveChanges(); return; } } @@ -194,7 +205,7 @@ namespace Disco.Web.Areas.API.Controllers // Invalidate Cache documentTemplate.FilterExpressionInvalidateCache(); - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateFlattenForm(Disco.Models.Repository.DocumentTemplate documentTemplate, string FlattenForm) { @@ -211,11 +222,11 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Boolean Format"); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateSubTypes(Disco.Models.Repository.DocumentTemplate documentTemplate, List SubTypes) { - dbContext.Configuration.LazyLoadingEnabled = true; + Database.Configuration.LazyLoadingEnabled = true; // Remove All Existing if (documentTemplate.JobSubTypes != null) @@ -232,35 +243,21 @@ namespace Disco.Web.Areas.API.Controllers { var typeId = stId.Substring(0, stId.IndexOf("_")); var subTypeId = stId.Substring(stId.IndexOf("_") + 1); - var subType = dbContext.JobSubTypes.FirstOrDefault(jst => jst.JobTypeId == typeId && jst.Id == subTypeId); + var subType = Database.JobSubTypes.FirstOrDefault(jst => jst.JobTypeId == typeId && jst.Id == subTypeId); subTypes.Add(subType); } documentTemplate.JobSubTypes = subTypes; } - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion - - #region Actions - [OutputCache(NoStore = true, Duration = 0)] + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages), OutputCache(NoStore = true, Duration = 0)] public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber) { - // Load from Cache - //var cacheKey = string.Format("Disco.BI.DocumentImporter-{0}-{1}", SessionId, PageNumber); - //var cacheValue = HttpContext.Cache.Get(cacheKey); - //if (cacheValue != null) - //{ - // var cacheFile = cacheValue as byte[]; - // if (cacheFile != null) - // { - // return File(cacheFile, "image/png"); - // } - //} - - var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); + var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages"); var filename = System.IO.Path.Combine(dataStoreSessionPagesCacheLocation, string.Format("{0}-{1}", SessionId, PageNumber)); if (System.IO.File.Exists(filename)) return File(filename, "image/png"); @@ -268,9 +265,10 @@ namespace Disco.Web.Areas.API.Controllers return File("~/ClientSource/Style/Images/Status/fileBroken256.png", "image/png"); } + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult ImporterUndetectedFiles() { - var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); + var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned"); var undetectedDirectory = new System.IO.DirectoryInfo(undetectedLocation); var m = undetectedDirectory.GetFiles("*.pdf").Select(f => new Models.DocumentTemplate.ImporterUndetectedFilesModel() { @@ -281,6 +279,8 @@ namespace Disco.Web.Areas.API.Controllers return Json(m); } + + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult ImporterUndetectedDataIdLookup(string id, string term, int limitCount = 20) { if (!string.IsNullOrEmpty(id) && !string.IsNullOrWhiteSpace(term)) @@ -306,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers } else { - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); if (documentTemplate != null) searchScope = documentTemplate.Scope; else @@ -318,13 +318,13 @@ namespace Disco.Web.Areas.API.Controllers switch (searchScope) { case DocumentTemplate.DocumentTemplateScopes.Device: - results = BI.DeviceBI.Searching.Search(dbContext, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); + results = BI.DeviceBI.Searching.Search(Database, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); break; case DocumentTemplate.DocumentTemplateScopes.Job: - results = BI.JobBI.Searching.Search(dbContext, term, limitCount, false).Items.Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); + results = BI.JobBI.Searching.Search(Database, term, limitCount, false).Items.Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); break; case DocumentTemplate.DocumentTemplateScopes.User: - results = BI.UserBI.Searching.Search(dbContext, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); + results = BI.UserBI.Searching.Search(Database, term, limitCount).Select(sr => Models.DocumentTemplate.ImporterUndetectedDataIdLookupModel.FromSearchResultItem(sr)).ToArray(); break; default: results = null; @@ -337,11 +337,13 @@ namespace Disco.Web.Areas.API.Controllers } return Json(null, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult ImporterUndetectedFile(string id, Nullable Source, Nullable Thumbnail) { if (!string.IsNullOrEmpty(id)) { - var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); + var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned"); if (Source.HasValue && Source.Value) { var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf")); @@ -372,11 +374,13 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound(); } + + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult ImporterUndetectedAssign(string id, string DocumentTemplateId, string DataId) { - var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); + var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned"); var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf")); - if (BI.Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, DocumentTemplateId, DataId, DiscoApplication.CurrentUser.Id, DateTime.Now)) + if (BI.Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, Database, DocumentTemplateId, DataId, UserService.CurrentUserId, DateTime.Now)) { // Delete File System.IO.File.Delete(filename); @@ -396,9 +400,11 @@ namespace Disco.Web.Areas.API.Controllers return Json("Unable to Import File with the supplied parameters"); } } + + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult ImporterUndetectedDelete(string id) { - var undetectedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); + var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned"); var filename = System.IO.Path.Combine(undetectedLocation, string.Concat(id, ".pdf")); if (System.IO.File.Exists(filename)) { @@ -421,32 +427,49 @@ namespace Disco.Web.Areas.API.Controllers } } + [DiscoAuthorize(Claims.Config.DocumentTemplate.BulkGenerate)] public virtual ActionResult BulkGenerate(string id, string DataIds = null) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(DataIds)) throw new ArgumentNullException("DataIds"); - var documentTemplate = dbContext.DocumentTemplates.Find(id); + var documentTemplate = Database.DocumentTemplates.Find(id); if (documentTemplate == null) throw new ArgumentException("Invalid Document Template Id", "id"); + switch (documentTemplate.Scope) + { + case DocumentTemplate.DocumentTemplateScopes.Device: + Authorization.Require(Claims.Device.Actions.GenerateDocuments); + break; + case DocumentTemplate.DocumentTemplateScopes.Job: + Authorization.Require(Claims.Job.Actions.GenerateDocuments); + break; + case DocumentTemplate.DocumentTemplateScopes.User: + Authorization.Require(Claims.User.Actions.GenerateDocuments); + break; + default: + throw new InvalidOperationException("Unknown DocumentType Scope"); + } + var dataIds = DataIds.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var timeStamp = DateTime.Now; - var pdf = documentTemplate.GeneratePdfBulk(dbContext, DiscoApplication.CurrentUser, timeStamp, dataIds); + var pdf = documentTemplate.GeneratePdfBulk(Database, UserService.CurrentUser, timeStamp, dataIds); return File(pdf, "application/pdf", string.Format("{0}_Bulk_{1:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, timeStamp)); } + [DiscoAuthorize(Claims.Config.DocumentTemplate.Delete)] public virtual ActionResult Delete(string id, Nullable redirect = false) { try { - var at = dbContext.DocumentTemplates.Include("JobSubTypes").FirstOrDefault(a => a.Id == id); + var at = Database.DocumentTemplates.Include("JobSubTypes").FirstOrDefault(a => a.Id == id); if (at != null) { - at.Delete(dbContext); - dbContext.SaveChanges(); + at.Delete(Database); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Config.DocumentTemplate.Index(null)); else diff --git a/Disco.Web/Areas/API/Controllers/ExpressionsController.cs b/Disco.Web/Areas/API/Controllers/ExpressionsController.cs index 8db63327..975250da 100644 --- a/Disco.Web/Areas/API/Controllers/ExpressionsController.cs +++ b/Disco.Web/Areas/API/Controllers/ExpressionsController.cs @@ -1,12 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class ExpressionsController : dbAdminController + [DiscoAuthorize(Claims.DiscoAdminAccount)] + public partial class ExpressionsController : AuthorizedDatabaseController { public virtual ActionResult ValidateExpression(string Expression) { diff --git a/Disco.Web/Areas/API/Controllers/JobController.cs b/Disco.Web/Areas/API/Controllers/JobController.cs index 1dcc2129..92eb85e3 100644 --- a/Disco.Web/Areas/API/Controllers/JobController.cs +++ b/Disco.Web/Areas/API/Controllers/JobController.cs @@ -1,17 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI.Extensions; -using Disco.Web.Extensions; +using Disco.BI.Extensions; using Disco.Models.Repository; -using Disco.Data.Configuration; +using Disco.Services.Authorization; +using Disco.Services.Users; +using Disco.Services.Web; +using Disco.Web.Extensions; +using System; +using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class JobController : dbAdminController + public partial class JobController : AuthorizedDatabaseController { #region Property Constants @@ -75,8 +76,10 @@ namespace Disco.Web.Areas.API.Controllers if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); - dbContext.Configuration.LazyLoadingEnabled = true; - var job = dbContext.Jobs.Find(id); + var authToken = UserService.CurrentAuthorization; + + Database.Configuration.LazyLoadingEnabled = true; + var job = Database.Jobs.Find(id); object resultData = null; string resultUrlFragment = null; @@ -86,144 +89,180 @@ namespace Disco.Web.Areas.API.Controllers switch (key.ToLower()) { case pExpectedClosedDate: + Authorization.Require(Claims.Job.Properties.ExpectedClosedDate); UpdateExpectedClosedDate(job, value); break; case pDeviceHeldLocation: + Authorization.Require(Claims.Job.Properties.DeviceHeldLocation); UpdateDeviceHeldLocation(job, value); break; case pFlags: + Authorization.Require(Claims.Job.Properties.Flags); UpdateFlags(job, value); resultUrlFragment = pJobDetailsTabFlags; break; case pNonWarrantyAccountingChargeRequired: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeRequired); resultData = UpdateNonWarrantyAccountingChargeRequired(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyAccountingChargeAdded: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeAdded); resultData = UpdateNonWarrantyAccountingChargeAdded(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyAccountingChargePaid: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.AccountingChargePaid); resultData = UpdateNonWarrantyAccountingChargePaid(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyPurchaseOrderRaised: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised); resultData = UpdateNonWarrantyPurchaseOrderRaised(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyPurchaseOrderReference: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderReference); UpdateNonWarrantyPurchaseOrderReference(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyPurchaseOrderSent: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderSent); resultData = UpdateNonWarrantyPurchaseOrderSent(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyInvoiceReceived: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InvoiceReceived); resultData = UpdateNonWarrantyInvoiceReceived(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyFinance; break; case pNonWarrantyRepairerName: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.RepairerName); UpdateNonWarrantyRepairerName(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyRepairs; break; case pNonWarrantyRepairerLoggedDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.RepairerLoggedDate); UpdateNonWarrantyRepairerLoggedDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyRepairs; break; case pNonWarrantyRepairerReference: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.RepairerReference); UpdateNonWarrantyRepairerReference(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyRepairs; break; case pNonWarrantyRepairerCompletedDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate); UpdateNonWarrantyRepairerCompletedDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyRepairs; break; case pNonWarrantyIsInsuranceClaim: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.IsInsuranceClaim); UpdateNonWarrantyIsInsuranceClaim(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceLossOrDamageDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceLossOrDamageDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceEventLocation: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceEventLocation(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceDescription: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceDescription(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceThirdPartyCaused: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceThirdPartyCaused(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceThirdPartyCausedName: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceThirdPartyCausedName(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceThirdPartyCausedWhy: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceThirdPartyCausedWhy(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceWitnessesNamesAddresses: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceWitnessesNamesAddresses(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceBurglaryTheftMethodOfEntry: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceBurglaryTheftMethodOfEntry(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsurancePropertyLastSeenDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsurancePropertyLastSeenDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsurancePoliceNotified: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsurancePoliceNotified(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsurancePoliceNotifiedStation: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsurancePoliceNotifiedStation(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsurancePoliceNotifiedDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsurancePoliceNotifiedDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsurancePoliceNotifiedCrimeReportNo: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsurancePoliceNotifiedCrimeReportNo(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceRecoverReduceAction: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceRecoverReduceAction(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceOtherInterestedParties: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceOtherInterestedParties(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceDateOfPurchase: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails); UpdateInsuranceDateOfPurchase(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pInsuranceClaimFormSentDate: + Authorization.Require(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent); resultData = UpdateInsuranceClaimFormSentDate(job, value); resultUrlFragment = pJobDetailsTabNonWarrantyInsurance; break; case pWarrantyExternalName: + Authorization.Require(Claims.Job.Properties.WarrantyProperties.ExternalName); UpdateWarrantyExternalName(job, value); resultUrlFragment = pJobDetailsTabWarranty; break; case pWarrantyExternalLoggedDate: + Authorization.Require(Claims.Job.Properties.WarrantyProperties.ExternalLoggedDate); UpdateWarrantyExternalLoggedDate(job, value); resultUrlFragment = pJobDetailsTabWarranty; break; case pWarrantyExternalReference: + Authorization.Require(Claims.Job.Properties.WarrantyProperties.ExternalReference); UpdateWarrantyExternalReference(job, value); resultUrlFragment = pJobDetailsTabWarranty; break; case pWarrantyExternalCompletedDate: + Authorization.Require(Claims.Job.Properties.WarrantyProperties.ExternalCompletedDate); UpdateWarrantyExternalCompletedDate(job, value); resultUrlFragment = pJobDetailsTabWarranty; break; @@ -237,7 +276,7 @@ namespace Disco.Web.Areas.API.Controllers } if (redirect.HasValue && redirect.Value) return this.RedirectToAction(MVC.Job.Show(job.Id), resultUrlFragment); - //return RedirectToAction(MVC.Job.Show(job.Id)); + //return RedirectToAction(MVC.Job.Show(job.Id)); else { if (resultData != null) @@ -260,64 +299,79 @@ namespace Disco.Web.Areas.API.Controllers } #region Update Shortcut Methods + [DiscoAuthorize(Claims.Job.Properties.ExpectedClosedDate)] public virtual ActionResult UpdateExpectedClosedDate(int id, string ExpectedClosedDate, Nullable redirect = null) { return Update(id, pExpectedClosedDate, ExpectedClosedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.DeviceHeldLocation)] public virtual ActionResult UpdateDeviceHeldLocation(int id, string DeviceHeldLocation, Nullable redirect = null) { return Update(id, pDeviceHeldLocation, DeviceHeldLocation, redirect); } + [DiscoAuthorize(Claims.Job.Properties.Flags)] public virtual ActionResult UpdateFlags(int id, string Flags, Nullable redirect = null) { return Update(id, pFlags, Flags, redirect); } #region NonWarranty + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeRequired)] public virtual ActionResult UpdateNonWarrantyAccountingChargeRequired(int id, string AccountingChargeRequiredDate, Nullable redirect = null) { return Update(id, pNonWarrantyAccountingChargeRequired, AccountingChargeRequiredDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeAdded)] public virtual ActionResult UpdateNonWarrantyAccountingChargeAdded(int id, string AccountingChargeAddedDate, Nullable redirect = null) { return Update(id, pNonWarrantyAccountingChargeAdded, AccountingChargeAddedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargePaid)] public virtual ActionResult UpdateNonWarrantyAccountingChargePaid(int id, string AccountingChargePaidDate, Nullable redirect = null) { return Update(id, pNonWarrantyAccountingChargePaid, AccountingChargePaidDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised)] public virtual ActionResult UpdateNonWarrantyPurchaseOrderRaised(int id, string PurchaseOrderRaisedDate, Nullable redirect = null) { return Update(id, pNonWarrantyPurchaseOrderRaised, PurchaseOrderRaisedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderReference)] public virtual ActionResult UpdateNonWarrantyPurchaseOrderReference(int id, string PurchaseOrderReference, Nullable redirect = null) { return Update(id, pNonWarrantyPurchaseOrderReference, PurchaseOrderReference, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderSent)] public virtual ActionResult UpdateNonWarrantyPurchaseOrderSent(int id, string PurchaseOrderSentDate, Nullable redirect = null) { return Update(id, pNonWarrantyPurchaseOrderSent, PurchaseOrderSentDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InvoiceReceived)] public virtual ActionResult UpdateNonWarrantyInvoiceReceived(int id, string InvoiceReceivedDate, Nullable redirect = null) { return Update(id, pNonWarrantyInvoiceReceived, InvoiceReceivedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerName)] public virtual ActionResult UpdateNonWarrantyRepairerName(int id, string RepairerName, Nullable redirect = null) { return Update(id, pNonWarrantyRepairerName, RepairerName, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerLoggedDate)] public virtual ActionResult UpdateNonWarrantyRepairerLoggedDate(int id, string RepairerLoggedDate, Nullable redirect = null) { return Update(id, pNonWarrantyRepairerLoggedDate, RepairerLoggedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerReference)] public virtual ActionResult UpdateNonWarrantyRepairerReference(int id, string RepairerReference, Nullable redirect = null) { return Update(id, pNonWarrantyRepairerReference, RepairerReference, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate)] public virtual ActionResult UpdateNonWarrantyRepairerCompletedDate(int id, string RepairerCompletedDate, Nullable redirect = null) { return Update(id, pNonWarrantyRepairerCompletedDate, RepairerCompletedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.IsInsuranceClaim)] public virtual ActionResult UpdateNonWarrantyIsInsuranceClaim(int id, bool IsInsuranceClaim, Nullable redirect = null) { return Update(id, pNonWarrantyIsInsuranceClaim, IsInsuranceClaim.ToString(), redirect); @@ -326,74 +380,92 @@ namespace Disco.Web.Areas.API.Controllers #region Insurance + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceLossOrDamageDate(int id, string LossOrDamageDate, Nullable redirect = null) { return Update(id, pInsuranceLossOrDamageDate, LossOrDamageDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceEventLocation(int id, string EventLocation, Nullable redirect = null) { return Update(id, pInsuranceEventLocation, EventLocation, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceDescription(int id, string Description, Nullable redirect = null) { return Update(id, pInsuranceDescription, Description, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceThirdPartyCaused(int id, string ThirdPartyCaused, Nullable redirect = null) { return Update(id, pInsuranceThirdPartyCaused, ThirdPartyCaused, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceThirdPartyCausedName(int id, string ThirdPartyCausedName, Nullable redirect = null) { return Update(id, pInsuranceThirdPartyCausedName, ThirdPartyCausedName, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceThirdPartyCausedWhy(int id, string ThirdPartyCausedWhy, Nullable redirect = null) { return Update(id, pInsuranceThirdPartyCausedWhy, ThirdPartyCausedWhy, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceWitnessesNamesAddresses(int id, string WitnessesNamesAddresses, Nullable redirect = null) { return Update(id, pInsuranceWitnessesNamesAddresses, WitnessesNamesAddresses, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceBurglaryTheftMethodOfEntry(int id, string BurglaryTheftMethodOfEntry, Nullable redirect = null) { return Update(id, pInsuranceBurglaryTheftMethodOfEntry, BurglaryTheftMethodOfEntry, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsurancePropertyLastSeenDate(int id, string PropertyLastSeenDate, Nullable redirect = null) { return Update(id, pInsurancePropertyLastSeenDate, PropertyLastSeenDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsurancePoliceNotified(int id, string PoliceNotified, Nullable redirect = null) { return Update(id, pInsurancePoliceNotified, PoliceNotified, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsurancePoliceNotifiedStation(int id, string PoliceNotifiedStation, Nullable redirect = null) { return Update(id, pInsurancePoliceNotifiedStation, PoliceNotifiedStation, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsurancePoliceNotifiedDate(int id, string PoliceNotifiedDate, Nullable redirect = null) { return Update(id, pInsurancePoliceNotifiedDate, PoliceNotifiedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsurancePoliceNotifiedCrimeReportNo(int id, string PoliceNotifiedCrimeReportNo, Nullable redirect = null) { return Update(id, pInsurancePoliceNotifiedCrimeReportNo, PoliceNotifiedCrimeReportNo, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceRecoverReduceAction(int id, string RecoverReduceAction, Nullable redirect = null) { return Update(id, pInsuranceRecoverReduceAction, RecoverReduceAction, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceOtherInterestedParties(int id, string OtherInterestedParties, Nullable redirect = null) { return Update(id, pInsuranceOtherInterestedParties, OtherInterestedParties, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)] public virtual ActionResult UpdateInsuranceDateOfPurchase(int id, string DateOfPurchase, Nullable redirect = null) { return Update(id, pInsuranceDateOfPurchase, DateOfPurchase, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent)] public virtual ActionResult UpdateInsuranceClaimFormSentDate(int id, string ClaimFormSentDate, Nullable redirect = null) { return Update(id, pInsuranceClaimFormSentDate, ClaimFormSentDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent)] public virtual ActionResult UpdateInsuranceClaimFormSentUserId(int id, string ClaimFormSentUserId, Nullable redirect = null) { return Update(id, pInsuranceClaimFormSentUserId, ClaimFormSentUserId, redirect); @@ -402,18 +474,22 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Warranty + [DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalName)] public virtual ActionResult UpdateWarrantyExternalName(int id, string ExternalName, Nullable redirect = null) { return Update(id, pWarrantyExternalName, ExternalName, redirect); } + [DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalLoggedDate)] public virtual ActionResult UpdateWarrantyExternalLoggedDate(int id, string ExternalLoggedDate, Nullable redirect = null) { return Update(id, pWarrantyExternalLoggedDate, ExternalLoggedDate, redirect); } + [DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalReference)] public virtual ActionResult UpdateWarrantyExternalReference(int id, string ExternalReference, Nullable redirect = null) { return Update(id, pWarrantyExternalReference, ExternalReference, redirect); } + [DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalCompletedDate)] public virtual ActionResult UpdateWarrantyExternalCompletedDate(int id, string ExternalCompletedDate, Nullable redirect = null) { return Update(id, pWarrantyExternalCompletedDate, ExternalCompletedDate, redirect); @@ -442,7 +518,7 @@ namespace Disco.Web.Areas.API.Controllers { job.ExpectedClosedDate = null; } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateDeviceHeldLocation(Job job, string DeviceHeldLocation) { @@ -451,7 +527,7 @@ namespace Disco.Web.Areas.API.Controllers else job.DeviceHeldLocation = DeviceHeldLocation; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateFlags(Job job, string Flags) { @@ -466,7 +542,7 @@ namespace Disco.Web.Areas.API.Controllers if (!job.Flags.HasValue) { job.Flags = null; - dbContext.SaveChanges(); + Database.SaveChanges(); } } else @@ -494,7 +570,7 @@ namespace Disco.Web.Areas.API.Controllers if (job.Flags.HasValue) { job.Flags = null; - dbContext.SaveChanges(); + Database.SaveChanges(); } } else @@ -502,7 +578,7 @@ namespace Disco.Web.Areas.API.Controllers if (!job.Flags.HasValue || (long)job.Flags.Value != flags) { job.Flags = (Disco.Models.Repository.Job.UserManagementFlags)flags; - dbContext.SaveChanges(); + Database.SaveChanges(); } } } @@ -544,9 +620,9 @@ namespace Disco.Web.Areas.API.Controllers jmi.OtherInterestedParties = job.User.DisplayName; job.JobMetaInsurance = jmi; - dbContext.JobMetaInsurances.Add(jmi); + Database.JobMetaInsurances.Add(jmi); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private Models.Job._DateChangeModel UpdateNonWarrantyAccountingChargeRequired(Job job, string AccountingChargeRequiredDate) @@ -574,13 +650,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.AccountingChargeRequiredUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.AccountingChargeRequiredUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.AccountingChargeRequiredDate); } private Models.Job._DateChangeModel UpdateNonWarrantyAccountingChargeAdded(Job job, string AccountingChargeAddedDate) @@ -608,13 +684,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.AccountingChargeAddedUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.AccountingChargeAddedUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.AccountingChargeAddedDate); } private Models.Job._DateChangeModel UpdateNonWarrantyAccountingChargePaid(Job job, string AccountingChargePaidDate) @@ -642,13 +718,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.AccountingChargePaidUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.AccountingChargePaidUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.AccountingChargePaidDate); } private Models.Job._DateChangeModel UpdateNonWarrantyPurchaseOrderRaised(Job job, string PurchaseOrderRaisedDate) @@ -676,13 +752,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.PurchaseOrderRaisedUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.PurchaseOrderRaisedUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.PurchaseOrderRaisedDate); } private void UpdateNonWarrantyPurchaseOrderReference(Job job, string PurchaseOrderReference) @@ -692,7 +768,7 @@ namespace Disco.Web.Areas.API.Controllers else job.JobMetaNonWarranty.PurchaseOrderReference = PurchaseOrderReference; - dbContext.SaveChanges(); + Database.SaveChanges(); } private Models.Job._DateChangeModel UpdateNonWarrantyPurchaseOrderSent(Job job, string PurchaseOrderSentDate) { @@ -719,13 +795,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.PurchaseOrderSentUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.PurchaseOrderSentUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.PurchaseOrderSentDate); } private Models.Job._DateChangeModel UpdateNonWarrantyInvoiceReceived(Job job, string InvoiceReceivedDate) @@ -753,13 +829,13 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - job.JobMetaNonWarranty.InvoiceReceivedUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaNonWarranty.InvoiceReceivedUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaNonWarranty.InvoiceReceivedDate); } @@ -779,7 +855,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaNonWarranty.RepairerName = RepairerName.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateNonWarrantyRepairerLoggedDate(Job job, string RepairerLoggedDate) { @@ -812,7 +888,7 @@ namespace Disco.Web.Areas.API.Controllers } } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateNonWarrantyRepairerReference(Job job, string RepairerReference) { @@ -830,7 +906,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaNonWarranty.RepairerReference = RepairerReference.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateNonWarrantyRepairerCompletedDate(Job job, string RepairerCompletedDate) { @@ -863,7 +939,7 @@ namespace Disco.Web.Areas.API.Controllers } } } - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion @@ -902,13 +978,13 @@ namespace Disco.Web.Areas.API.Controllers } } } - job.JobMetaInsurance.ClaimFormSentUserId = DiscoApplication.CurrentUser.Id; - dbContext.SaveChanges(); + job.JobMetaInsurance.ClaimFormSentUserId = CurrentUser.Id; + Database.SaveChanges(); return new Models.Job._DateChangeModel() { Id = job.Id, Result = "OK", - UserDescription = DiscoApplication.CurrentUser.ToString() + UserDescription = CurrentUser.ToString() }.SetDateTime(job.JobMetaInsurance.ClaimFormSentDate); } @@ -933,7 +1009,7 @@ namespace Disco.Web.Areas.API.Controllers } job.JobMetaInsurance.DateOfPurchase = dt; } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceOtherInterestedParties(Job job, string OtherInterestedParties) @@ -952,7 +1028,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.OtherInterestedParties = OtherInterestedParties.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceRecoverReduceAction(Job job, string RecoverReduceAction) @@ -971,7 +1047,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.RecoverReduceAction = RecoverReduceAction.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsurancePoliceNotifiedCrimeReportNo(Job job, string PoliceNotifiedCrimeReportNo) @@ -990,7 +1066,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.PoliceNotifiedCrimeReportNo = PoliceNotifiedCrimeReportNo.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsurancePoliceNotifiedDate(Job job, string PoliceNotifiedDate) @@ -1014,7 +1090,7 @@ namespace Disco.Web.Areas.API.Controllers } job.JobMetaInsurance.PoliceNotifiedDate = dt; } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsurancePoliceNotifiedStation(Job job, string PoliceNotifiedStation) @@ -1033,7 +1109,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.PoliceNotifiedStation = PoliceNotifiedStation.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsurancePoliceNotified(Job job, string PoliceNotified) @@ -1051,7 +1127,7 @@ namespace Disco.Web.Areas.API.Controllers } job.JobMetaInsurance.PoliceNotified = b; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsurancePropertyLastSeenDate(Job job, string PropertyLastSeenDate) @@ -1078,7 +1154,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceBurglaryTheftMethodOfEntry(Job job, string BurglaryTheftMethodOfEntry) @@ -1097,7 +1173,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.BurglaryTheftMethodOfEntry = BurglaryTheftMethodOfEntry.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceWitnessesNamesAddresses(Job job, string WitnessesNamesAddresses) @@ -1116,7 +1192,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.WitnessesNamesAddresses = WitnessesNamesAddresses.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceThirdPartyCausedWhy(Job job, string ThirdPartyCausedWhy) @@ -1135,7 +1211,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.ThirdPartyCausedWhy = ThirdPartyCausedWhy.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceThirdPartyCausedName(Job job, string ThirdPartyCausedName) @@ -1154,7 +1230,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.ThirdPartyCausedName = ThirdPartyCausedName.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceThirdPartyCaused(Job job, string ThirdPartyCaused) @@ -1172,7 +1248,7 @@ namespace Disco.Web.Areas.API.Controllers } job.JobMetaInsurance.ThirdPartyCaused = b; - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceDescription(Job job, string Description) @@ -1191,7 +1267,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.Description = Description.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceEventLocation(Job job, string EventLocation) @@ -1210,7 +1286,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaInsurance.EventLocation = EventLocation.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateInsuranceLossOrDamageDate(Job job, string LossOrDamageDate) @@ -1237,7 +1313,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion @@ -1258,7 +1334,7 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaWarranty.ExternalName = ExternalName.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateWarrantyExternalLoggedDate(Job job, string ExternalLoggedDate) @@ -1285,7 +1361,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Date Format"); } } - dbContext.SaveChanges(); + Database.SaveChanges(); } private void UpdateWarrantyExternalReference(Job job, string ExternalReference) @@ -1304,8 +1380,9 @@ namespace Disco.Web.Areas.API.Controllers { job.JobMetaWarranty.ExternalReference = ExternalReference.Trim(); } - dbContext.SaveChanges(); + Database.SaveChanges(); } + private void UpdateWarrantyExternalCompletedDate(Job job, string ExternalCompletedDate) { // Validate Is Warranty Job @@ -1337,13 +1414,15 @@ namespace Disco.Web.Areas.API.Controllers } } } - dbContext.SaveChanges(); + Database.SaveChanges(); } #endregion #endregion #region Job Actions + + [DiscoAuthorize(Claims.Job.Actions.UpdateSubTypes)] public virtual ActionResult UpdateSubTypes(int id, List SubTypes = null, Nullable AddComponents = null, Nullable redirect = null) { try @@ -1357,14 +1436,14 @@ namespace Disco.Web.Areas.API.Controllers if (AddComponents == null) AddComponents = false; - dbContext.Configuration.LazyLoadingEnabled = true; - var job = dbContext.Jobs.Include("JobSubTypes").Where(j => j.Id == id).FirstOrDefault(); + Database.Configuration.LazyLoadingEnabled = true; + var job = Database.Jobs.Include("JobSubTypes").Where(j => j.Id == id).FirstOrDefault(); if (job == null) throw new Exception("Invalid Job Id"); - var subTypes = dbContext.JobSubTypes.Where(jst => SubTypes.Contains(jst.JobTypeId + "_" + jst.Id)).ToList(); - job.UpdateSubTypes(dbContext, subTypes, AddComponents.Value, DiscoApplication.CurrentUser); - dbContext.SaveChanges(); + var subTypes = Database.JobSubTypes.Where(jst => SubTypes.Contains(jst.JobTypeId + "_" + jst.Id)).ToList(); + job.UpdateSubTypes(Database, subTypes, AddComponents.Value, CurrentUser); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Job.Show(job.Id)); else @@ -1378,6 +1457,8 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + + [DiscoAuthorize(Claims.Job.Properties.Flags)] public virtual ActionResult UpdateFlag(int id, long? Flag, string Reason, Nullable redirect = null) { try @@ -1387,7 +1468,7 @@ namespace Disco.Web.Areas.API.Controllers if (!Flag.HasValue || Flag.Value == 0) throw new ArgumentNullException("Flag"); - var job = dbContext.Jobs.Include("JobSubTypes").Where(j => j.Id == id).FirstOrDefault(); + var job = Database.Jobs.Include("JobSubTypes").Where(j => j.Id == id).FirstOrDefault(); if (job == null) throw new Exception("Invalid Job Id"); @@ -1401,7 +1482,7 @@ namespace Disco.Web.Areas.API.Controllers if (flagStatus.Item2) { job.Flags = (Disco.Models.Repository.Job.UserManagementFlags)((long)(job.Flags ?? 0) ^ (flag * -1)); - dbContext.SaveChanges(); + Database.SaveChanges(); } } else @@ -1414,13 +1495,13 @@ namespace Disco.Web.Areas.API.Controllers JobLog jobLog = new JobLog() { JobId = job.Id, - TechUserId = DiscoApplication.CurrentUser.Id, + TechUserId = CurrentUser.Id, Timestamp = DateTime.Now, Comments = string.Format("Added Flag: {0}{1}Reason: {2}", flagStatus.Item1, Environment.NewLine, Reason) }; - dbContext.JobLogs.Add(jobLog); + Database.JobLogs.Add(jobLog); - dbContext.SaveChanges(); + Database.SaveChanges(); } @@ -1442,6 +1523,8 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + + [DiscoAuthorize(Claims.Job.Properties.WaitingForUserAction)] public virtual ActionResult WaitingForUserAction(int id, string Reason, Nullable redirect = null) { try @@ -1449,15 +1532,15 @@ namespace Disco.Web.Areas.API.Controllers if (id < 0) throw new ArgumentOutOfRangeException("id"); - dbContext.Configuration.LazyLoadingEnabled = true; - var job = dbContext.Jobs.Where(j => j.Id == id).FirstOrDefault(); + Database.Configuration.LazyLoadingEnabled = true; + var job = Database.Jobs.Where(j => j.Id == id).FirstOrDefault(); if (job == null) throw new Exception("Invalid Job Id"); if (!job.CanWaitingForUserAction()) throw new InvalidOperationException("Unable to set Waiting For User Action"); - job.OnWaitingForUserAction(dbContext, DiscoApplication.CurrentUser, Reason); - dbContext.SaveChanges(); + job.OnWaitingForUserAction(Database, CurrentUser, Reason); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Job.Show(job.Id)); else @@ -1471,6 +1554,8 @@ namespace Disco.Web.Areas.API.Controllers return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); } } + + [DiscoAuthorize(Claims.Job.Properties.NotWaitingForUserAction)] public virtual ActionResult NotWaitingForUserAction(int id, string Resolution, Nullable redirect = null) { try @@ -1478,15 +1563,15 @@ namespace Disco.Web.Areas.API.Controllers if (id < 0) throw new ArgumentOutOfRangeException("id"); - dbContext.Configuration.LazyLoadingEnabled = true; - var job = dbContext.Jobs.Where(j => j.Id == id).FirstOrDefault(); + Database.Configuration.LazyLoadingEnabled = true; + var job = Database.Jobs.Where(j => j.Id == id).FirstOrDefault(); if (job == null) throw new Exception("Invalid Job Id"); if (!job.CanNotWaitingForUserAction()) throw new InvalidOperationException("Unable to set Waiting For User Action"); - job.OnNotWaitingForUserAction(dbContext, DiscoApplication.CurrentUser, Resolution); - dbContext.SaveChanges(); + job.OnNotWaitingForUserAction(Database, CurrentUser, Resolution); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Job.Show(job.Id)); else @@ -1501,16 +1586,17 @@ namespace Disco.Web.Areas.API.Controllers } } + [DiscoAuthorize(Claims.Job.Actions.LogRepair)] public virtual ActionResult LogRepair(int id, string RepairerName, string RepairerReference, bool? redirect = null) { - var j = dbContext.Jobs.Include("JobMetaNonWarranty").Where(job => job.Id == id).FirstOrDefault(); + var j = Database.Jobs.Include("JobMetaNonWarranty").Where(job => job.Id == id).FirstOrDefault(); if (j != null) { if (j.CanLogRepair()) { j.OnLogRepair(RepairerName, RepairerReference); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Job.Show(id)); @@ -1524,16 +1610,18 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Properties.DeviceReadyForReturn)] public virtual ActionResult DeviceReadyForReturn(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { if (j.CanDeviceReadyForReturn()) { - j.OnDeviceReadyForReturn(DiscoApplication.CurrentUser); + j.OnDeviceReadyForReturn(CurrentUser); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(id)); else @@ -1546,16 +1634,18 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Properties.DeviceHeld)] public virtual ActionResult DeviceHeld(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { if (j.CanDeviceHeld()) { - j.OnDeviceHeld(DiscoApplication.CurrentUser); + j.OnDeviceHeld(CurrentUser); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(id)); else @@ -1568,16 +1658,18 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Properties.DeviceReturned)] public virtual ActionResult DeviceReturned(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { if (j.CanDeviceReturned()) { - j.OnDeviceReturned(DiscoApplication.CurrentUser); + j.OnDeviceReturned(CurrentUser); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(id)); else @@ -1590,17 +1682,19 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Actions.ForceClose)] public virtual ActionResult ForceClose(int id, string Reason, Nullable redirect = null) { - var j = dbContext.Jobs.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var j = Database.Jobs.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (j != null) { if (j.CanForceClose()) { - j.OnForceClose(dbContext, DiscoApplication.CurrentUser, Reason); + j.OnForceClose(Database, CurrentUser, Reason); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect.HasValue && redirect.Value) return RedirectToAction(MVC.Job.Show(id)); else @@ -1613,17 +1707,19 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Actions.Close)] public virtual ActionResult Close(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var j = Database.Jobs.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (j != null) { if (j.CanClose()) { - j.OnClose(DiscoApplication.CurrentUser); + j.OnClose(CurrentUser); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(id)); else @@ -1636,16 +1732,18 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Actions.Reopen)] public virtual ActionResult Reopen(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { if (j.CanReopen()) { j.OnReopen(); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(id)); else @@ -1658,17 +1756,19 @@ namespace Disco.Web.Areas.API.Controllers } return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Actions.Delete)] public virtual ActionResult Delete(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var j = Database.Jobs.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (j != null) { if (j.CanDelete()) { - j.OnDelete(dbContext); + j.OnDelete(Database); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Index()); else @@ -1682,17 +1782,18 @@ namespace Disco.Web.Areas.API.Controllers return Json("Invalid Job Number", JsonRequestBehavior.AllowGet); } + [DiscoAuthorize(Claims.Job.Actions.ConvertHWarToHNWar)] public virtual ActionResult ConvertHWarToHNWar(int id, bool redirect) { - var j = dbContext.Jobs.Find(id); - dbContext.Configuration.LazyLoadingEnabled = true; + var j = Database.Jobs.Find(id); + Database.Configuration.LazyLoadingEnabled = true; if (j != null) { if (j.CanConvertHWarToHNWar()) { - j.OnConvertHWarToHNWar(dbContext); + j.OnConvertHWarToHNWar(Database); - dbContext.SaveChanges(); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Job.Show(j.Id)); else @@ -1709,9 +1810,10 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Job Comments + [DiscoAuthorize(Claims.Job.ShowLogs)] public virtual ActionResult Comments(int id) { - var j = dbContext.Jobs.Include("JobLogs.TechUser").Where(m => m.Id == id).FirstOrDefault(); + var j = Database.Jobs.Include("JobLogs.TechUser").Where(m => m.Id == id).FirstOrDefault(); if (j != null) { var c = new Models.Job.CommentsModel() { Result = "OK" }; @@ -1721,9 +1823,10 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Job.CommentsModel() { Result = "Invalid Job Number" }, JsonRequestBehavior.AllowGet); } + [DiscoAuthorize(Claims.Job.ShowLogs)] public virtual ActionResult Comment(int id) { - var jl = dbContext.JobLogs.Include("TechUser").FirstOrDefault(l => l.Id == id); + var jl = Database.JobLogs.Include("TechUser").FirstOrDefault(l => l.Id == id); if (jl != null) { var c = Models.Job._CommentModel.FromJobLog(jl); @@ -1732,43 +1835,42 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Job.CommentsModel() { Result = "Invalid Comment Id" }, JsonRequestBehavior.AllowGet); } + [DiscoAuthorize(Claims.Job.Actions.AddLogs)] public virtual ActionResult CommentPost(int id, string comment) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { var jl = new Disco.Models.Repository.JobLog() { JobId = j.Id, - TechUserId = DiscoApplication.CurrentUser.Id, + TechUserId = CurrentUser.Id, Timestamp = DateTime.Now, Comments = comment }; - dbContext.JobLogs.Add(jl); - dbContext.SaveChanges(); + Database.JobLogs.Add(jl); + Database.SaveChanges(); - jl = dbContext.JobLogs.Include("TechUser").Where(m => m.Id == jl.Id).FirstOrDefault(); + jl = Database.JobLogs.Include("TechUser").Where(m => m.Id == jl.Id).FirstOrDefault(); return Json(new Models.Job.CommentPostModel() { Result = "OK", Comment = Models.Job._CommentModel.FromJobLog(jl) }, JsonRequestBehavior.AllowGet); } return Json(new Models.Job.CommentPostModel() { Result = "Invalid Job Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyLogs, Claims.Job.Actions.RemoveOwnLogs)] public virtual ActionResult CommentRemove(int id) { - var jl = dbContext.JobLogs.Find(id); + var jl = Database.JobLogs.Find(id); if (jl != null) { - // 2012-02-17 G# Remove - 'Delete Own Comments' policy - // Only Delete Own Comments - //if (jl.TechUserId == DiscoApplication.CurrentUser.Id) - //{ - dbContext.JobLogs.Remove(jl); - dbContext.SaveChanges(); + if (jl.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase)) + Authorization.RequireAny(Claims.Job.Actions.RemoveAnyLogs, Claims.Job.Actions.RemoveOwnLogs); + else + Authorization.Require(Claims.Job.Actions.RemoveAnyLogs); + + Database.JobLogs.Remove(jl); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); - //} - //else - //{ - // return Json("You can only delete your own comments.", JsonRequestBehavior.AllowGet); - //} } // Doesn't Exist/Already Deleted - OK return Json("OK", JsonRequestBehavior.AllowGet); @@ -1777,13 +1879,13 @@ namespace Disco.Web.Areas.API.Controllers #region Job Attachements - [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] + [DiscoAuthorize(Claims.Job.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentDownload(int id) { - var ja = dbContext.JobAttachments.Find(id); + var ja = Database.JobAttachments.Find(id); if (ja != null) { - var filePath = ja.RepositoryFilename(dbContext); + var filePath = ja.RepositoryFilename(Database); if (System.IO.File.Exists(filePath)) { return File(filePath, ja.MimeType, ja.Filename); @@ -1795,13 +1897,14 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } - [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] + + [DiscoAuthorize(Claims.Job.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentThumbnail(int id) { - var ja = dbContext.JobAttachments.Find(id); + var ja = Database.JobAttachments.Find(id); if (ja != null) { - var thumbPath = ja.RepositoryThumbnailFilename(dbContext); + var thumbPath = ja.RepositoryThumbnailFilename(Database); var thumbFileInfo = new FileInfo(thumbPath); if (thumbFileInfo.Exists && thumbFileInfo.Length > 0) { @@ -1815,9 +1918,11 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } + + [DiscoAuthorize(Claims.Job.Actions.AddAttachments)] public virtual ActionResult AttachmentUpload(int id, string Comments) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { if (Request.Files.Count > 0) @@ -1832,18 +1937,18 @@ namespace Disco.Web.Areas.API.Controllers var ja = new Disco.Models.Repository.JobAttachment() { JobId = j.Id, - TechUserId = DiscoApplication.CurrentUser.Id, + TechUserId = CurrentUser.Id, Filename = file.FileName, MimeType = contentType, Timestamp = DateTime.Now, Comments = Comments }; - dbContext.JobAttachments.Add(ja); - dbContext.SaveChanges(); + Database.JobAttachments.Add(ja); + Database.SaveChanges(); - ja.SaveAttachment(dbContext, file.InputStream); + ja.SaveAttachment(Database, file.InputStream); - ja.GenerateThumbnail(dbContext); + ja.GenerateThumbnail(Database); return Json(ja.Id, JsonRequestBehavior.AllowGet); } @@ -1852,9 +1957,11 @@ namespace Disco.Web.Areas.API.Controllers } throw new Exception("Invalid Job Number"); } + + [DiscoAuthorize(Claims.Job.ShowAttachments)] public virtual ActionResult Attachment(int id) { - var ja = dbContext.JobAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var ja = Database.JobAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (ja != null) { @@ -1868,9 +1975,11 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.ShowAttachments)] public virtual ActionResult Attachments(int id) { - var j = dbContext.Jobs.Include("JobAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault(); + var j = Database.Jobs.Include("JobAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault(); if (j != null) { var m = new Models.Attachment.AttachmentsModel() @@ -1883,22 +1992,21 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments)] public virtual ActionResult AttachmentRemove(int id) { - var ja = dbContext.JobAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var ja = Database.JobAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (ja != null) { - // 2012-02-17 G# Remove - 'Delete Own Comments' policy - //if (ja.TechUserId == DiscoApplication.CurrentUser.Id) - //{ - ja.OnDelete(dbContext); - dbContext.SaveChanges(); + if (ja.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase)) + Authorization.RequireAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments); + else + Authorization.Require(Claims.Job.Actions.RemoveAnyAttachments); + + ja.OnDelete(Database); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); - //} - //else - //{ - // return Json("You can only delete your own attachments.", JsonRequestBehavior.AllowGet); - //} } return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet); } @@ -1906,9 +2014,11 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Job Components + + [DiscoAuthorizeAll(Claims.Job.Properties.NonWarrantyProperties.AddComponents, Claims.Job.Properties.NonWarrantyProperties.EditComponents)] public virtual ActionResult ComponentAdd(int id, string Description, string Cost) { - var j = dbContext.Jobs.Find(id); + var j = Database.Jobs.Find(id); if (j != null) { decimal cost = 0; @@ -1923,18 +2033,20 @@ namespace Disco.Web.Areas.API.Controllers JobId = j.Id, Description = Description, Cost = cost, - TechUserId = DiscoApplication.CurrentUser.Id + TechUserId = CurrentUser.Id }; - dbContext.JobComponents.Add(jc); - dbContext.SaveChanges(); + Database.JobComponents.Add(jc); + Database.SaveChanges(); return Json(new Models.Job.ComponentModel { Result = "OK", Component = Models.Job._ComponentModel.FromJobComponent(jc) }, JsonRequestBehavior.AllowGet); } return Json(new Models.Job.ComponentModel { Result = "Invalid Job Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.EditComponents)] public virtual ActionResult ComponentUpdate(int id, string Description, string Cost) { - var jc = dbContext.JobComponents.Find(id); + var jc = Database.JobComponents.Find(id); if (jc != null) { decimal cost = 0; @@ -1947,55 +2059,60 @@ namespace Disco.Web.Areas.API.Controllers jc.Description = Description; jc.Cost = cost; - dbContext.SaveChanges(); + Database.SaveChanges(); return Json(new Models.Job.ComponentModel { Result = "OK", Component = Models.Job._ComponentModel.FromJobComponent(jc) }, JsonRequestBehavior.AllowGet); } return Json(new Models.Job.ComponentModel { Result = "Invalid Job Component Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.EditComponents)] public virtual ActionResult ComponentRemove(int id) { - var jc = dbContext.JobComponents.Find(id); + var jc = Database.JobComponents.Find(id); if (jc != null) { - dbContext.JobComponents.Remove(jc); - dbContext.SaveChanges(); + Database.JobComponents.Remove(jc); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); } return Json("Invalid Job Component Number", JsonRequestBehavior.AllowGet); } + #endregion #region Job Statistics + [DiscoAuthorize(Claims.Job.Show)] public virtual ActionResult StatisticsDailyOpenedClosed() { - var result = BI.JobBI.Statistics.DailyOpenedClosed.Data(dbContext, true); + var result = BI.JobBI.Statistics.DailyOpenedClosed.Data(Database, true); return Json(result, JsonRequestBehavior.AllowGet); } #endregion + [DiscoAuthorize(Claims.Job.Actions.GenerateDocuments)] public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(DocumentTemplateId)) throw new ArgumentNullException("AttachmentTypeId"); - var job = dbContext.Jobs.Find(int.Parse(id)); + var job = Database.Jobs.Find(int.Parse(id)); if (job != null) { - var documentTemplate = dbContext.DocumentTemplates.Find(DocumentTemplateId); + var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId); if (documentTemplate != null) { var timeStamp = DateTime.Now; Stream pdf; using (var generationState = Disco.Models.BI.DocumentTemplates.DocumentState.DefaultState()) { - pdf = documentTemplate.GeneratePdf(dbContext, job, DiscoApplication.CurrentUser, timeStamp, generationState); + pdf = documentTemplate.GeneratePdf(Database, job, CurrentUser, timeStamp, generationState); } - dbContext.SaveChanges(); + Database.SaveChanges(); return File(pdf, "application/pdf", string.Format("{0}_{1}_{2:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, job.Id, timeStamp)); } else @@ -2008,11 +2125,5 @@ namespace Disco.Web.Areas.API.Controllers throw new ArgumentException("Invalid Job Id", "id"); } } - - public virtual ActionResult OrganisationAddress(int id) - { - var address = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(id); - return Json(address, JsonRequestBehavior.AllowGet); - } } } diff --git a/Disco.Web/Areas/API/Controllers/LoggingController.cs b/Disco.Web/Areas/API/Controllers/LoggingController.cs index 302107c9..01d825cc 100644 --- a/Disco.Web/Areas/API/Controllers/LoggingController.cs +++ b/Disco.Web/Areas/API/Controllers/LoggingController.cs @@ -1,22 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI.Extensions; +using Disco.Services.Authorization; using Disco.Services.Logging; using Disco.Services.Tasks; +using Disco.Services.Web; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class LoggingController : dbAdminController + public partial class LoggingController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.Config.Logging.Show)] public virtual ActionResult Modules() { var m = LogContext.LogModules.Values.Select(lm => Models.Logs.LogModuleModel.FromLogModule(lm)).ToList(); return Json(m, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.Config.Logging.Show)] public virtual ActionResult RetrieveEvents(string Format, DateTime? Start = null, DateTime? End = null, int? ModuleId = null, List EventTypeIds = null, int? Take = null) { var logRetriever = new ReadLogContext() @@ -27,7 +30,7 @@ namespace Disco.Web.Areas.API.Controllers EventTypes = EventTypeIds, Take = Take }; - var results = logRetriever.Query(dbContext); + var results = logRetriever.Query(Database); switch (Format.ToLower()) { @@ -46,6 +49,7 @@ namespace Disco.Web.Areas.API.Controllers } } + public virtual ActionResult ScheduledTaskStatus(string id) { if (string.IsNullOrEmpty(id)) diff --git a/Disco.Web/Areas/API/Controllers/PluginController.cs b/Disco.Web/Areas/API/Controllers/PluginController.cs index 858c50df..14c530b8 100644 --- a/Disco.Web/Areas/API/Controllers/PluginController.cs +++ b/Disco.Web/Areas/API/Controllers/PluginController.cs @@ -1,16 +1,18 @@ -using System; -using System.Collections.Generic; +using Disco.Services.Authorization; +using Disco.Services.Plugins; +using Disco.Services.Plugins.CommunityInterop; +using Disco.Services.Web; +using System; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; -using Disco.Services.Plugins; -using Disco.Services.Plugins.CommunityInterop; namespace Disco.Web.Areas.API.Controllers { - public partial class PluginController : dbAdminController + public partial class PluginController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.Config.Plugin.Install)] public virtual ActionResult UpdateLibraryCatalogue() { var status = PluginLibraryUpdateTask.ScheduleNow(); @@ -20,6 +22,7 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Config.Plugin.Install)] public virtual ActionResult UpdateAll() { var status = UpdatePluginTask.UpdateAllPlugins(); @@ -27,6 +30,7 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Config.Plugin.Install)] public virtual ActionResult Update(string PluginId) { if (string.IsNullOrEmpty(PluginId)) @@ -37,6 +41,7 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal)] public virtual ActionResult UpdateLocal(string PluginId, HttpPostedFileBase Plugin) { if (string.IsNullOrEmpty(PluginId)) @@ -45,10 +50,10 @@ namespace Disco.Web.Areas.API.Controllers if (Plugin == null || Plugin.ContentLength <= 0 || string.IsNullOrWhiteSpace(Plugin.FileName)) throw new ArgumentException("A discoPlugin file must be uploaded", "Plugin"); - var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName)); + var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName)); - if (!Directory.Exists(dbContext.DiscoConfiguration.PluginPackagesLocation)) - Directory.CreateDirectory(dbContext.DiscoConfiguration.PluginPackagesLocation); + if (!Directory.Exists(Database.DiscoConfiguration.PluginPackagesLocation)) + Directory.CreateDirectory(Database.DiscoConfiguration.PluginPackagesLocation); if (System.IO.File.Exists(tempPluginLocation)) System.IO.File.Delete(tempPluginLocation); @@ -60,6 +65,7 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Config.Plugin.Uninstall)] public virtual ActionResult Uninstall(string id, bool UninstallData) { if (string.IsNullOrEmpty(id)) @@ -72,12 +78,13 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorize(Claims.Config.Plugin.Install)] public virtual ActionResult Install(string PluginId) { if (string.IsNullOrEmpty(PluginId)) throw new ArgumentNullException("PluginId", "A PluginId must be supplied"); - var catalogue = Plugins.LoadCatalogue(dbContext); + var catalogue = Plugins.LoadCatalogue(Database); var plugin = catalogue.Plugins.FirstOrDefault(p => p.Id.Equals(PluginId)); if (plugin == null) @@ -87,22 +94,23 @@ namespace Disco.Web.Areas.API.Controllers if (Plugins.PluginInstalled(plugin.Id)) throw new InvalidOperationException("This plugin is already installed"); - var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, string.Format("{0}.discoPlugin", plugin.Id)); + var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, string.Format("{0}.discoPlugin", plugin.Id)); var status = InstallPluginTask.InstallPlugin(plugin.LatestDownloadUrl, tempPluginLocation, true); return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId)); } + [DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal)] public virtual ActionResult InstallLocal(HttpPostedFileBase Plugin) { if (Plugin == null || Plugin.ContentLength <= 0 || string.IsNullOrWhiteSpace(Plugin.FileName)) throw new ArgumentException("A discoPlugin file must be uploaded", "Plugin"); - var tempPluginLocation = Path.Combine(dbContext.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName)); + var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, Path.GetFileName(Plugin.FileName)); - if (!Directory.Exists(dbContext.DiscoConfiguration.PluginPackagesLocation)) - Directory.CreateDirectory(dbContext.DiscoConfiguration.PluginPackagesLocation); + if (!Directory.Exists(Database.DiscoConfiguration.PluginPackagesLocation)) + Directory.CreateDirectory(Database.DiscoConfiguration.PluginPackagesLocation); if (System.IO.File.Exists(tempPluginLocation)) System.IO.File.Delete(tempPluginLocation); diff --git a/Disco.Web/Areas/API/Controllers/SystemController.cs b/Disco.Web/Areas/API/Controllers/SystemController.cs index e8409d45..adf40523 100644 --- a/Disco.Web/Areas/API/Controllers/SystemController.cs +++ b/Disco.Web/Areas/API/Controllers/SystemController.cs @@ -1,22 +1,20 @@ -using System; -using System.Collections.Generic; +using Disco.BI.Extensions; +using Disco.BI.Interop.ActiveDirectory; +using Disco.Services.Authorization; +using Disco.Services.Web; +using System; +using System.Drawing; +using System.IO; using System.Linq; +using System.Text; using System.Web; using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using System.IO; -using System.Drawing; -using System.Text; -using Disco.Services.Tasks; -using Disco.BI.Interop.ActiveDirectory; -using Disco.Models.Repository; namespace Disco.Web.Areas.API.Controllers { - public partial class SystemController : dbAdminController + public partial class SystemController : AuthorizedDatabaseController { - + [DiscoAuthorize(Claims.Config.System.Show)] public virtual ActionResult UpdateLastNetworkLogonDates() { var taskStatus = ActiveDirectoryUpdateLastNetworkLogonDateJob.ScheduleImmediately(); @@ -24,44 +22,46 @@ namespace Disco.Web.Areas.API.Controllers return RedirectToAction(MVC.Config.Logging.TaskStatus(taskStatus.SessionId)); } + [DiscoAuthorize(Claims.DiscoAdminAccount)] public virtual ActionResult UpdateAttachmentThumbnails() { // Device Attachments - var das = dbContext.DeviceAttachments.Where(da => da.MimeType == "application/pdf"); + var das = Database.DeviceAttachments.Where(da => da.MimeType == "application/pdf"); foreach (var da in das) { - var fileName = da.RepositoryThumbnailFilename(dbContext); + var fileName = da.RepositoryThumbnailFilename(Database); if (!System.IO.File.Exists(fileName)) { - da.GenerateThumbnail(dbContext); + da.GenerateThumbnail(Database); } } // User Attachments - var uas = dbContext.UserAttachments.Where(ua => ua.MimeType == "application/pdf"); + var uas = Database.UserAttachments.Where(ua => ua.MimeType == "application/pdf"); foreach (var ua in uas) { - var fileName = ua.RepositoryThumbnailFilename(dbContext); + var fileName = ua.RepositoryThumbnailFilename(Database); if (!System.IO.File.Exists(fileName)) { - ua.GenerateThumbnail(dbContext); + ua.GenerateThumbnail(Database); } } // Job Attachments - var jas = dbContext.JobAttachments.Where(ja => ja.MimeType == "application/pdf"); + var jas = Database.JobAttachments.Where(ja => ja.MimeType == "application/pdf"); foreach (var ja in jas) { - var fileName = ja.RepositoryThumbnailFilename(dbContext); + var fileName = ja.RepositoryThumbnailFilename(Database); if (!System.IO.File.Exists(fileName)) { - ja.GenerateThumbnail(dbContext); + ja.GenerateThumbnail(Database); } } return Content("Done", "text/text"); } + [DiscoAuthorize(Claims.Config.System.Show)] public virtual ActionResult UpdateCheck() { var ts = Disco.BI.Interop.Community.UpdateCheckTask.ScheduleNow(); @@ -72,16 +72,17 @@ namespace Disco.Web.Areas.API.Controllers #region Organisation #region Organisation Name + [DiscoAuthorize(Claims.Config.Organisation.ConfigureName)] public virtual ActionResult UpdateOrganisationName(string OrganisationName, bool redirect = false) { if (string.IsNullOrWhiteSpace(OrganisationName)) - dbContext.DiscoConfiguration.OrganisationName = null; + Database.DiscoConfiguration.OrganisationName = null; else - dbContext.DiscoConfiguration.OrganisationName = OrganisationName; + Database.DiscoConfiguration.OrganisationName = OrganisationName; - dbContext.SaveChanges(); + Database.SaveChanges(); - DiscoApplication.OrganisationName = dbContext.DiscoConfiguration.OrganisationName; + DiscoApplication.OrganisationName = Database.DiscoConfiguration.OrganisationName; if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); @@ -99,7 +100,7 @@ namespace Disco.Web.Areas.API.Controllers if (Height < 1) throw new ArgumentOutOfRangeException("Height"); - using (Stream logoStream = dbContext.DiscoConfiguration.OrganisationLogo) + using (Stream logoStream = Database.DiscoConfiguration.OrganisationLogo) { using (Image logoBitmap = Bitmap.FromStream(logoStream)) { @@ -107,12 +108,12 @@ namespace Disco.Web.Areas.API.Controllers } } } - [HttpPost] + [DiscoAuthorize(Claims.Config.Organisation.ConfigureLogo), HttpPost] public virtual ActionResult OrganisationLogo(bool redirect, HttpPostedFileBase Image, bool? ResetLogo = null) { if (ResetLogo.HasValue && ResetLogo.Value) { - dbContext.DiscoConfiguration.OrganisationLogo = null; + Database.DiscoConfiguration.OrganisationLogo = null; if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); @@ -124,7 +125,7 @@ namespace Disco.Web.Areas.API.Controllers { if (Image.ContentType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) { - dbContext.DiscoConfiguration.OrganisationLogo = Image.InputStream; + Database.DiscoConfiguration.OrganisationLogo = Image.InputStream; if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); @@ -147,7 +148,7 @@ namespace Disco.Web.Areas.API.Controllers #endregion #region Organisation Addresses - + [DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)] public virtual ActionResult UpdateOrganisationAddress(Disco.Models.BI.Config.OrganisationAddress organisationAddress, bool redirect = false) { if (organisationAddress == null) @@ -156,8 +157,8 @@ namespace Disco.Web.Areas.API.Controllers } if (ModelState.IsValid) { - dbContext.DiscoConfiguration.OrganisationAddresses.SetAddress(organisationAddress); - dbContext.SaveChanges(); + Database.DiscoConfiguration.OrganisationAddresses.SetAddress(organisationAddress); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); else @@ -183,10 +184,11 @@ namespace Disco.Web.Areas.API.Controllers return Json(em.ToString(), JsonRequestBehavior.AllowGet); } } + [DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)] public virtual ActionResult DeleteOrganisationAddress(int Id, bool redirect = false) { - dbContext.DiscoConfiguration.OrganisationAddresses.RemoveAddress(Id); - dbContext.SaveChanges(); + Database.DiscoConfiguration.OrganisationAddresses.RemoveAddress(Id); + Database.SaveChanges(); if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); @@ -198,13 +200,14 @@ namespace Disco.Web.Areas.API.Controllers #region MultiSiteMode + [DiscoAuthorize(Claims.Config.Organisation.ConfigureMultiSiteMode)] public virtual ActionResult UpdateMultiSiteMode(bool MultiSiteMode, bool redirect = false) { - dbContext.DiscoConfiguration.MultiSiteMode = MultiSiteMode; + Database.DiscoConfiguration.MultiSiteMode = MultiSiteMode; - dbContext.SaveChanges(); + Database.SaveChanges(); - DiscoApplication.MultiSiteMode = dbContext.DiscoConfiguration.MultiSiteMode; + DiscoApplication.MultiSiteMode = Database.DiscoConfiguration.MultiSiteMode; if (redirect) return RedirectToAction(MVC.Config.Organisation.Index()); diff --git a/Disco.Web/Areas/API/Controllers/UserController.cs b/Disco.Web/Areas/API/Controllers/UserController.cs index 53ab3f14..7f14beb2 100644 --- a/Disco.Web/Areas/API/Controllers/UserController.cs +++ b/Disco.Web/Areas/API/Controllers/UserController.cs @@ -1,29 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; +using Disco.BI.Extensions; +using Disco.Services.Authorization; +using Disco.Services.Users; +using Disco.Services.Web; +using System; using System.IO; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.API.Controllers { - public partial class UserController : dbAdminController + public partial class UserController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.User.Search)] public virtual ActionResult UpstreamUsers(string term) { return Json(BI.UserBI.Searching.SearchUpstream(term), JsonRequestBehavior.AllowGet); } #region User Attachements + + [DiscoAuthorize(Claims.User.ShowAttachments)] [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentDownload(int id) { - var ua = dbContext.UserAttachments.Find(id); + var ua = Database.UserAttachments.Find(id); if (ua != null) { - var filePath = ua.RepositoryFilename(dbContext); + var filePath = ua.RepositoryFilename(Database); if (System.IO.File.Exists(filePath)) { return File(filePath, ua.MimeType, ua.Filename); @@ -35,13 +38,15 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } + + [DiscoAuthorize(Claims.User.ShowAttachments)] [OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)] public virtual ActionResult AttachmentThumbnail(int id) { - var ua = dbContext.UserAttachments.Find(id); + var ua = Database.UserAttachments.Find(id); if (ua != null) { - var thumbPath = ua.RepositoryThumbnailFilename(dbContext); + var thumbPath = ua.RepositoryThumbnailFilename(Database); if (System.IO.File.Exists(thumbPath)) { if (thumbPath.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) @@ -54,9 +59,11 @@ namespace Disco.Web.Areas.API.Controllers } return HttpNotFound("Invalid Attachment Number"); } + + [DiscoAuthorize(Claims.User.Actions.AddAttachments)] public virtual ActionResult AttachmentUpload(string id, string Comments) { - var u = dbContext.Users.Find(id); + var u = Database.Users.Find(id); if (u != null) { if (Request.Files.Count > 0) @@ -71,18 +78,18 @@ namespace Disco.Web.Areas.API.Controllers var ua = new Disco.Models.Repository.UserAttachment() { UserId = u.Id, - TechUserId = DiscoApplication.CurrentUser.Id, + TechUserId = UserService.CurrentUserId, Filename = file.FileName, MimeType = contentType, Timestamp = DateTime.Now, Comments = Comments }; - dbContext.UserAttachments.Add(ua); - dbContext.SaveChanges(); + Database.UserAttachments.Add(ua); + Database.SaveChanges(); - ua.SaveAttachment(dbContext, file.InputStream); + ua.SaveAttachment(Database, file.InputStream); - ua.GenerateThumbnail(dbContext); + ua.GenerateThumbnail(Database); return Json(ua.Id, JsonRequestBehavior.AllowGet); } @@ -91,9 +98,11 @@ namespace Disco.Web.Areas.API.Controllers } throw new Exception("Invalid User Id"); } + + [DiscoAuthorize(Claims.User.ShowAttachments)] public virtual ActionResult Attachment(int id) { - var ua = dbContext.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var ua = Database.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (ua != null) { @@ -107,9 +116,11 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorize(Claims.User.ShowAttachments)] public virtual ActionResult Attachments(string id) { - var u = dbContext.Users.Include("UserAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault(); + var u = Database.Users.Include("UserAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault(); if (u != null) { var m = new Models.Attachment.AttachmentsModel() @@ -122,47 +133,47 @@ namespace Disco.Web.Areas.API.Controllers } return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid User Id" }, JsonRequestBehavior.AllowGet); } + + [DiscoAuthorizeAny(Claims.User.Actions.RemoveAnyAttachments, Claims.User.Actions.RemoveOwnAttachments)] public virtual ActionResult AttachmentRemove(int id) { - var ua = dbContext.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); + var ua = Database.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault(); if (ua != null) { - // 2012-02-17 G# Remove - 'Delete Own Comments' policy - //if (ua.TechUserId == DiscoApplication.CurrentUser.Id) - //{ - ua.OnDelete(dbContext); - dbContext.SaveChanges(); + if (ua.TechUserId.Equals(CurrentUser.Id, StringComparison.InvariantCultureIgnoreCase)) + Authorization.RequireAny(Claims.User.Actions.RemoveAnyAttachments, Claims.User.Actions.RemoveOwnAttachments); + else + Authorization.Require(Claims.User.Actions.RemoveAnyAttachments); + + ua.OnDelete(Database); + Database.SaveChanges(); return Json("OK", JsonRequestBehavior.AllowGet); - //} - //else - //{ - // return Json("You can only delete your own attachments.", JsonRequestBehavior.AllowGet); - //} } return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet); } #endregion + [DiscoAuthorize(Claims.User.Actions.GenerateDocuments)] public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); if (string.IsNullOrEmpty(DocumentTemplateId)) throw new ArgumentNullException("AttachmentTypeId"); - var user = dbContext.Users.Find(id); + var user = Database.Users.Find(id); if (user != null) { - var documentTemplate = dbContext.DocumentTemplates.Find(DocumentTemplateId); + var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId); if (documentTemplate != null) { var timeStamp = DateTime.Now; Stream pdf; using (var generationState = Disco.Models.BI.DocumentTemplates.DocumentState.DefaultState()) { - pdf = documentTemplate.GeneratePdf(dbContext, user, DiscoApplication.CurrentUser, timeStamp, generationState); + pdf = documentTemplate.GeneratePdf(Database, user, UserService.CurrentUser, timeStamp, generationState); } - dbContext.SaveChanges(); + Database.SaveChanges(); return File(pdf, "application/pdf", string.Format("{0}_{1}_{2:yyyyMMdd-HHmmss}.pdf", documentTemplate.Id, user.Id, timeStamp)); } else diff --git a/Disco.Web/Areas/API/Models/Attachment/_AttachmentModel.cs b/Disco.Web/Areas/API/Models/Attachment/_AttachmentModel.cs index 00991741..8f315faf 100644 --- a/Disco.Web/Areas/API/Models/Attachment/_AttachmentModel.cs +++ b/Disco.Web/Areas/API/Models/Attachment/_AttachmentModel.cs @@ -12,6 +12,7 @@ namespace Disco.Web.Areas.API.Models.Attachment public string ParentId { get; set; } public int Id { get; set; } public string Author { get; set; } + public string AuthorId { get; set; } public DateTime Timestamp { get; set; } public string Comments { get; set; } public string Filename { get; set; } @@ -45,6 +46,7 @@ namespace Disco.Web.Areas.API.Models.Attachment { ParentId = ua.UserId, Id = ua.Id, + AuthorId = ua.TechUserId, Author = ua.TechUser.ToString(), Timestamp = ua.Timestamp, Comments = ua.Comments, @@ -58,6 +60,7 @@ namespace Disco.Web.Areas.API.Models.Attachment { ParentId = ja.JobId.ToString(), Id = ja.Id, + AuthorId = ja.TechUserId, Author = ja.TechUser.ToString(), Timestamp = ja.Timestamp, Comments = ja.Comments, @@ -71,6 +74,7 @@ namespace Disco.Web.Areas.API.Models.Attachment { ParentId = da.DeviceSerialNumber, Id = da.Id, + AuthorId = da.TechUserId, Author = da.TechUser.ToString(), Timestamp = da.Timestamp, Comments = da.Comments, diff --git a/Disco.Web/Areas/API/Models/AuthorizationRole/SubjectItem.cs b/Disco.Web/Areas/API/Models/AuthorizationRole/SubjectItem.cs new file mode 100644 index 00000000..f22f5728 --- /dev/null +++ b/Disco.Web/Areas/API/Models/AuthorizationRole/SubjectItem.cs @@ -0,0 +1,25 @@ +using Disco.Models.Interop.ActiveDirectory; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace Disco.Web.Areas.API.Models.AuthorizationRole +{ + public class SubjectItem + { + public string Id { get; set; } + public string Name { get; set; } + public string Type { get; set; } + + public static SubjectItem FromActiveDirectoryObject(IActiveDirectoryObject ADObject) + { + return new Models.AuthorizationRole.SubjectItem() + { + Id = ADObject.SamAccountName, + Name = ADObject.Name, + Type = ADObject is ActiveDirectoryGroup ? "group" : "user" + }; + } + } +} \ No newline at end of file diff --git a/Disco.Web/Areas/API/Models/Job/_CommentModel.cs b/Disco.Web/Areas/API/Models/Job/_CommentModel.cs index 25fb3590..880f8c0c 100644 --- a/Disco.Web/Areas/API/Models/Job/_CommentModel.cs +++ b/Disco.Web/Areas/API/Models/Job/_CommentModel.cs @@ -11,6 +11,7 @@ namespace Disco.Web.Areas.API.Models.Job { public int Id { get; set; } public int JobId { get; set; } + public string AuthorId { get; set; } public string Author { get; set; } public DateTime Timestamp { get; set; } public string Comments { get; set; } @@ -43,6 +44,7 @@ namespace Disco.Web.Areas.API.Models.Job { Id = jl.Id, JobId = jl.JobId, + AuthorId = jl.TechUserId, Author = jl.TechUser.ToString(), Timestamp = jl.Timestamp, Comments = jl.Comments diff --git a/Disco.Web/Areas/Config/ConfigAreaRegistration.cs b/Disco.Web/Areas/Config/ConfigAreaRegistration.cs index e9d0537a..c5a4ddd9 100644 --- a/Disco.Web/Areas/Config/ConfigAreaRegistration.cs +++ b/Disco.Web/Areas/Config/ConfigAreaRegistration.cs @@ -94,11 +94,15 @@ namespace Disco.Web.Areas.Config "Config/DocumentTemplate/{id}", new { controller = "DocumentTemplate", action = "Index", id = UrlParameter.Optional } ); - context.MapRoute( - "Config_Warranty", - "Config/Warranty/{id}", - new { controller = "Warranty", action = "Index", id = UrlParameter.Optional } + "Config_AuthorizationRole_Create", + "Config/AuthorizationRole/Create", + new { controller = "AuthorizationRole", action = "Create", id = UrlParameter.Optional } + ); + context.MapRoute( + "Config_AuthorizationRole", + "Config/AuthorizationRole/{id}", + new { controller = "AuthorizationRole", action = "Index", id = UrlParameter.Optional } ); context.MapRoute( diff --git a/Disco.Web/Areas/Config/Controllers/AuthorizationRoleController.cs b/Disco.Web/Areas/Config/Controllers/AuthorizationRoleController.cs new file mode 100644 index 00000000..a02d0580 --- /dev/null +++ b/Disco.Web/Areas/Config/Controllers/AuthorizationRoleController.cs @@ -0,0 +1,105 @@ +using Disco.Models.Authorization; +using Disco.Models.UI.Config.AuthorizationRole; +using Disco.Services.Authorization; +using Disco.Services.Authorization.Roles; +using Disco.Services.Plugins.Features.UIExtension; +using Disco.Services.Users; +using Disco.Services.Web; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Mvc; + +namespace Disco.Web.Areas.Config.Controllers +{ + [DiscoAuthorize(Claims.DiscoAdminAccount)] + public partial class AuthorizationRoleController : AuthorizedDatabaseController + { + public virtual ActionResult Index(int? id) + { + if (id.HasValue) + { + // Show + var ar = Database.AuthorizationRoles.Find(id.Value); + + if (ar == null) + throw new ArgumentException("Invalid Authorization Role Id"); + + var token = RoleToken.FromAuthorizationRole(ar); + var subjects = token.SubjectIds == null ? new List() : + token.SubjectIds.Select(subjectId => Disco.BI.Interop.ActiveDirectory.ActiveDirectory.GetObject(subjectId)) + .Where(item => item != null) + .Select(item => Models.AuthorizationRole.ShowModel.SubjectDescriptor.FromActiveDirectoryObject(item)) + .OrderBy(item => item.Name).ToList(); + + var m = new Models.AuthorizationRole.ShowModel() + { + Token = token, + Subjects = subjects, + ClaimNavigator = Claims.RoleClaimNavigator.BuildClaimTree(token.Claims) + }; + + + // UI Extensions + UIExtensions.ExecuteExtensions(this.ControllerContext, m); + + return View(MVC.Config.AuthorizationRole.Views.Show, m); + } + else + { + // List Index + var ars = Database.AuthorizationRoles.ToList() + .Select(ar => RoleToken.FromAuthorizationRole(ar)).Cast().ToList(); + + var m = new Models.AuthorizationRole.IndexModel() + { + Tokens = ars + }; + + // UI Extensions + UIExtensions.ExecuteExtensions(this.ControllerContext, m); + + return View(m); + } + } + + public virtual ActionResult Create() + { + // Default Role + var m = new Models.AuthorizationRole.CreateModel() + { + AuthorizationRole = new Disco.Models.Repository.AuthorizationRole() + }; + + // UI Extensions + UIExtensions.ExecuteExtensions(this.ControllerContext, m); + + return View(m); + } + + [HttpPost] + public virtual ActionResult Create(Models.AuthorizationRole.CreateModel model) + { + if (ModelState.IsValid) + { + // Check for Existing + var existing = Database.AuthorizationRoles.Where(m => m.Name == model.AuthorizationRole.Name).FirstOrDefault(); + if (existing == null) + { + var roleId = UserService.CreateAuthorizationRole(Database, model.AuthorizationRole); + + return RedirectToAction(MVC.Config.AuthorizationRole.Index(roleId)); + } + else + { + ModelState.AddModelError("Name", "Am Authorization Role with this name already exists."); + } + } + + // UI Extensions + UIExtensions.ExecuteExtensions(this.ControllerContext, model); + + return View(model); + } + } +} diff --git a/Disco.Web/Areas/Config/Controllers/ConfigController.cs b/Disco.Web/Areas/Config/Controllers/ConfigController.cs index 5a92c4db..48d9493c 100644 --- a/Disco.Web/Areas/Config/Controllers/ConfigController.cs +++ b/Disco.Web/Areas/Config/Controllers/ConfigController.cs @@ -1,22 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class ConfigController : dbAdminController + public partial class ConfigController : AuthorizedDatabaseController { // // GET: /Config/Config/ + [DiscoAuthorize(Claims.Config.Show)] public virtual ActionResult Index() { var m = new Models.Config.IndexModel() { - UpdateResponse = dbContext.DiscoConfiguration.UpdateLastCheck + UpdateResponse = Database.DiscoConfiguration.UpdateLastCheck }; return View(m); diff --git a/Disco.Web/Areas/Config/Controllers/DeviceBatchController.cs b/Disco.Web/Areas/Config/Controllers/DeviceBatchController.cs index dfbf0ad5..be765620 100644 --- a/Disco.Web/Areas/Config/Controllers/DeviceBatchController.cs +++ b/Disco.Web/Areas/Config/Controllers/DeviceBatchController.cs @@ -1,26 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Web.Extensions; -using Disco.Services.Plugins.Features.UIExtension; +using Disco.BI.Extensions; using Disco.Models.UI.Config.DeviceBatch; +using Disco.Services.Authorization; +using Disco.Services.Plugins.Features.UIExtension; +using Disco.Services.Web; +using System; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class DeviceBatchController : dbAdminController + public partial class DeviceBatchController : AuthorizedDatabaseController { - + [DiscoAuthorize(Claims.Config.DeviceBatch.Show)] public virtual ActionResult Index(int? id) { - dbContext.Configuration.LazyLoadingEnabled = true; + Database.Configuration.LazyLoadingEnabled = true; if (id.HasValue) { - var m = dbContext.DeviceBatches.Where(db => db.Id == id.Value) + var m = Database.DeviceBatches.Where(db => db.Id == id.Value) .Select(db => new Models.DeviceBatch.ShowModel() { DeviceBatch = db, @@ -38,9 +36,18 @@ namespace Disco.Web.Areas.Config.Controllers DeviceDecommissionedCount = dG.Count(d => d.DecommissionedDate.HasValue) }).ToArray().Cast().ToList(); - m.CanDelete = m.DeviceBatch.CanDelete(dbContext); + if (Authorization.Has(Claims.Config.DeviceBatch.Delete)) + m.CanDelete = m.DeviceBatch.CanDelete(Database); - m.DeviceModels = dbContext.DeviceModels.ToList(); + if (Authorization.Has(Claims.Config.DeviceBatch.Configure)) + { + m.DeviceModels = Database.DeviceModels.ToList(); + m.DefaultDeviceModel = m.DeviceBatch.DefaultDeviceModelId.HasValue ? m.DeviceModels.FirstOrDefault(dm => dm.Id == m.DeviceBatch.DefaultDeviceModelId.Value) : null; + } + else + { + m.DefaultDeviceModel = m.DeviceBatch.DefaultDeviceModelId.HasValue ? Database.DeviceModels.Find(m.DeviceBatch.DefaultDeviceModelId.Value) : null; + } // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -49,7 +56,7 @@ namespace Disco.Web.Areas.Config.Controllers } else { - var m = Models.DeviceBatch.IndexModel.Build(dbContext); + var m = Models.DeviceBatch.IndexModel.Build(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -58,12 +65,13 @@ namespace Disco.Web.Areas.Config.Controllers } } + [DiscoAuthorizeAll(Claims.Config.DeviceBatch.Create, Claims.Config.DeviceBatch.Configure)] public virtual ActionResult Create() { // Default Batch var m = new Models.DeviceBatch.CreateModel() { - DeviceBatch = BI.DeviceBI.BatchUtilities.DefaultNewDeviceBatch(dbContext) + DeviceBatch = BI.DeviceBI.BatchUtilities.DefaultNewDeviceBatch(Database) }; // UI Extensions @@ -72,17 +80,17 @@ namespace Disco.Web.Areas.Config.Controllers return View(m); } - [HttpPost] + [DiscoAuthorizeAll(Claims.Config.DeviceBatch.Create, Claims.Config.DeviceBatch.Configure), HttpPost] public virtual ActionResult Create(Models.DeviceBatch.CreateModel model) { if (ModelState.IsValid) { // Check for Existing - var existing = dbContext.DeviceBatches.Where(m => m.Name == model.DeviceBatch.Name).FirstOrDefault(); + var existing = Database.DeviceBatches.Where(m => m.Name == model.DeviceBatch.Name).FirstOrDefault(); if (existing == null) { - dbContext.DeviceBatches.Add(model.DeviceBatch); - dbContext.SaveChanges(); + Database.DeviceBatches.Add(model.DeviceBatch); + Database.SaveChanges(); return RedirectToAction(MVC.Config.DeviceBatch.Index(model.DeviceBatch.Id)); } else @@ -97,6 +105,7 @@ namespace Disco.Web.Areas.Config.Controllers return View(model); } + [DiscoAuthorize(Claims.Config.DeviceBatch.ShowTimeline)] public virtual ActionResult Timeline() { var m = new Models.DeviceBatch.TimelineModel(); diff --git a/Disco.Web/Areas/Config/Controllers/DeviceModelController.cs b/Disco.Web/Areas/Config/Controllers/DeviceModelController.cs index 35755da4..c113d315 100644 --- a/Disco.Web/Areas/Config/Controllers/DeviceModelController.cs +++ b/Disco.Web/Areas/Config/Controllers/DeviceModelController.cs @@ -1,23 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.Services.Plugins.Features.WarrantyProvider; -using Disco.Services.Plugins; -using Disco.BI.Extensions; -using Disco.Services.Plugins.Features.UIExtension; +using Disco.BI.Extensions; using Disco.Models.UI.Config.DeviceModel; +using Disco.Services.Authorization; +using Disco.Services.Plugins; +using Disco.Services.Plugins.Features.UIExtension; +using Disco.Services.Plugins.Features.WarrantyProvider; +using Disco.Services.Web; +using System; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class DeviceModelController : dbAdminController + public partial class DeviceModelController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.Config.DeviceModel.Show)] public virtual ActionResult Index(int? id) { if (id.HasValue) { - var m = dbContext.DeviceModels.Include("DeviceComponents").Where(dm => dm.Id == id.Value).Select(dm => new Models.DeviceModel.ShowModel() + var m = Database.DeviceModels.Include("DeviceComponents").Where(dm => dm.Id == id.Value).Select(dm => new Models.DeviceModel.ShowModel() { DeviceModel = dm, DeviceCount = dm.Devices.Count(), @@ -32,16 +33,11 @@ namespace Disco.Web.Areas.Config.Controllers m.DeviceComponentsModel = new Models.DeviceModel.ComponentsModel() { DeviceModelId = m.DeviceModel.Id, - DeviceComponents = dbContext.DeviceComponents.Include("JobSubTypes").Where(dc => dc.DeviceModelId == m.DeviceModel.Id).ToList(), - JobSubTypes = dbContext.JobSubTypes.Where(jst => jst.JobTypeId == Disco.Models.Repository.JobType.JobTypeIds.HNWar).ToList() + DeviceComponents = Database.DeviceComponents.Include("JobSubTypes").Where(dc => dc.DeviceModelId == m.DeviceModel.Id).ToList(), + JobSubTypes = Database.JobSubTypes.Where(jst => jst.JobTypeId == Disco.Models.Repository.JobType.JobTypeIds.HNWar).ToList() }; - m.CanDelete = m.DeviceModel.CanDelete(dbContext); - - //m.Devices = BI.DeviceBI.SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceModelId == m.DeviceModel.Id)); - - //m.Devices = dbContext.Devices.Include("DeviceModel").Include("DeviceProfile").Include("AssignedUser") - // .Where(d => d.DeviceModelId == m.DeviceModel.Id).ToList(); + m.CanDelete = m.DeviceModel.CanDelete(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -50,7 +46,7 @@ namespace Disco.Web.Areas.Config.Controllers } else { - var m = Models.DeviceModel.IndexModel.Build(dbContext); + var m = Models.DeviceModel.IndexModel.Build(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -59,12 +55,13 @@ namespace Disco.Web.Areas.Config.Controllers } } + [DiscoAuthorize(Claims.Config.DeviceModel.Show)] public virtual ActionResult GenericComponents() { var m = new Models.DeviceModel.ComponentsModel() { - DeviceComponents = dbContext.DeviceComponents.Include("JobSubTypes").Where(dc => !dc.DeviceModelId.HasValue).ToList(), - JobSubTypes = dbContext.JobSubTypes.Where(jst => jst.JobTypeId == Disco.Models.Repository.JobType.JobTypeIds.HNWar).ToList() + DeviceComponents = Database.DeviceComponents.Include("JobSubTypes").Where(dc => !dc.DeviceModelId.HasValue).ToList(), + JobSubTypes = Database.JobSubTypes.Where(jst => jst.JobTypeId == Disco.Models.Repository.JobType.JobTypeIds.HNWar).ToList() }; // UI Extensions diff --git a/Disco.Web/Areas/Config/Controllers/DeviceProfileController.cs b/Disco.Web/Areas/Config/Controllers/DeviceProfileController.cs index d856f5ce..cd5dda61 100644 --- a/Disco.Web/Areas/Config/Controllers/DeviceProfileController.cs +++ b/Disco.Web/Areas/Config/Controllers/DeviceProfileController.cs @@ -1,26 +1,26 @@ -using System; +using Disco.BI.Extensions; +using Disco.Models.Repository; +using Disco.Models.UI.Config.DeviceProfile; +using Disco.Services.Authorization; +using Disco.Services.Plugins; +using Disco.Services.Plugins.Features.CertificateProvider; +using Disco.Services.Plugins.Features.UIExtension; +using Disco.Services.Web; +using System; using System.Collections.Generic; using System.Linq; -using System.Web; using System.Web.Mvc; -using Disco.Data.Configuration; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Services.Plugins.Features.CertificateProvider; -using Disco.Services.Plugins; -using Disco.Services.Plugins.Features.UIExtension; -using Disco.Models.UI.Config.DeviceProfile; -using Disco.Models.Repository; namespace Disco.Web.Areas.Config.Controllers { - public partial class DeviceProfileController : dbAdminController + public partial class DeviceProfileController : AuthorizedDatabaseController { + [DiscoAuthorize(Claims.Config.DeviceProfile.Show)] public virtual ActionResult Index(int? id) { if (id.HasValue) { - var m = dbContext.DeviceProfiles.Where(dp => dp.Id == id.Value).Select(dp => new Models.DeviceProfile.ShowModel() + var m = Database.DeviceProfiles.Where(dp => dp.Id == id.Value).Select(dp => new Models.DeviceProfile.ShowModel() { DeviceProfile = dp, DeviceCount = dp.Devices.Count(), @@ -30,7 +30,11 @@ namespace Disco.Web.Areas.Config.Controllers if (m == null || m.DeviceProfile == null) throw new ArgumentException("Invalid Device Profile Id", "id"); - m.OrganisationAddresses = dbContext.DiscoConfiguration.OrganisationAddresses.Addresses; + m.OrganisationAddresses = Database.DiscoConfiguration.OrganisationAddresses.Addresses; + + if (m.DeviceProfile.DefaultOrganisationAddress.HasValue) + m.DefaultOrganisationAddress = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(m.DeviceProfile.DefaultOrganisationAddress.Value); + m.CertificateProviders = Plugins.GetPluginFeatures(typeof(CertificateProviderFeature)); var DistributionValues = Enum.GetValues(typeof(Disco.Models.Repository.DeviceProfile.DistributionTypes)); @@ -44,13 +48,7 @@ namespace Disco.Web.Areas.Config.Controllers Selected = ((int)m.DeviceProfile.DistributionType == value) }); } - m.CanDelete = m.DeviceProfile.CanDelete(dbContext); - - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //var config = m.DeviceProfile.Configuration(dbContext); - //m.AllocateWirelessCertificate = m.DeviceProfile.AllocateWirelessCertificate; - //m.OrganisationalUnit = m.DeviceProfile.OrganisationalUnit; - //m.ComputerNameTemplate = m.DeviceProfile.ComputerNameTemplate; + m.CanDelete = m.DeviceProfile.CanDelete(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -59,7 +57,7 @@ namespace Disco.Web.Areas.Config.Controllers } else { - var m = Models.DeviceProfile.IndexModel.Build(dbContext); + var m = Models.DeviceProfile.IndexModel.Build(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -68,6 +66,7 @@ namespace Disco.Web.Areas.Config.Controllers } } + [DiscoAuthorizeAll(Claims.Config.DeviceProfile.Create, Claims.Config.DeviceProfile.Configure)] public virtual ActionResult Create() { var m = new Models.DeviceProfile.CreateModel() @@ -86,19 +85,19 @@ namespace Disco.Web.Areas.Config.Controllers return View(m); } - [HttpPost] + [DiscoAuthorizeAll(Claims.Config.DeviceProfile.Create, Claims.Config.DeviceProfile.Configure), HttpPost] public virtual ActionResult Create(Models.DeviceProfile.CreateModel model) { if (ModelState.IsValid) { // Check for Existing - var existing = dbContext.DeviceProfiles.Where(m => m.Name == model.DeviceProfile.Name).FirstOrDefault(); + var existing = Database.DeviceProfiles.Where(m => m.Name == model.DeviceProfile.Name).FirstOrDefault(); if (existing == null) { model.DeviceProfile.ProvisionADAccount = true; - dbContext.DeviceProfiles.Add(model.DeviceProfile); - dbContext.SaveChanges(); + Database.DeviceProfiles.Add(model.DeviceProfile); + Database.SaveChanges(); return RedirectToAction(MVC.Config.DeviceProfile.Index(model.DeviceProfile.Id)); } else @@ -113,13 +112,14 @@ namespace Disco.Web.Areas.Config.Controllers return View(model); } + [DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)] public virtual ActionResult Defaults() { var m = new Models.DeviceProfile.DefaultsModel() { - DeviceProfiles = dbContext.DeviceProfiles.ToList(), - Default = dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId, - DefaultAddDeviceOffline = dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId + DeviceProfiles = Database.DeviceProfiles.ToList(), + Default = Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId, + DefaultAddDeviceOffline = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId }; m.DeviceProfilesAndNone = m.DeviceProfiles.ToList(); m.DeviceProfilesAndNone.Insert(0, new Disco.Models.Repository.DeviceProfile() { Id = 0, Name = "" }); diff --git a/Disco.Web/Areas/Config/Controllers/DocumentTemplateController.cs b/Disco.Web/Areas/Config/Controllers/DocumentTemplateController.cs index 7a48194b..d408ff4c 100644 --- a/Disco.Web/Areas/Config/Controllers/DocumentTemplateController.cs +++ b/Disco.Web/Areas/Config/Controllers/DocumentTemplateController.cs @@ -1,23 +1,23 @@ -using System; +using Disco.BI.Extensions; +using Disco.Models.UI.Config.DocumentTemplate; +using Disco.Services.Authorization; +using Disco.Services.Plugins.Features.UIExtension; +using Disco.Services.Web; +using System; using System.Collections.Generic; using System.Linq; -using System.Web; using System.Web.Mvc; -using Disco.BI; -using Disco.BI.Extensions; -using Disco.Services.Plugins.Features.UIExtension; -using Disco.Models.UI.Config.DocumentTemplate; namespace Disco.Web.Areas.Config.Controllers { - public partial class DocumentTemplateController : dbAdminController + public partial class DocumentTemplateController : AuthorizedDatabaseController { - + [DiscoAuthorize(Claims.Config.DocumentTemplate.Show)] public virtual ActionResult Index(string id) { if (string.IsNullOrEmpty(id)) { - var m = new Models.DocumentTemplate.IndexModel() { DocumentTemplates = dbContext.DocumentTemplates.ToList() }; + var m = new Models.DocumentTemplate.IndexModel() { DocumentTemplates = Database.DocumentTemplates.ToList() }; // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -28,10 +28,10 @@ namespace Disco.Web.Areas.Config.Controllers { var m = new Models.DocumentTemplate.ShowModel() { - DocumentTemplate = dbContext.DocumentTemplates.Include("JobSubTypes").Where(at => at.Id == id).FirstOrDefault() + DocumentTemplate = Database.DocumentTemplates.Include("JobSubTypes").Where(at => at.Id == id).FirstOrDefault() }; - m.TemplateExpressions = m.DocumentTemplate.ExtractPdfExpressions(dbContext); - m.UpdateModel(dbContext); + m.TemplateExpressions = m.DocumentTemplate.ExtractPdfExpressions(Database); + m.UpdateModel(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -40,6 +40,7 @@ namespace Disco.Web.Areas.Config.Controllers } } + [DiscoAuthorize(Claims.Config.DocumentTemplate.ShowStatus)] public virtual ActionResult ImportStatus() { var m = new Models.DocumentTemplate.ImportStatusModel(); @@ -49,11 +50,13 @@ namespace Disco.Web.Areas.Config.Controllers return View(); } + + [DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)] public virtual ActionResult UndetectedPages() { var m = new Models.DocumentTemplate.UndetectedPagesModel() { - DocumentTemplates = dbContext.DocumentTemplates.ToList() + DocumentTemplates = Database.DocumentTemplates.ToList() }; // UI Extensions @@ -62,10 +65,11 @@ namespace Disco.Web.Areas.Config.Controllers return View(m); } + [DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Create, Claims.Config.DocumentTemplate.Configure)] public virtual ActionResult Create() { var m = new Models.DocumentTemplate.CreateModel(); - m.UpdateModel(dbContext); + m.UpdateModel(Database); // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, m); @@ -73,19 +77,19 @@ namespace Disco.Web.Areas.Config.Controllers return View(m); } - [HttpPost] + [DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Create, Claims.Config.DocumentTemplate.Configure), HttpPost] public virtual ActionResult Create(Models.DocumentTemplate.CreateModel model) { - model.UpdateModel(dbContext); + model.UpdateModel(Database); if (ModelState.IsValid) { // Check for Existing - var existing = dbContext.DocumentTemplates.Where(m => m.Id == model.DocumentTemplate.Id).FirstOrDefault(); + var existing = Database.DocumentTemplates.Where(m => m.Id == model.DocumentTemplate.Id).FirstOrDefault(); if (existing == null) { - dbContext.DocumentTemplates.Add(model.DocumentTemplate); + Database.DocumentTemplates.Add(model.DocumentTemplate); if (model.DocumentTemplate.Scope == Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Job) { @@ -96,10 +100,10 @@ namespace Disco.Web.Areas.Config.Controllers // model.AttachmentType.JobSubTypes.Add(jobSubType); } - dbContext.SaveChanges(); + Database.SaveChanges(); // Save Template - model.DocumentTemplate.SavePdfTemplate(dbContext, model.Template.InputStream); + model.DocumentTemplate.SavePdfTemplate(Database, model.Template.InputStream); return RedirectToAction(MVC.Config.DocumentTemplate.Index(model.DocumentTemplate.Id)); } @@ -115,6 +119,7 @@ namespace Disco.Web.Areas.Config.Controllers return View(model); } + [DiscoAuthorize(Claims.Config.Show)] public virtual ActionResult ExpressionBrowser(string type, bool StaticDeclaredMembersOnly = false) { if (string.IsNullOrWhiteSpace(type)) diff --git a/Disco.Web/Areas/Config/Controllers/EnrolmentController.cs b/Disco.Web/Areas/Config/Controllers/EnrolmentController.cs index 84ebffe1..e9607d1b 100644 --- a/Disco.Web/Areas/Config/Controllers/EnrolmentController.cs +++ b/Disco.Web/Areas/Config/Controllers/EnrolmentController.cs @@ -1,23 +1,19 @@ using Disco.Models.UI.Config.Enrolment; +using Disco.Services.Authorization; using Disco.Services.Plugins.Features.UIExtension; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Web; using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class EnrolmentController : dbAdminController + public partial class EnrolmentController : AuthorizedDatabaseController { - // - // GET: /Config/Bootstrapper/ - + [DiscoAuthorize(Claims.Config.Enrolment.Show)] public virtual ActionResult Index() { var m = new Models.Enrolment.IndexModel() { - MacSshUsername = dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername + MacSshUsername = Database.DiscoConfiguration.Bootstrapper.MacSshUsername }; // UI Extensions @@ -25,6 +21,8 @@ namespace Disco.Web.Areas.Config.Controllers return View(m); } + + [DiscoAuthorize(Claims.Config.Enrolment.ShowStatus)] public virtual ActionResult Status() { var m = new Models.Enrolment.StatusModel(); diff --git a/Disco.Web/Areas/Config/Controllers/ExpressionsController.cs b/Disco.Web/Areas/Config/Controllers/ExpressionsController.cs index 75d7e40e..5fb3cd13 100644 --- a/Disco.Web/Areas/Config/Controllers/ExpressionsController.cs +++ b/Disco.Web/Areas/Config/Controllers/ExpressionsController.cs @@ -1,22 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; +using System; using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class ExpressionsController : Controller + [DiscoAuthorize(Claims.DiscoAdminAccount)] + public partial class ExpressionsController : AuthorizedDatabaseController { - // - // GET: /Config/Expressions/ + // Under Construction - Not In Production public virtual ActionResult Index() { - return View(Views.Editor, new Models.Expressions.EditorModel() - { - Expression = @"JobComponentsTotalCost() < 100 ? JobComponentsTotalCost().ToString('c') : '$100.00'" - }); + throw new NotImplementedException(); + + //return View(Views.Editor, new Models.Expressions.EditorModel() + //{ + // Expression = @"JobComponentsTotalCost() < 100 ? JobComponentsTotalCost().ToString('c') : '$100.00'" + //}); } } diff --git a/Disco.Web/Areas/Config/Controllers/LoggingController.cs b/Disco.Web/Areas/Config/Controllers/LoggingController.cs index 4f17a52b..d0887e31 100644 --- a/Disco.Web/Areas/Config/Controllers/LoggingController.cs +++ b/Disco.Web/Areas/Config/Controllers/LoggingController.cs @@ -1,20 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; +using Disco.Models.UI.Config.Logging; +using Disco.Services.Authorization; using Disco.Services.Logging; using Disco.Services.Logging.Models; using Disco.Services.Plugins.Features.UIExtension; -using Disco.Models.UI.Config.Logging; +using Disco.Services.Web; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class LoggingController : dbAdminController + public partial class LoggingController : AuthorizedDatabaseController { // // GET: /Config/Logs/ - + [DiscoAuthorize(Claims.Config.Logging.Show)] public virtual ActionResult Index() { var m = new Models.Logging.IndexModel() diff --git a/Disco.Web/Areas/Config/Controllers/OrganisationController.cs b/Disco.Web/Areas/Config/Controllers/OrganisationController.cs index ee758b1b..e109ce47 100644 --- a/Disco.Web/Areas/Config/Controllers/OrganisationController.cs +++ b/Disco.Web/Areas/Config/Controllers/OrganisationController.cs @@ -1,25 +1,24 @@ using Disco.Models.UI.Config.Organisation; +using Disco.Services.Authorization; using Disco.Services.Plugins.Features.UIExtension; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Web; using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class OrganisationController : dbAdminController + public partial class OrganisationController : AuthorizedDatabaseController { // // GET: /Config/Organisation/ + [DiscoAuthorize(Claims.Config.Organisation.Show)] public virtual ActionResult Index() { var viewModel = new Models.Organisation.IndexModel(); - viewModel.OrganisationName = dbContext.DiscoConfiguration.OrganisationName; - viewModel.MultiSiteMode = dbContext.DiscoConfiguration.MultiSiteMode; - viewModel.OrganisationAddresses = dbContext.DiscoConfiguration.OrganisationAddresses.Addresses; + viewModel.OrganisationName = Database.DiscoConfiguration.OrganisationName; + viewModel.MultiSiteMode = Database.DiscoConfiguration.MultiSiteMode; + viewModel.OrganisationAddresses = Database.DiscoConfiguration.OrganisationAddresses.Addresses; // UI Extensions UIExtensions.ExecuteExtensions(this.ControllerContext, viewModel); diff --git a/Disco.Web/Areas/Config/Controllers/PluginsController.cs b/Disco.Web/Areas/Config/Controllers/PluginsController.cs index bb8bab4e..ace52205 100644 --- a/Disco.Web/Areas/Config/Controllers/PluginsController.cs +++ b/Disco.Web/Areas/Config/Controllers/PluginsController.cs @@ -1,30 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Disco.Models.BI.Interop.Community; +using Disco.Services.Authorization; using Disco.Services.Plugins; -using Disco.Services.Tasks; +using Disco.Services.Users; +using Disco.Services.Web; using Disco.Web.Areas.Config.Models.Plugins; +using System; +using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class PluginsController : dbAdminController + public partial class PluginsController : AuthorizedDatabaseController { - [HttpGet] + [DiscoAuthorize(Claims.Config.Plugin.Show), HttpGet] public virtual ActionResult Index() { Models.Plugins.IndexViewModel vm = new Models.Plugins.IndexViewModel() { PluginManifests = Plugins.GetPlugins(), - Catalogue = Plugins.LoadCatalogue(dbContext) + Catalogue = Plugins.LoadCatalogue(Database) }; return View(vm); } #region Plugin Configuration - [HttpPost] + [DiscoAuthorize(Claims.Config.Plugin.Configure), HttpPost] public virtual ActionResult Configure(string PluginId, FormCollection form) { if (string.IsNullOrEmpty(PluginId)) @@ -34,24 +32,24 @@ namespace Disco.Web.Areas.Config.Controllers using (PluginConfigurationHandler configHandler = manifest.CreateConfigurationHandler()) { - if (configHandler.Post(dbContext, form, this)) + if (configHandler.Post(Database, form, this)) { - dbContext.SaveChanges(); + Database.SaveChanges(); - PluginsLog.LogPluginConfigurationSaved(manifest.Id, DiscoApplication.CurrentUser.Id); + PluginsLog.LogPluginConfigurationSaved(manifest.Id, UserService.CurrentUserId); return RedirectToAction(MVC.Config.Plugins.Index()); } else { // Config Errors - PluginConfigurationViewModel vm = new PluginConfigurationViewModel(configHandler.Get(dbContext, this)); + PluginConfigurationViewModel vm = new PluginConfigurationViewModel(configHandler.Get(Database, this)); return View(Views.Configure, vm); } } } - [HttpGet] + [DiscoAuthorize(Claims.Config.Plugin.Configure), HttpGet] public virtual ActionResult Configure(string PluginId) { if (string.IsNullOrEmpty(PluginId)) @@ -61,18 +59,18 @@ namespace Disco.Web.Areas.Config.Controllers using (PluginConfigurationHandler configHandler = manifest.CreateConfigurationHandler()) { - PluginConfigurationViewModel vm = new PluginConfigurationViewModel(configHandler.Get(dbContext, this)); - PluginsLog.LogPluginConfigurationLoaded(manifest.Id, DiscoApplication.CurrentUser.Id); + PluginConfigurationViewModel vm = new PluginConfigurationViewModel(configHandler.Get(Database, this)); + PluginsLog.LogPluginConfigurationLoaded(manifest.Id, UserService.CurrentUserId); return View(Views.Configure, vm); } } #endregion + [DiscoAuthorize(Claims.Config.Plugin.Install)] public virtual ActionResult Install() { // Check for recent catalogue - - var catalogue = Plugins.LoadCatalogue(dbContext); + var catalogue = Plugins.LoadCatalogue(Database); if (catalogue == null || catalogue.ResponseTimestamp < DateTime.Now.AddHours(-1)) { diff --git a/Disco.Web/Areas/Config/Controllers/SystemConfigController.cs b/Disco.Web/Areas/Config/Controllers/SystemConfigController.cs index fa4f908f..d245fb63 100644 --- a/Disco.Web/Areas/Config/Controllers/SystemConfigController.cs +++ b/Disco.Web/Areas/Config/Controllers/SystemConfigController.cs @@ -1,25 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Disco.Services.Authorization; +using Disco.Services.Web; using System.Web.Mvc; namespace Disco.Web.Areas.Config.Controllers { - public partial class SystemConfigController : dbAdminController + public partial class SystemConfigController : AuthorizedDatabaseController { - [HttpGet] + [DiscoAuthorize(Claims.Config.System.Show), HttpGet] public virtual ActionResult Index() { - var m = Models.SystemConfig.IndexModel.FromConfiguration(dbContext.DiscoConfiguration); + var m = Models.SystemConfig.IndexModel.FromConfiguration(Database.DiscoConfiguration); return View(m); } - [HttpPost] + + [DiscoAuthorizeAll(Claims.Config.System.Show, Claims.Config.System.ConfigureProxy), HttpPost] public virtual ActionResult Index(Models.SystemConfig.IndexModel config) { if (ModelState.IsValid) { - config.ToConfiguration(dbContext); + config.ToConfiguration(Database); return RedirectToAction(MVC.Config.Config.Index()); } else diff --git a/Disco.Web/Areas/Config/Models/AuthorizationRole/CreateModel.cs b/Disco.Web/Areas/Config/Models/AuthorizationRole/CreateModel.cs new file mode 100644 index 00000000..b42d645a --- /dev/null +++ b/Disco.Web/Areas/Config/Models/AuthorizationRole/CreateModel.cs @@ -0,0 +1,13 @@ +using Disco.Models.UI.Config.AuthorizationRole; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace Disco.Web.Areas.Config.Models.AuthorizationRole +{ + public class CreateModel : ConfigAuthorizationRoleCreateModel + { + public Disco.Models.Repository.AuthorizationRole AuthorizationRole { get; set; } + } +} \ No newline at end of file diff --git a/Disco.Web/Areas/Config/Models/AuthorizationRole/IndexModel.cs b/Disco.Web/Areas/Config/Models/AuthorizationRole/IndexModel.cs new file mode 100644 index 00000000..e427dc0d --- /dev/null +++ b/Disco.Web/Areas/Config/Models/AuthorizationRole/IndexModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using Disco.Data.Repository; +using Disco.Models.UI.Config.AuthorizationRole; +using Disco.Models.Authorization; + +namespace Disco.Web.Areas.Config.Models.AuthorizationRole +{ + public class IndexModel : ConfigAuthorizationRoleIndexModel + { + public List Tokens { get; set; } + } +} \ No newline at end of file diff --git a/Disco.Web/Areas/Config/Models/AuthorizationRole/ShowModel.cs b/Disco.Web/Areas/Config/Models/AuthorizationRole/ShowModel.cs new file mode 100644 index 00000000..b963fa1f --- /dev/null +++ b/Disco.Web/Areas/Config/Models/AuthorizationRole/ShowModel.cs @@ -0,0 +1,54 @@ +using Disco.Models.Authorization; +using Disco.Models.Interop.ActiveDirectory; +using Disco.Models.UI.Config.AuthorizationRole; +using Disco.Web.Models.Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace Disco.Web.Areas.Config.Models.AuthorizationRole +{ + public class ShowModel : ConfigAuthorizationRoleShowModel + { + public IRoleToken Token { get; set; } + + public List Subjects { get; set; } + + public IClaimNavigatorItem ClaimNavigator { get; set; } + + public FancyTreeNode[] ClaimNavigatorFancyTreeNodes + { + get + { + var rootNode = FancyTreeNode.FromClaimNavigatorItem(this.ClaimNavigator, false); + rootNode.expanded = true; + + return new FancyTreeNode[] { + rootNode + }; + } + } + + public class SubjectDescriptor + { + public bool IsGroup { get; set; } + public string Name { get; set; } + public string Id { get; set; } + + public static SubjectDescriptor FromActiveDirectoryObject(IActiveDirectoryObject ADObject) + { + var item = new SubjectDescriptor() + { + Id = ADObject.SamAccountName, + Name = ADObject.Name + }; + + if (ADObject is ActiveDirectoryGroup) + item.IsGroup = true; + + return item; + } + } + } +} \ No newline at end of file diff --git a/Disco.Web/Areas/Config/Models/DeviceBatch/IndexModel.cs b/Disco.Web/Areas/Config/Models/DeviceBatch/IndexModel.cs index 49d2147d..5f3af37f 100644 --- a/Disco.Web/Areas/Config/Models/DeviceBatch/IndexModel.cs +++ b/Disco.Web/Areas/Config/Models/DeviceBatch/IndexModel.cs @@ -11,10 +11,10 @@ namespace Disco.Web.Areas.Config.Models.DeviceBatch { public List DeviceBatches { get; set; } - public static IndexModel Build(DiscoDataContext dbContext) + public static IndexModel Build(DiscoDataContext Database) { var m = new IndexModel(); - m.DeviceBatches = dbContext.DeviceBatches.OrderBy(db => db.Name).Select(db => new _IndexModelItem() + m.DeviceBatches = Database.DeviceBatches.OrderBy(db => db.Name).Select(db => new _IndexModelItem() { Id = db.Id, Name = db.Name, @@ -28,6 +28,9 @@ namespace Disco.Web.Areas.Config.Models.DeviceBatch InsuredUntil = db.InsuredUntil }).ToArray().Cast().ToList(); + foreach (var item in m.DeviceBatches.Where(db => db.DefaultDeviceModel == null)) + item.DefaultDeviceModel = ""; + return m; } diff --git a/Disco.Web/Areas/Config/Models/DeviceBatch/ShowModel.cs b/Disco.Web/Areas/Config/Models/DeviceBatch/ShowModel.cs index 7d7aa083..13db03f2 100644 --- a/Disco.Web/Areas/Config/Models/DeviceBatch/ShowModel.cs +++ b/Disco.Web/Areas/Config/Models/DeviceBatch/ShowModel.cs @@ -10,6 +10,7 @@ namespace Disco.Web.Areas.Config.Models.DeviceBatch public class ShowModel : ConfigDeviceBatchShowModel { public Disco.Models.Repository.DeviceBatch DeviceBatch { get; set; } + public Disco.Models.Repository.DeviceModel DefaultDeviceModel { get; set; } public List DeviceModels { get; set; } public List DeviceModelMembers { get; set; } public int DeviceCount { get; set; } diff --git a/Disco.Web/Areas/Config/Models/DeviceModel/IndexModel.cs b/Disco.Web/Areas/Config/Models/DeviceModel/IndexModel.cs index 5bad732d..51c3fa6f 100644 --- a/Disco.Web/Areas/Config/Models/DeviceModel/IndexModel.cs +++ b/Disco.Web/Areas/Config/Models/DeviceModel/IndexModel.cs @@ -11,10 +11,10 @@ namespace Disco.Web.Areas.Config.Models.DeviceModel { public List DeviceModels { get; set; } - public static IndexModel Build(DiscoDataContext dbContext) + public static IndexModel Build(DiscoDataContext Database) { var m = new IndexModel(); - m.DeviceModels = dbContext.DeviceModels.OrderBy(dm => dm.Description).Select(dm => new _IndexModelItem() + m.DeviceModels = Database.DeviceModels.OrderBy(dm => dm.Description).Select(dm => new _IndexModelItem() { Id = dm.Id, Name = dm.Description, diff --git a/Disco.Web/Areas/Config/Models/DeviceProfile/IndexModel.cs b/Disco.Web/Areas/Config/Models/DeviceProfile/IndexModel.cs index e000e5f0..6293c1a5 100644 --- a/Disco.Web/Areas/Config/Models/DeviceProfile/IndexModel.cs +++ b/Disco.Web/Areas/Config/Models/DeviceProfile/IndexModel.cs @@ -12,10 +12,10 @@ namespace Disco.Web.Areas.Config.Models.DeviceProfile { public List DeviceProfiles { get; set; } - public static IndexModel Build(DiscoDataContext dbContext) + public static IndexModel Build(DiscoDataContext Database) { var m = new IndexModel(); - m.DeviceProfiles = dbContext.DeviceProfiles.OrderBy(dp => dp.Name).Select(dp => new _IndexModelItem() + m.DeviceProfiles = Database.DeviceProfiles.OrderBy(dp => dp.Name).Select(dp => new _IndexModelItem() { Id = dp.Id, Name = dp.Name, @@ -31,7 +31,7 @@ namespace Disco.Web.Areas.Config.Models.DeviceProfile { foreach (var dp in m.DeviceProfiles) if (dp.Address.HasValue) - dp.AddressName = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(dp.Address.Value).Name; + dp.AddressName = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(dp.Address.Value).Name; } return m; diff --git a/Disco.Web/Areas/Config/Models/DeviceProfile/ShowModel.cs b/Disco.Web/Areas/Config/Models/DeviceProfile/ShowModel.cs index 962471fd..c4fe28c8 100644 --- a/Disco.Web/Areas/Config/Models/DeviceProfile/ShowModel.cs +++ b/Disco.Web/Areas/Config/Models/DeviceProfile/ShowModel.cs @@ -12,6 +12,7 @@ namespace Disco.Web.Areas.Config.Models.DeviceProfile { public Disco.Models.Repository.DeviceProfile DeviceProfile { get; set; } public List DeviceProfileDistributionTypes { get; set; } + public Disco.Models.BI.Config.OrganisationAddress DefaultOrganisationAddress { get; set; } public List OrganisationAddresses { get; set; } public List CertificateProviders { get; set; } diff --git a/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs b/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs index b2bc7279..c08fe793 100644 --- a/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs +++ b/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs @@ -55,12 +55,12 @@ namespace Disco.Web.Areas.Config.Models.DocumentTemplate } } - public void UpdateModel(DiscoDataContext dbContext) + public void UpdateModel(DiscoDataContext Database) { if (this.JobTypes == null) - JobTypes = dbContext.JobTypes.ToList(); + JobTypes = Database.JobTypes.ToList(); if (this.JobSubTypes == null) - JobSubTypes = dbContext.JobSubTypes.ToList(); + JobSubTypes = Database.JobSubTypes.ToList(); } } diff --git a/Disco.Web/Areas/Config/Models/DocumentTemplate/ShowModel.cs b/Disco.Web/Areas/Config/Models/DocumentTemplate/ShowModel.cs index 91f57d18..b7790831 100644 --- a/Disco.Web/Areas/Config/Models/DocumentTemplate/ShowModel.cs +++ b/Disco.Web/Areas/Config/Models/DocumentTemplate/ShowModel.cs @@ -36,26 +36,26 @@ namespace Disco.Web.Areas.Config.Models.DocumentTemplate } } - public void UpdateModel(DiscoDataContext dbContext) + public void UpdateModel(DiscoDataContext Database) { switch (this.DocumentTemplate.Scope) { case Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device: - this.StoredInstanceCount = dbContext.DeviceAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); + this.StoredInstanceCount = Database.DeviceAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); break; case Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.Job: - this.StoredInstanceCount = dbContext.JobAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); + this.StoredInstanceCount = Database.JobAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); break; case Disco.Models.Repository.DocumentTemplate.DocumentTemplateScopes.User: - this.StoredInstanceCount = dbContext.UserAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); + this.StoredInstanceCount = Database.UserAttachments.Count(a => a.DocumentTemplateId == this.DocumentTemplate.Id); break; } if (this.JobTypes == null) - JobTypes = dbContext.JobTypes.ToList(); + JobTypes = Database.JobTypes.ToList(); if (this.JobSubTypes == null) - JobSubTypes = dbContext.JobSubTypes.ToList(); + JobSubTypes = Database.JobSubTypes.ToList(); if (DocumentTemplate != null) { diff --git a/Disco.Web/Areas/Config/Models/SystemConfig/IndexModel.cs b/Disco.Web/Areas/Config/Models/SystemConfig/IndexModel.cs index a7def612..7a522f0a 100644 --- a/Disco.Web/Areas/Config/Models/SystemConfig/IndexModel.cs +++ b/Disco.Web/Areas/Config/Models/SystemConfig/IndexModel.cs @@ -102,9 +102,9 @@ namespace Disco.Web.Areas.Config.Models.SystemConfig }; } - public void ToConfiguration(DiscoDataContext db) + public void ToConfiguration(DiscoDataContext Database) { - SystemConfiguration config = db.DiscoConfiguration; + SystemConfiguration config = Database.DiscoConfiguration; //config.DataStoreLocation = DataStoreLocation; config.ProxyAddress = ProxyAddress; config.ProxyPort = ProxyPort; @@ -112,11 +112,11 @@ namespace Disco.Web.Areas.Config.Models.SystemConfig config.ProxyPassword = ProxyPassword; DiscoApplication.SetGlobalProxy(ProxyAddress, ProxyPort, ProxyUsername, ProxyPassword); - db.SaveChanges(); + Database.SaveChanges(); // Try and check for updates if needed - After Proxy Changed - if (db.DiscoConfiguration.UpdateLastCheck == null - || db.DiscoConfiguration.UpdateLastCheck.ResponseTimestamp < DateTime.Now.AddDays(-1)) + if (Database.DiscoConfiguration.UpdateLastCheck == null + || Database.DiscoConfiguration.UpdateLastCheck.ResponseTimestamp < DateTime.Now.AddDays(-1)) { Disco.BI.Interop.Community.UpdateCheckTask.ScheduleNow(); } diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.cshtml b/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.cshtml new file mode 100644 index 00000000..ab13efa1 --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.cshtml @@ -0,0 +1,28 @@ +@model Disco.Web.Areas.Config.Models.AuthorizationRole.CreateModel +@{ + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles", MVC.Config.AuthorizationRole.Index(null), "Create"); +} +@using (Html.BeginForm()) +{ +
+ + + + + +
+ Name: + + @Html.EditorFor(model => model.AuthorizationRole.Name)
@Html.ValidationMessageFor(model => model.AuthorizationRole.Name) +
+

+ +

+
+ +} diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.generated.cs b/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.generated.cs new file mode 100644 index 00000000..602fa6eb --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Create.generated.cs @@ -0,0 +1,122 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.18051 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Disco.Web.Areas.Config.Views.AuthorizationRole +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using System.Web.Helpers; + using System.Web.Mvc; + using System.Web.Mvc.Ajax; + using System.Web.Mvc.Html; + using System.Web.Routing; + using System.Web.Security; + using System.Web.UI; + using System.Web.WebPages; + using Disco.BI.Extensions; + using Disco.Models.Repository; + using Disco.Services.Authorization; + using Disco.Services.Web; + using Disco.Web; + using Disco.Web.Extensions; + + [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] + [System.Web.WebPages.PageVirtualPathAttribute("~/Areas/Config/Views/AuthorizationRole/Create.cshtml")] + public partial class Create : Disco.Services.Web.WebViewPage + { + public Create() + { + } + public override void Execute() + { + + #line 2 "..\..\Areas\Config\Views\AuthorizationRole\Create.cshtml" + + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles", MVC.Config.AuthorizationRole.Index(null), "Create"); + + + #line default + #line hidden +WriteLiteral("\r\n"); + + + #line 6 "..\..\Areas\Config\Views\AuthorizationRole\Create.cshtml" + using (Html.BeginForm()) +{ + + + #line default + #line hidden +WriteLiteral(" \r\n \r\n \r\n \r\n \r\n \r\n
\r\n N" + +"ame:\r\n \r\n"); + +WriteLiteral(" "); + + + #line 15 "..\..\Areas\Config\Views\AuthorizationRole\Create.cshtml" + Write(Html.EditorFor(model => model.AuthorizationRole.Name)); + + + #line default + #line hidden +WriteLiteral("
"); + + + #line 15 "..\..\Areas\Config\Views\AuthorizationRole\Create.cshtml" + Write(Html.ValidationMessageFor(model => model.AuthorizationRole.Name)); + + + #line default + #line hidden +WriteLiteral("\r\n
\r\n \r\n \r\n

\r\n \r\n"); + +WriteLiteral(" \r\n $(function () {\r\n $(\'#AuthorizationRole_Name\').focus().sele" + +"ct();\r\n });\r\n \r\n"); + + + #line 28 "..\..\Areas\Config\Views\AuthorizationRole\Create.cshtml" +} + + + #line default + #line hidden + } + } +} +#pragma warning restore 1591 diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.cshtml b/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.cshtml new file mode 100644 index 00000000..759aea3b --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.cshtml @@ -0,0 +1,43 @@ +@model Disco.Web.Areas.Config.Models.AuthorizationRole.IndexModel +@{ + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles"); +} +@if (Model.Tokens.Count == 0) +{ +
+

No authorization roles are configured

+
+} +else +{ + + + + + + @foreach (var item in Model.Tokens) + { + + + + + } +
Name + Linked Groups/Users +
+ @Html.ActionLink(item.Role.Name, MVC.Config.AuthorizationRole.Index(item.Role.Id)) + + @if (item.SubjectIds.Count == 0) + { + <None> + } + else + { + @(string.Join(", ", item.SubjectIds.OrderBy(i => i))) + } +
+} +
+ @Html.ActionLinkButton("Create Authorization Role", MVC.Config.AuthorizationRole.Create()) +
diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.generated.cs b/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.generated.cs new file mode 100644 index 00000000..e901d3c3 --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Index.generated.cs @@ -0,0 +1,197 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.18051 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Disco.Web.Areas.Config.Views.AuthorizationRole +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using System.Web.Helpers; + using System.Web.Mvc; + using System.Web.Mvc.Ajax; + using System.Web.Mvc.Html; + using System.Web.Routing; + using System.Web.Security; + using System.Web.UI; + using System.Web.WebPages; + using Disco.BI.Extensions; + using Disco.Models.Repository; + using Disco.Services.Authorization; + using Disco.Services.Web; + using Disco.Web; + using Disco.Web.Extensions; + + [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] + [System.Web.WebPages.PageVirtualPathAttribute("~/Areas/Config/Views/AuthorizationRole/Index.cshtml")] + public partial class Index : Disco.Services.Web.WebViewPage + { + public Index() + { + } + public override void Execute() + { + + #line 2 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles"); + + + #line default + #line hidden +WriteLiteral("\r\n"); + + + #line 6 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + if (Model.Tokens.Count == 0) +{ + + + #line default + #line hidden +WriteLiteral(" \r\n

No authorization roles are configured

\r\n \r\n"); + + + #line 11 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" +} +else +{ + + + #line default + #line hidden +WriteLiteral(" \r\n \r\n Name\r\n \r\n Linked " + +"Groups/Users\r\n \r\n \r\n"); + + + #line 21 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + + + #line default + #line hidden + + #line 21 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + foreach (var item in Model.Tokens) + { + + + #line default + #line hidden +WriteLiteral(" \r\n \r\n"); + +WriteLiteral(" "); + + + #line 25 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + Write(Html.ActionLink(item.Role.Name, MVC.Config.AuthorizationRole.Index(item.Role.Id))); + + + #line default + #line hidden +WriteLiteral("\r\n \r\n \r\n"); + + + #line 28 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + + + #line default + #line hidden + + #line 28 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + if (item.SubjectIds.Count == 0) + { + + + #line default + #line hidden +WriteLiteral(" <None>\r\n"); + + + #line 31 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + } + else + { + + + #line default + #line hidden + + #line 34 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + Write(string.Join(", ", item.SubjectIds.OrderBy(i => i))); + + + #line default + #line hidden + + #line 34 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + + } + + + #line default + #line hidden +WriteLiteral(" \r\n \r\n"); + + + #line 38 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" + } + + + #line default + #line hidden +WriteLiteral(" \r\n"); + + + #line 40 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" +} + + + #line default + #line hidden +WriteLiteral("\r\n"); + +WriteLiteral(" "); + + + #line 42 "..\..\Areas\Config\Views\AuthorizationRole\Index.cshtml" +Write(Html.ActionLinkButton("Create Authorization Role", MVC.Config.AuthorizationRole.Create())); + + + #line default + #line hidden +WriteLiteral("\r\n\r\n"); + + } + } +} +#pragma warning restore 1591 diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.cshtml b/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.cshtml new file mode 100644 index 00000000..b3cce872 --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.cshtml @@ -0,0 +1,320 @@ +@model Disco.Web.Areas.Config.Models.AuthorizationRole.ShowModel +@using Disco.Models.Authorization; +@{ + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles", MVC.Config.AuthorizationRole.Index(null), Model.Token.Role.Name); + Html.BundleDeferred("~/ClientScripts/Modules/Disco-PropertyChangeHelpers"); + Html.BundleDeferred("~/ClientScripts/Modules/Disco-AjaxHelperIcons"); + Html.BundleDeferred("~/Style/Fancytree"); + Html.BundleDeferred("~/ClientScripts/Modules/jQuery-Fancytree"); +} +
+ + + + + + + + + + + + + + + + +
Id: + + @Html.DisplayFor(model => model.Token.Role.Id) +
Name: + @Html.EditorFor(model => model.Token.Role.Name) + @AjaxHelpers.AjaxSave() + @AjaxHelpers.AjaxLoader() + +
Linked Groups/Users: + @if (Model.Token.SubjectIds.Count == 0) + { + None Associated + } + else + { +
    + @foreach (var sg in Model.Subjects) + { +
  • @(sg.Id == sg.Name ? sg.Id : string.Format("{0} [{1}]", sg.Name, sg.Id))
  • + } +
+ } +
+ Update +
+
+ None Associated +
    + @foreach (var sg in Model.Subjects) + { +
  • @(sg.Id == sg.Name ? sg.Id : string.Format("{0} [{1}]", sg.Name, sg.Id))
  • + } +
+
+
+ + Add +
+
+
+ +
+
+
+
+
+ Save Changes@AjaxHelpers.AjaxLoader() +
+ +
+
+
+ @Html.ActionLinkButton("Delete", MVC.API.AuthorizationRole.Delete(Model.Token.Role.Id, true), "Config_AuthRoles_Actions_Delete_Button") +
+

+ + This item will be permanently deleted and cannot be recovered.
+
+ Are you sure? +

+
+ +
diff --git a/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.generated.cs b/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.generated.cs new file mode 100644 index 00000000..adf7fc60 --- /dev/null +++ b/Disco.Web/Areas/Config/Views/AuthorizationRole/Show.generated.cs @@ -0,0 +1,632 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.18051 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Disco.Web.Areas.Config.Views.AuthorizationRole +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using System.Web.Helpers; + using System.Web.Mvc; + using System.Web.Mvc.Ajax; + using System.Web.Mvc.Html; + using System.Web.Routing; + using System.Web.Security; + using System.Web.UI; + using System.Web.WebPages; + using Disco.BI.Extensions; + + #line 2 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + using Disco.Models.Authorization; + + #line default + #line hidden + using Disco.Models.Repository; + using Disco.Services.Authorization; + using Disco.Services.Web; + using Disco.Web; + using Disco.Web.Extensions; + + [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] + [System.Web.WebPages.PageVirtualPathAttribute("~/Areas/Config/Views/AuthorizationRole/Show.cshtml")] + public partial class Show : Disco.Services.Web.WebViewPage + { + public Show() + { + } + public override void Execute() + { + + #line 3 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + + Authorization.Require(Claims.DiscoAdminAccount); + ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Authorization Roles", MVC.Config.AuthorizationRole.Index(null), Model.Token.Role.Name); + Html.BundleDeferred("~/ClientScripts/Modules/Disco-PropertyChangeHelpers"); + Html.BundleDeferred("~/ClientScripts/Modules/Disco-AjaxHelperIcons"); + Html.BundleDeferred("~/Style/Fancytree"); + Html.BundleDeferred("~/ClientScripts/Modules/jQuery-Fancytree"); + + + #line default + #line hidden +WriteLiteral("\r\n\r\n \r\n \r\n Id:\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n " + +" \r\n \r\n + +
\r\n"); + +WriteLiteral(" "); + + + #line 17 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(Html.DisplayFor(model => model.Token.Role.Id)); + + + #line default + #line hidden +WriteLiteral("\r\n
Name:\r\n " + +" "); + + + #line 23 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(Html.EditorFor(model => model.Token.Role.Name)); + + + #line default + #line hidden +WriteLiteral("\r\n"); + +WriteLiteral(" "); + + + #line 24 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(AjaxHelpers.AjaxSave()); + + + #line default + #line hidden +WriteLiteral("\r\n"); + +WriteLiteral(" "); + + + #line 25 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(AjaxHelpers.AjaxLoader()); + + + #line default + #line hidden +WriteLiteral("\r\n \r\n $(function () {\r\n document.DiscoFun" + +"ctions.PropertyChangeHelper(\r\n $(\'#Token_Role_Name\')," + +"\r\n \'Invalid Name\',\r\n \'"); + + + #line 31 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(Url.Action(MVC.API.AuthorizationRole.UpdateName(Model.Token.Role.Id))); + + + #line default + #line hidden +WriteLiteral("\',\r\n \'RoleName\'\r\n );\r\n " + +" });\r\n \r\n
Linked Groups/Users:\r\n"); + + + #line 41 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + + + #line default + #line hidden + + #line 41 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + if (Model.Token.SubjectIds.Count == 0) + { + + + #line default + #line hidden +WriteLiteral(" None Associated\r\n"); + + + #line 44 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + } + else + { + + + #line default + #line hidden +WriteLiteral(" \r\n"); + + + #line 48 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + + + #line default + #line hidden + + #line 48 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + foreach (var sg in Model.Subjects) + { + + + #line default + #line hidden +WriteLiteral(" (sg.IsGroup ? "group" : "user" + + #line default + #line hidden +, 2077), false) +); + +WriteLiteral(">"); + + + #line 50 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(sg.Id == sg.Name ? sg.Id : string.Format("{0} [{1}]", sg.Name, sg.Id)); + + + #line default + #line hidden +WriteLiteral("\r\n"); + + + #line 51 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + } + + + #line default + #line hidden +WriteLiteral(" \r\n"); + + + #line 53 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + } + + + #line default + #line hidden +WriteLiteral("
\r\n Update\r\n \r\n \r\n None Associated\r\n \r\n"); + + + #line 60 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + + + #line default + #line hidden + + #line 60 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + foreach (var sg in Model.Subjects) + { + + + #line default + #line hidden +WriteLiteral(" (sg.IsGroup ? "group" : "user" + + #line default + #line hidden +, 2990), false) +); + +WriteLiteral(" data-subjectid=\""); + + + #line 62 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(sg.Id); + + + #line default + #line hidden +WriteLiteral("\""); + +WriteLiteral(">"); + + + #line 62 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + Write(sg.Id == sg.Name ? sg.Id : string.Format("{0} [{1}]", sg.Name, sg.Id)); + + + #line default + #line hidden +WriteLiteral(" \r\n"); + + + #line 63 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" + } + + + #line default + #line hidden +WriteLiteral(" \r\n
\r\n " + +" \r\n \r\n Add\r\n \r\n (Url.Action(MVC.API.AuthorizationRole.UpdateSubjects(Model.Token.Role.Id, null, true)) + + #line default + #line hidden +, 3690), false) +); + +WriteLiteral(" method=\"post\""); + +WriteLiteral(">\r\n \r\n +
+ +\r\n"); + +WriteLiteral(" "); + + + #line 283 "..\..\Areas\Config\Views\AuthorizationRole\Show.cshtml" +Write(Html.ActionLinkButton("Delete", MVC.API.AuthorizationRole.Delete(Model.Token.Role.Id, true), "Config_AuthRoles_Actions_Delete_Button")); + + + #line default + #line hidden +WriteLiteral("\r\n \r\n

\r\n \r\n This item will be permanently deleted and cannot be recover" + +"ed.
\r\n
\r\n Are you sure?\r\n

\r\n \r\n + $(function () { + var button = $('#Config_AuthRoles_Actions_Delete_Button'); + var buttonDialog = $('#Config_AuthRoles_Actions_Delete_Dialog'); + var buttonLink = button.attr('href'); + button.attr('href', '#'); + button.click(function () { + buttonDialog.dialog('open'); + return false; + }); + buttonDialog.dialog({ + resizable: false, + modal: true, + autoOpen: false, + buttons: { + ""Delete"": function () { + var $this = $(this); + $this.dialog(""disable""); + $this.dialog(""option"", ""buttons"", null); + window.location.href = buttonLink; + }, + Cancel: function () { + $(this).dialog(""close""); + } + } + }); + }); + + +"); + + } + } +} +#pragma warning restore 1591 diff --git a/Disco.Web/Areas/Config/Views/Config/Index.cshtml b/Disco.Web/Areas/Config/Views/Config/Index.cshtml index 52b78767..fe4e5962 100644 --- a/Disco.Web/Areas/Config/Views/Config/Index.cshtml +++ b/Disco.Web/Areas/Config/Views/Config/Index.cshtml @@ -1,62 +1,106 @@ @model Disco.Web.Areas.Config.Models.Config.IndexModel @{ + Authorization.Require(Claims.Config.Show); ViewBag.Title = "Configuration"; } - - + } + @if (Authorization.HasAny(Claims.Config.DeviceModel.Show, Claims.Config.DeviceBatch.Show, Claims.Config.DeviceProfile.Show, Claims.Config.Enrolment.Show)) + { + - + } + @if (Authorization.HasAny(Claims.Config.DocumentTemplate.Show, Claims.Config.Plugin.Show)) + { + + + } @{ diff --git a/Disco.Web/Areas/Config/Views/Config/Index.generated.cs b/Disco.Web/Areas/Config/Views/Config/Index.generated.cs index f4a294c3..f2471c80 100644 --- a/Disco.Web/Areas/Config/Views/Config/Index.generated.cs +++ b/Disco.Web/Areas/Config/Views/Config/Index.generated.cs @@ -2,7 +2,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18033 +// Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -28,12 +28,14 @@ namespace Disco.Web.Areas.Config.Views.Config using System.Web.WebPages; using Disco.BI.Extensions; using Disco.Models.Repository; + using Disco.Services.Authorization; + using Disco.Services.Web; using Disco.Web; using Disco.Web.Extensions; [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] [System.Web.WebPages.PageVirtualPathAttribute("~/Areas/Config/Views/Config/Index.cshtml")] - public partial class Index : System.Web.Mvc.WebViewPage + public partial class Index : Disco.Services.Web.WebViewPage { public Index() { @@ -43,6 +45,7 @@ namespace Disco.Web.Areas.Config.Views.Config #line 2 "..\..\Areas\Config\Views\Config\Index.cshtml" + Authorization.Require(Claims.Config.Show); ViewBag.Title = "Configuration"; @@ -52,170 +55,485 @@ WriteLiteral("\r\n\r\n \r\n \r\n \r\n \r\n"); + + + #line 8 "..\..\Areas\Config\Views\Config\Index.cshtml" + + + #line default + #line hidden + + #line 8 "..\..\Areas\Config\Views\Config\Index.cshtml" + if (Authorization.HasAny(Claims.Config.System.Show, Claims.Config.Organisation.Show, Claims.DiscoAdminAccount, Claims.Config.Logging.Show)) + { + + + #line default + #line hidden +WriteLiteral(" \r\n \r\n

Hosting

\r\n"); - -WriteLiteral(" "); +WriteLiteral(">\r\n

Hosting

\r\n"); - #line 10 "..\..\Areas\Config\Views\Config\Index.cshtml" - Write(Html.ActionLinkClass("System", MVC.Config.SystemConfig.Index(), "config")); + #line 13 "..\..\Areas\Config\Views\Config\Index.cshtml" + + + #line default + #line hidden + + #line 13 "..\..\Areas\Config\Views\Config\Index.cshtml" + if (Authorization.Has(Claims.Config.System.Show)) + { + + + #line default + #line hidden + + #line 15 "..\..\Areas\Config\Views\Config\Index.cshtml" + Write(Html.ActionLinkClass("System", MVC.Config.SystemConfig.Index(), "config")); #line default #line hidden -WriteLiteral("\r\n \r\n Update system configuration, such as the Data Storage Loca" + -"tion and Proxy settings.\r\n \r\n"); - -WriteLiteral(" "); - - #line 14 "..\..\Areas\Config\Views\Config\Index.cshtml" - Write(Html.ActionLinkClass("Organisation Details", MVC.Config.Organisation.Index(), "config")); + #line 15 "..\..\Areas\Config\Views\Config\Index.cshtml" + #line default #line hidden -WriteLiteral("\r\n \r\n Update the Organisation Name, Logo and Addresses associate" + -"d with this organisation.\r\n \r\n"); - -WriteLiteral(" "); +WriteLiteral(">\r\n Update system configuration, such as the Data Stor" + +"age Location and Proxy settings.\r\n \r\n"); - #line 18 "..\..\Areas\Config\Views\Config\Index.cshtml" - Write(Html.ActionLinkClass("Logging", MVC.Config.Logging.Index(), "config")); + #line 19 "..\..\Areas\Config\Views\Config\Index.cshtml" + } #line default #line hidden -WriteLiteral("\r\n