security: use more antiforgery tokens

This commit is contained in:
Gary Sharp
2025-07-25 12:32:44 +10:00
parent fd43d85778
commit 7deead494b
222 changed files with 12919 additions and 11728 deletions
@@ -17,7 +17,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Properties
const string pName = "name";
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
try
@@ -40,19 +40,19 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Authorization Role Id");
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -96,27 +96,27 @@ namespace Disco.Web.Areas.API.Controllers
AuthorizationLog.LogRoleConfiguredClaimsAdded(AuthorizationRole, CurrentUser.UserId, addedClaims);
}
private void UpdateSubjects(AuthorizationRole AuthorizationRole, string[] Subjects)
private void UpdateSubjects(AuthorizationRole AuthorizationRole, string[] subjects)
{
string subjectIds = null;
string[] removedSubjects = null;
string[] addedSubjects = null;
// Validate Subjects
if (Subjects != null && Subjects.Length > 0)
if (subjects != null && subjects.Length > 0)
{
var subjects = Subjects
var subjectRecords = subjects
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Trim())
.Select(s => Tuple.Create(s, ActiveDirectory.RetrieveADObject(s, Quick: true)))
.Where(s => s.Item2 is ADUserAccount || s.Item2 is ADGroup)
.ToList();
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
var invalidSubjects = subjectRecords.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0)
throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var proposedSubjects = subjectRecords.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var currentSubjects = AuthorizationRole.SubjectIds == null ? new string[0] : AuthorizationRole.SubjectIds.Split(',');
removedSubjects = currentSubjects.Except(proposedSubjects).ToArray();
addedSubjects = proposedSubjects.Except(currentSubjects).ToArray();
@@ -139,12 +139,14 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[HttpPost, ValidateAntiForgeryToken]
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)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateClaims(int id, string[] claimKeys = null, bool redirect = false)
{
try
{
@@ -154,26 +156,27 @@ namespace Disco.Web.Areas.API.Controllers
var authorizationRole = Database.AuthorizationRoles.Find(id);
if (authorizationRole != null)
{
UpdateClaims(authorizationRole, ClaimKeys);
UpdateClaims(authorizationRole, claimKeys);
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Authorization Role Id");
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSubjects(int id, string[] Subjects = null, bool redirect = false)
{
try
@@ -188,26 +191,26 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Authorization Role Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Authorization Role Id");
}
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(authorizationRole.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
#region Actions
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -220,7 +223,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.AuthorizationRole.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Authorization Role Id");
}
@@ -229,33 +232,33 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[HttpPost]
public virtual ActionResult UpdateAdministratorSubjects(string[] Subjects, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAdministratorSubjects(string[] subjects, bool redirect = false)
{
string[] proposedSubjects;
string[] removedSubjects = null;
string[] addedSubjects = null;
// Validate Subjects
if (Subjects == null || Subjects.Length == 0)
if (subjects == null || subjects.Length == 0)
throw new ArgumentNullException("Subjects", "At least one Id must be supplied");
var subjects = Subjects
var subjectValues = subjects
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Trim())
.Select(s => Tuple.Create(s, ActiveDirectory.RetrieveADObject(s, Quick: true)))
.Where(s => s.Item2 is ADUserAccount || s.Item2 is ADGroup)
.ToList();
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
var invalidSubjects = subjectValues.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0)
throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
proposedSubjects = subjectValues.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var currentSubjects = UserService.AdministratorSubjectIds;
removedSubjects = currentSubjects.Except(proposedSubjects).ToArray();
addedSubjects = proposedSubjects.Except(currentSubjects).ToArray();
@@ -270,7 +273,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.AuthorizationRole.Index());
else
return Json("OK");
return Ok();
}
#endregion
@@ -1,53 +0,0 @@
using Disco.Services.Authorization;
using Disco.Services.Web;
using System;
using System.Web.Mvc;
namespace Disco.Web.Areas.API.Controllers
{
[DiscoAuthorize(Claims.Config.Enrolment.Configure)]
public partial class BootstrapperController : AuthorizedDatabaseController
{
public virtual ActionResult MacSshUsername(string MacSshUsername)
{
try
{
if (!string.IsNullOrWhiteSpace(MacSshUsername))
{
Database.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername;
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
else
{
throw new Exception("The Username cannot be null or empty");
}
}
catch (Exception ex)
{
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
}
}
public virtual ActionResult MacSshPassword(string MacSshPassword)
{
try
{
if (!string.IsNullOrWhiteSpace(MacSshPassword))
{
Database.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword;
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
else
{
throw new Exception("The Password cannot be null or empty");
}
}
catch (Exception ex)
{
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
}
}
}
}
@@ -9,6 +9,7 @@ using Disco.Services.Web;
using Disco.Web.Extensions;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Web.Mvc;
@@ -35,6 +36,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pAssignedUsersLinkedGroup = "assigneduserslinkedgroup";
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
Authorization.Require(Claims.Config.DeviceBatch.Configure);
@@ -104,109 +106,124 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Device Batch Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Batch Id");
}
if (redirect)
return RedirectToAction(MVC.Config.DeviceBatch.Index(deviceBatch.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateName(int id, string BatchName = null, bool redirect = false)
{
return Update(id, pName, BatchName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdatePurchaseDate(int id, string PurchaseDate = null, bool redirect = false)
{
return Update(id, pPurchaseDate, PurchaseDate, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSupplier(int id, string Supplier = null, bool redirect = false)
{
return Update(id, pSupplier, Supplier, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdatePurchaseDetails(int id, string PurchaseDetails = null, bool redirect = false)
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public virtual ActionResult UpdatePurchaseDetails(int id, string purchaseDetails = null, bool redirect = false)
{
return Update(id, pPurchaseDetails, PurchaseDetails, redirect);
return Update(id, pPurchaseDetails, purchaseDetails, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateUnitCost(int id, string UnitCost = null, bool redirect = false)
{
return Update(id, pUnitCost, UnitCost, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateUnitQuantity(int id, string UnitQuantity = null, bool redirect = false)
{
return Update(id, pUnitQuantity, UnitQuantity, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDefaultDeviceModelId(int id, string DefaultDeviceModelId = null, bool redirect = false)
{
return Update(id, pDefaultDeviceModelId, DefaultDeviceModelId, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyValidUntil(int id, string WarrantyValidUntil = null, bool redirect = false)
{
return Update(id, pWarrantyValidUntil, WarrantyValidUntil, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateWarrantyDetails(int id, string WarrantyDetails = null, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyDetails(int id, string warrantyDetails = null, bool redirect = false)
{
return Update(id, pWarrantyDetails, WarrantyDetails, redirect);
return Update(id, pWarrantyDetails, warrantyDetails, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuredDate(int id, string InsuredDate = null, bool redirect = false)
{
return Update(id, pInsuredDate, InsuredDate, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceSupplier(int id, string InsuranceSupplier = null, bool redirect = false)
{
return Update(id, pInsuranceSupplier, InsuranceSupplier, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuredUntil(int id, string InsuredUntil = null, bool redirect = false)
{
return Update(id, pInsuredUntil, InsuredUntil, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateInsuranceDetails(int id, string InsuranceDetails = null, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceDetails(int id, string insuranceDetails = null, bool redirect = false)
{
return Update(id, pInsuranceDetails, InsuranceDetails, redirect);
return Update(id, pInsuranceDetails, insuranceDetails, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure), ValidateInput(false)]
public virtual ActionResult UpdateComments(int id, string Comments = null, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateComments(int id, string comments = null, bool redirect = false)
{
return Update(id, pComments, Comments, redirect);
return Update(id, pComments, comments, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDevicesLinkedGroup(int id, string GroupId = null, bool redirect = false)
{
try
@@ -228,17 +245,18 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUsersLinkedGroup(int id, string GroupId = null, bool redirect = false)
{
try
@@ -260,42 +278,42 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
#region Update Properties
private void UpdateName(DeviceBatch deviceBatch, string Name)
private void UpdateName(DeviceBatch deviceBatch, string name)
{
if (string.IsNullOrWhiteSpace(Name))
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException("Name", "Device Batch Name is required");
else
{
// Check for Duplicates
var d = Database.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;
deviceBatch.Name = name;
}
Database.SaveChanges();
}
private void UpdatePurchaseDate(DeviceBatch deviceBatch, string PurchaseDate)
private void UpdatePurchaseDate(DeviceBatch deviceBatch, string purchaseDate)
{
if (string.IsNullOrEmpty(PurchaseDate))
if (string.IsNullOrEmpty(purchaseDate))
throw new ArgumentNullException("PurchaseDate", "A Device Batch Purchase Date is required");
else
{
if (DateTime.TryParse(PurchaseDate, out var ecd))
if (DateTime.TryParse(purchaseDate, out var ecd))
{
deviceBatch.PurchaseDate = ecd.Date;
}
@@ -306,48 +324,48 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateSupplier(DeviceBatch deviceBatch, string Supplier)
private void UpdateSupplier(DeviceBatch deviceBatch, string supplier)
{
if (string.IsNullOrWhiteSpace(Supplier))
if (string.IsNullOrWhiteSpace(supplier))
deviceBatch.Supplier = null;
else
deviceBatch.Supplier = Supplier;
deviceBatch.Supplier = supplier;
Database.SaveChanges();
}
private void UpdatePurchaseDetails(DeviceBatch deviceBatch, string PurchaseDetails)
private void UpdatePurchaseDetails(DeviceBatch deviceBatch, string purchaseDetails)
{
if (string.IsNullOrWhiteSpace(PurchaseDetails))
if (string.IsNullOrWhiteSpace(purchaseDetails))
deviceBatch.PurchaseDetails = null;
else
deviceBatch.PurchaseDetails = PurchaseDetails;
deviceBatch.PurchaseDetails = purchaseDetails;
Database.SaveChanges();
}
private void UpdateUnitCost(DeviceBatch deviceBatch, string UnitCost)
private void UpdateUnitCost(DeviceBatch deviceBatch, string unitCost)
{
if (string.IsNullOrWhiteSpace(UnitCost))
if (string.IsNullOrWhiteSpace(unitCost))
deviceBatch.UnitCost = null;
else
{
if (decimal.TryParse(UnitCost, out var unitCost))
{
deviceBatch.UnitCost = unitCost;
}
unitCost = unitCost.Trim();
if (unitCost.StartsWith("$"))
unitCost = unitCost.Substring(1).Trim(); // Remove $ sign if present
if (decimal.TryParse(unitCost, out var unitCostValue))
deviceBatch.UnitCost = unitCostValue;
else
{
throw new Exception("Invalid Currency Format");
}
}
Database.SaveChanges();
}
private void UpdateUnitQuantity(DeviceBatch deviceBatch, string UnitQuantity)
private void UpdateUnitQuantity(DeviceBatch deviceBatch, string unitQuantity)
{
if (string.IsNullOrWhiteSpace(UnitQuantity))
if (string.IsNullOrWhiteSpace(unitQuantity))
deviceBatch.UnitQuantity = null;
else
{
if (int.TryParse(UnitQuantity, out var unitQuantity))
if (int.TryParse(unitQuantity, out var unitQuantityValue))
{
deviceBatch.UnitQuantity = unitQuantity;
deviceBatch.UnitQuantity = unitQuantityValue;
}
else
{
@@ -356,11 +374,11 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateDefaultDeviceModelId(DeviceBatch deviceBatch, string DefaultDeviceModelId)
private void UpdateDefaultDeviceModelId(DeviceBatch deviceBatch, string defaultDeviceModelId)
{
if (!string.IsNullOrEmpty(DefaultDeviceModelId))
if (!string.IsNullOrEmpty(defaultDeviceModelId))
{
if (int.TryParse(DefaultDeviceModelId, out var bId))
if (int.TryParse(defaultDeviceModelId, out var bId))
{
var dm = Database.DeviceModels.Find(bId);
if (dm != null)
@@ -384,13 +402,13 @@ namespace Disco.Web.Areas.API.Controllers
}
throw new Exception("Invalid Device Model Id");
}
private void UpdateWarrantyValidUntil(DeviceBatch deviceBatch, string WarrantyValidUntil)
private void UpdateWarrantyValidUntil(DeviceBatch deviceBatch, string warrantyValidUntil)
{
if (string.IsNullOrEmpty(WarrantyValidUntil))
if (string.IsNullOrEmpty(warrantyValidUntil))
deviceBatch.WarrantyValidUntil = null;
else
{
if (DateTime.TryParse(WarrantyValidUntil, out var ecd))
if (DateTime.TryParse(warrantyValidUntil, out var ecd))
{
deviceBatch.WarrantyValidUntil = ecd.Date;
}
@@ -401,21 +419,21 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateWarrantyDetails(DeviceBatch deviceBatch, string WarrantyDetails)
private void UpdateWarrantyDetails(DeviceBatch deviceBatch, string warrantyDetails)
{
if (string.IsNullOrWhiteSpace(WarrantyDetails))
if (string.IsNullOrWhiteSpace(warrantyDetails))
deviceBatch.WarrantyDetails = null;
else
deviceBatch.WarrantyDetails = WarrantyDetails;
deviceBatch.WarrantyDetails = warrantyDetails;
Database.SaveChanges();
}
private void UpdateInsuredDate(DeviceBatch deviceBatch, string InsuredDate)
private void UpdateInsuredDate(DeviceBatch deviceBatch, string insuredDate)
{
if (string.IsNullOrEmpty(InsuredDate))
if (string.IsNullOrEmpty(insuredDate))
deviceBatch.InsuredDate = null;
else
{
if (DateTime.TryParse(InsuredDate, out var ecd))
if (DateTime.TryParse(insuredDate, out var ecd))
{
deviceBatch.InsuredDate = ecd.Date;
}
@@ -426,21 +444,21 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateInsuranceSupplier(DeviceBatch deviceBatch, string InsuranceSupplier)
private void UpdateInsuranceSupplier(DeviceBatch deviceBatch, string insuranceSupplier)
{
if (string.IsNullOrWhiteSpace(InsuranceSupplier))
if (string.IsNullOrWhiteSpace(insuranceSupplier))
deviceBatch.InsuranceSupplier = null;
else
deviceBatch.InsuranceSupplier = InsuranceSupplier;
deviceBatch.InsuranceSupplier = insuranceSupplier;
Database.SaveChanges();
}
private void UpdateInsuredUntil(DeviceBatch deviceBatch, string InsuredUntil)
private void UpdateInsuredUntil(DeviceBatch deviceBatch, string insuredUntil)
{
if (string.IsNullOrEmpty(InsuredUntil))
if (string.IsNullOrEmpty(insuredUntil))
deviceBatch.InsuredUntil = null;
else
{
if (DateTime.TryParse(InsuredUntil, out var ecd))
if (DateTime.TryParse(insuredUntil, out var ecd))
{
deviceBatch.InsuredUntil = ecd.Date;
}
@@ -451,26 +469,26 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateInsuranceDetails(DeviceBatch deviceBatch, string InsuranceDetails)
private void UpdateInsuranceDetails(DeviceBatch deviceBatch, string insuranceDetails)
{
if (string.IsNullOrWhiteSpace(InsuranceDetails))
if (string.IsNullOrWhiteSpace(insuranceDetails))
deviceBatch.InsuranceDetails = null;
else
deviceBatch.InsuranceDetails = InsuranceDetails;
deviceBatch.InsuranceDetails = insuranceDetails;
Database.SaveChanges();
}
private void UpdateComments(DeviceBatch deviceBatch, string Comments)
private void UpdateComments(DeviceBatch deviceBatch, string comments)
{
if (string.IsNullOrWhiteSpace(Comments))
if (string.IsNullOrWhiteSpace(comments))
deviceBatch.Comments = null;
else
deviceBatch.Comments = Comments;
deviceBatch.Comments = comments;
Database.SaveChanges();
}
private ScheduledTaskStatus UpdateDevicesLinkedGroup(DeviceBatch DeviceBatch, string DevicesLinkedGroup)
private ScheduledTaskStatus UpdateDevicesLinkedGroup(DeviceBatch DeviceBatch, string devicesLinkedGroup)
{
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceBatchDevicesManagedGroup.GetKey(DeviceBatch), DevicesLinkedGroup, null);
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceBatchDevicesManagedGroup.GetKey(DeviceBatch), devicesLinkedGroup, null);
if (DeviceBatch.DevicesLinkedGroup != configJson)
{
@@ -485,9 +503,9 @@ namespace Disco.Web.Areas.API.Controllers
return null;
}
private ScheduledTaskStatus UpdateAssignedUsersLinkedGroup(DeviceBatch DeviceBatch, string AssignedUsersLinkedGroup)
private ScheduledTaskStatus UpdateAssignedUsersLinkedGroup(DeviceBatch DeviceBatch, string assignedUsersLinkedGroup)
{
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceBatchAssignedUsersManagedGroup.GetKey(DeviceBatch), AssignedUsersLinkedGroup, null);
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceBatchAssignedUsersManagedGroup.GetKey(DeviceBatch), assignedUsersLinkedGroup, null);
if (DeviceBatch.AssignedUsersLinkedGroup != configJson)
{
@@ -506,6 +524,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DeviceBatch.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -518,7 +537,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceBatch.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Device Batch Number");
}
@@ -527,7 +546,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -536,6 +555,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Index
[DiscoAuthorize(Claims.Config.DeviceBatch.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Index(int? id)
{
if (id.HasValue)
@@ -556,6 +576,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Timeline
[DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Config.DeviceBatch.ShowTimeline)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Timeline()
{
@@ -601,7 +622,7 @@ namespace Disco.Web.Areas.API.Controllers
}
#endregion
#region Attachements
#region Attachments
[DiscoAuthorize(Claims.Config.DeviceBatch.Show)]
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
@@ -660,6 +681,9 @@ namespace Disco.Web.Areas.API.Controllers
if (string.IsNullOrEmpty(contentType) || contentType.Equals("unknown/unknown", StringComparison.OrdinalIgnoreCase))
contentType = MimeTypes.ResolveMimeType(file.FileName);
if (string.IsNullOrWhiteSpace(comments))
comments = null;
var attachment = new DeviceBatchAttachment()
{
DeviceBatchId = batch.Id,
@@ -687,7 +711,7 @@ namespace Disco.Web.Areas.API.Controllers
[DiscoAuthorize(Claims.Config.DeviceBatch.Show)]
public virtual ActionResult Attachment(int id)
{
var attachment = Database.DeviceBatchAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var attachment = Database.DeviceBatchAttachments.Include(a => a.TechUser).Where(m => m.Id == id).FirstOrDefault();
if (attachment != null)
{
@@ -699,13 +723,13 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m, JsonRequestBehavior.AllowGet);
}
return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Show)]
public virtual ActionResult Attachments(int id)
{
var batch = Database.DeviceBatches.Include("DeviceBatchAttachments.TechUser").Where(m => m.Id == id).FirstOrDefault();
var batch = Database.DeviceBatches.Include(b => b.DeviceBatchAttachments.Select(a => a.TechUser)).Where(m => m.Id == id).FirstOrDefault();
if (batch != null)
{
var m = new Models.Attachment.AttachmentsModel()
@@ -716,20 +740,21 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m, JsonRequestBehavior.AllowGet);
}
return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid Device Batch Id" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Batch Id");
}
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentRemove(int id)
{
var attachment = Database.DeviceBatchAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
var attachment = Database.DeviceBatchAttachments.Include(a => a.TechUser).Where(m => m.Id == id).FirstOrDefault();
if (attachment != null)
{
attachment.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
#endregion
@@ -9,6 +9,7 @@ namespace Disco.Web.Areas.API.Controllers
{
[DiscoAuthorize(Claims.Config.DeviceCertificate.DownloadCertificates)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Download(int id)
{
var wc = Database.DeviceCertificates.Find(id);
@@ -26,7 +26,6 @@ namespace Disco.Web.Areas.API.Controllers
{
public partial class DeviceController : AuthorizedDatabaseController
{
const string pDeviceProfileId = "deviceprofileid";
const string pDeviceBatchId = "devicebatchid";
const string pAssetNumber = "assetnumber";
@@ -37,6 +36,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pDetailBattery = "detailbattery";
const string pDetailKeyboard = "detailkeyboard";
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false)
{
Database.Configuration.LazyLoadingEnabled = true;
@@ -99,20 +99,21 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Device.Show(device.SerialNumber));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Device.Properties.DeviceProfile), HttpPost, ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Device.Properties.DeviceProfile)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDeviceProfileId(string id, string DeviceProfileId = null, bool enforceOrganisationalUnit = false, bool redirect = false)
{
var updateResult = Update(id, pDeviceProfileId, DeviceProfileId, redirect);
@@ -163,24 +164,28 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Device.Properties.DeviceBatch)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDeviceBatchId(string id, string DeviceBatchId = null, bool redirect = false)
{
return Update(id, pDeviceBatchId, DeviceBatchId, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.AssetNumber)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssetNumber(string id, string AssetNumber = null, bool redirect = false)
{
return Update(id, pAssetNumber, AssetNumber, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.Location)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLocation(string id, string Location = null, bool redirect = false)
{
return Update(id, pLocation, Location, redirect);
}
[DiscoAuthorize(Claims.Device.Actions.AssignUser)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUserId(string id, string AssignedUserId = null, bool redirect = false)
{
if (!string.IsNullOrWhiteSpace(AssignedUserId))
@@ -190,24 +195,28 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Device.Actions.AllowUnauthenticatedEnrol)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAllowUnauthenticatedEnrol(string id, string AllowUnauthenticatedEnrol = null, bool redirect = false)
{
return Update(id, pAllowUnauthenticatedEnrol, AllowUnauthenticatedEnrol, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.Details)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDetailACAdapter(string id, string DetailACAdapter = null, bool redirect = false)
{
return Update(id, pDetailACAdapter, DetailACAdapter, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.Details)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDetailBattery(string id, string DetailBattery = null, bool redirect = false)
{
return Update(id, pDetailBattery, DetailBattery, redirect);
}
[DiscoAuthorize(Claims.Device.Properties.Details)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDetailKeyboard(string id, string DetailKeyboard = null, bool redirect = false)
{
return Update(id, pDetailKeyboard, DetailKeyboard, redirect);
@@ -344,31 +353,36 @@ namespace Disco.Web.Areas.API.Controllers
#region Device Actions
[DiscoAuthorize(Claims.Device.Actions.Decommission)]
public virtual ActionResult Decommission(string id, int Reason, bool redirect)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Decommission(string id, int? Reason = null, bool redirect = false)
{
if (Reason == null)
throw new ArgumentNullException(nameof(Reason), "Decommission Reason is required");
var d = Database.Devices.Find(id);
Database.Configuration.LazyLoadingEnabled = true;
if (d != null)
{
if (d.CanDecommission())
{
d.OnDecommission((DecommissionReasons)Reason, Database);
d.OnDecommission((DecommissionReasons)Reason.Value, Database);
Database.SaveChanges();
if (redirect)
return RedirectToAction(MVC.Device.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Device's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Device's state doesn't allow this action");
}
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Serial Number");
}
[DiscoAuthorize(Claims.Device.Actions.Recommission)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Recommission(string id, bool redirect)
{
var d = Database.Devices.Find(id);
@@ -383,17 +397,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Device.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Device's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Device's state doesn't allow this action");
}
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Serial Number");
}
[DiscoAuthorize(Claims.Device.Actions.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(string id, bool redirect)
{
var j = Database.Devices.Find(id);
@@ -408,43 +423,20 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Device.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Device Serial Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Serial Number");
}
#endregion
[DiscoAuthorize(Claims.Device.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdf(string id, string DocumentTemplateId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplateId))
throw new ArgumentNullException(nameof(DocumentTemplateId));
// Obsolete: Use API\DocumentTemplate\Generate instead
return RedirectToAction(MVC.API.DocumentTemplate.Generate(DocumentTemplateId, id));
}
[DiscoAuthorize(Claims.Device.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdfPackage(string id, string DocumentTemplatePackageId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplatePackageId))
throw new ArgumentNullException(nameof(DocumentTemplatePackageId));
// Obsolete: Use API\DocumentTemplatePackage\Generate instead
return RedirectToAction(MVC.API.DocumentTemplatePackage.Generate(DocumentTemplatePackageId, id));
}
[DiscoAuthorize(Claims.Device.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult LastNetworkLogonDate(string id)
{
if (string.IsNullOrWhiteSpace(id))
@@ -585,7 +577,8 @@ namespace Disco.Web.Areas.API.Controllers
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Device.Actions.AddAttachments), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Device.Actions.AddAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentUpload(string id, string comments)
{
var d = Database.Devices.Find(id);
@@ -644,7 +637,7 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m, JsonRequestBehavior.AllowGet);
}
return Json(new Models.Attachment.AttachmentModel() { Result = "Invalid Attachment Number" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Device.ShowAttachments)]
@@ -661,10 +654,11 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m, JsonRequestBehavior.AllowGet);
}
return Json(new Models.Attachment.AttachmentsModel() { Result = "Invalid Device Serial Number" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Serial Number");
}
[DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentRemove(int id)
{
var da = Database.DeviceAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
@@ -677,9 +671,9 @@ namespace Disco.Web.Areas.API.Controllers
da.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Device.Actions.AddAttachments)]
@@ -706,11 +700,7 @@ namespace Disco.Web.Areas.API.Controllers
}
catch (InvalidOperationException ex)
{
return Json(new
{
Success = false,
ErrorMessage = ex.Message,
});
return BadRequest(ex.Message);
}
}
@@ -736,6 +726,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Device.Actions.Import)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImportBegin(HttpPostedFileBase ImportFile, bool HasHeader)
{
if (ImportFile == null || ImportFile.ContentLength == 0)
@@ -752,15 +743,14 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Device.Actions.Import)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImportParse(string Id, List<DeviceImportFieldTypes> Headers)
{
if (string.IsNullOrWhiteSpace(Id))
throw new ArgumentNullException("Id");
throw new ArgumentNullException(nameof(Id));
var context = Import_RetrieveContext(Id);
if (context == null)
throw new ArgumentException("The Import Session Id is invalid or the session timed out (60 minutes), try importing again", "Id");
var context = Import_RetrieveContext(Id)
?? throw new ArgumentException("The Import Session Id is invalid or the session timed out (60 minutes), try importing again", nameof(Id));
context.UpdateColumnTypes(Headers);
@@ -777,15 +767,14 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Device.Actions.Import)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImportApply(string Id)
{
if (string.IsNullOrWhiteSpace(Id))
throw new ArgumentNullException("Id");
throw new ArgumentNullException(nameof(Id));
var context = Import_RetrieveContext(Id);
if (context == null)
throw new ArgumentException("The Import Session Id is invalid or the session timed out (60 minutes), try importing again", "Id");
var context = Import_RetrieveContext(Id)
?? throw new ArgumentException("The Import Session Id is invalid or the session timed out (60 minutes), try importing again", nameof(Id));
var status = DeviceImportApplyTask.ScheduleNow(context);
status.SetFinishedUrl(Url.Action(MVC.Device.Import(context.SessionId)));
@@ -895,6 +884,7 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
[DiscoAuthorize(Claims.DiscoAdminAccount)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult MigrateDeviceMacAddressesFromLog()
{
var taskStatus = Disco.Services.Devices.Enrolment.LogMacAddressImportingTask.ScheduleImmediately();
@@ -40,14 +40,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return Redirect($"{Url.Action(MVC.Device.Show(assignment.DeviceSerialNumber))}#DeviceDetailTab-Flags");
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -24,6 +24,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pOnUnassignmentExpression = "onunassignmentexpression";
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
Authorization.Require(Claims.Config.DeviceFlag.Configure);
@@ -68,43 +69,48 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceFlag.Index(flag.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateName(int id, string FlagName = null, bool? redirect = null)
{
return Update(id, pName, FlagName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDescription(int id, string Description = null, bool? redirect = null)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIcon(int id, string Icon = null, bool? redirect = null)
{
return Update(id, pIcon, Icon, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconColour(int id, string IconColour = null, bool? redirect = null)
{
return Update(id, pIconColour, IconColour, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconAndColour(int id, string Icon = null, string IconColour = null, bool redirect = false)
{
try
@@ -124,27 +130,30 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DeviceFlag.Index(DeviceFlag.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnAssignmentExpression(int id, string OnAssignmentExpression = null, bool redirect = false)
{
return Update(id, pOnAssignmentExpression, OnAssignmentExpression, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnUnassignmentExpression(int id, string OnUnassignmentExpression = null, bool redirect = false)
{
return Update(id, pOnUnassignmentExpression, OnUnassignmentExpression, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDevicesLinkedGroup(int id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
@@ -167,17 +176,18 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUserLinkedGroup(int id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
@@ -200,14 +210,14 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
@@ -341,6 +351,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorizeAll(Claims.Config.DeviceFlag.Configure, Claims.Config.DeviceFlag.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -354,7 +365,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new ArgumentException("Invalid Device Flag Id", nameof(id));
}
@@ -363,11 +374,12 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorizeAll(Claims.Config.DeviceFlag.Configure, Claims.Device.Actions.AddFlags, Claims.Device.Actions.RemoveFlags, Claims.Device.ShowFlagAssignments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkAssignDevices(int id, bool Override, string DeviceSerialNumbers = null, string Comments = null)
{
if (id < 0)
@@ -7,6 +7,7 @@ using Disco.Services.Plugins.Features.WarrantyProvider;
using Disco.Services.Web;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
@@ -24,6 +25,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pDefaultRepairProvider = "defaultrepairprovider";
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool redirect = false)
{
Authorization.Require(Claims.Config.DeviceModel.Configure);
@@ -63,19 +65,19 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Device Model Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Model Number");
}
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index(deviceModel.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -120,12 +122,12 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
#region Update Properties
private void UpdateDescription(DeviceModel deviceModel, string Description)
private void UpdateDescription(DeviceModel deviceModel, string description)
{
if (string.IsNullOrWhiteSpace(Description))
if (string.IsNullOrWhiteSpace(description))
deviceModel.Description = null;
else
deviceModel.Description = Description;
deviceModel.Description = description;
Database.SaveChanges();
}
private void UpdateManufacturer(DeviceModel deviceModel, string manufacturer)
@@ -150,15 +152,15 @@ namespace Disco.Web.Areas.API.Controllers
deviceModel.Model = model;
Database.SaveChanges();
}
private void UpdateDefaultPurchaseDate(DeviceModel deviceModel, string DefaultPurchaseDate)
private void UpdateDefaultPurchaseDate(DeviceModel deviceModel, string defaultPurchaseDate)
{
if (string.IsNullOrEmpty(DefaultPurchaseDate))
if (string.IsNullOrEmpty(defaultPurchaseDate))
{
deviceModel.DefaultPurchaseDate = null;
}
else
{
if (DateTime.TryParse(DefaultPurchaseDate, out var d))
if (DateTime.TryParse(defaultPurchaseDate, out var d))
{
deviceModel.DefaultPurchaseDate = d;
}
@@ -169,30 +171,30 @@ namespace Disco.Web.Areas.API.Controllers
}
Database.SaveChanges();
}
private void UpdateDefaultWarrantyProvider(DeviceModel deviceModel, string DefaultWarrantyProvider)
private void UpdateDefaultWarrantyProvider(DeviceModel deviceModel, string defaultWarrantyProvider)
{
if (string.IsNullOrEmpty(DefaultWarrantyProvider))
if (string.IsNullOrEmpty(defaultWarrantyProvider))
{
deviceModel.DefaultWarrantyProvider = null;
}
else
{
// Validate
var WarrantyProvider = Plugins.GetPluginFeature(DefaultWarrantyProvider, typeof(WarrantyProviderFeature));
var WarrantyProvider = Plugins.GetPluginFeature(defaultWarrantyProvider, typeof(WarrantyProviderFeature));
deviceModel.DefaultWarrantyProvider = WarrantyProvider.Id;
}
Database.SaveChanges();
}
private void UpdateDefaultRepairProvider(DeviceModel deviceModel, string DefaultRepairProvider)
private void UpdateDefaultRepairProvider(DeviceModel deviceModel, string defaultRepairProvider)
{
if (string.IsNullOrEmpty(DefaultRepairProvider))
if (string.IsNullOrEmpty(defaultRepairProvider))
{
deviceModel.DefaultRepairProvider = null;
}
else
{
// Validate
var RepairProvider = Plugins.GetPluginFeature(DefaultRepairProvider, typeof(RepairProviderFeature));
var RepairProvider = Plugins.GetPluginFeature(defaultRepairProvider, typeof(RepairProviderFeature));
deviceModel.DefaultRepairProvider = RepairProvider.Id;
}
Database.SaveChanges();
@@ -213,12 +215,7 @@ namespace Disco.Web.Areas.API.Controllers
var deviceModelImage = m.Image();
if (deviceModelImage != null)
return File(deviceModelImage, "image/png");
//if ( m.Image != null)
//{
// return File(m.Image, "image/png");
//}
//else
//{
// DataStore Failed - Use Generic Images
if (m.ModelType != null)
{
@@ -228,13 +225,13 @@ namespace Disco.Web.Areas.API.Controllers
return File(modelTypePath, "image/png");
}
}
//}
}
}
return File(Links.ClientSource.Style.Images.DeviceTypes.Unknown_png, "image/png");
}
[DiscoAuthorize(Claims.Config.DeviceModel.Configure), HttpPost]
[DiscoAuthorize(Claims.Config.DeviceModel.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Image(int id, bool redirect, HttpPostedFileBase Image)
{
if (Image != null && Image.ContentLength > 0)
@@ -248,31 +245,32 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index(dm.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index(dm.Id));
else
return Json("Invalid Image Format", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Image Format");
}
}
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index());
else
return Json("Invalid Device Model Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Device Model Number");
}
if (redirect)
return RedirectToAction(MVC.Config.DeviceModel.Index());
else
return Json("No Image Supplied", JsonRequestBehavior.AllowGet);
return BadRequest("No Image Supplied");
}
#endregion
#region Actions
[DiscoAuthorize(Claims.Config.DeviceModel.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -285,7 +283,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceModel.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Device Model Number");
}
@@ -294,7 +292,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -303,39 +301,38 @@ namespace Disco.Web.Areas.API.Controllers
#region Device Model Components
[DiscoAuthorize(Claims.Config.DeviceModel.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Component(int id)
{
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);
}
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Component Id" }, JsonRequestBehavior.AllowGet);
var dc = Database.DeviceComponents.Include(c => c.JobSubTypes).Where(i => i.Id == id).FirstOrDefault();
if (dc == null)
return BadRequest("Invalid Device Component Id");
return Json(Models.DeviceModel.ComponentModel.FromDeviceComponent(dc));
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentAdd(int? id, string Description, string Cost)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentAdd(int? id, string description, string cost)
{
DeviceModel dm = null;
if (id.HasValue)
{
dm = Database.DeviceModels.Find(id.Value);
if (dm == null)
{
return Json(new Models.DeviceModel.ComponentModel { Result = "Invalid Device Model Id" }, JsonRequestBehavior.AllowGet);
}
return BadRequest("Invalid Device Model Id");
}
if (string.IsNullOrEmpty(Description))
Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out var cost);
if (string.IsNullOrEmpty(description))
description = "?";
if (!string.IsNullOrEmpty(cost) && cost.Contains("$"))
cost = cost.Substring(cost.IndexOf("$") + 1);
decimal.TryParse(cost, out var costValue);
var dc = new DeviceComponent()
{
Description = Description,
Cost = cost
Description = description,
Cost = costValue
};
if (dm != null)
{
@@ -346,77 +343,77 @@ namespace Disco.Web.Areas.API.Controllers
Database.DeviceComponents.Add(dc);
Database.SaveChanges();
return Json(new Models.DeviceModel.ComponentModel { Result = "OK", Component = Models.DeviceModel._ComponentModel.FromDeviceComponent(dc) }, JsonRequestBehavior.AllowGet);
return Json(Models.DeviceModel.ComponentModel.FromDeviceComponent(dc));
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentUpdateJobSubTypes(int id, List<string> JobSubTypes)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentUpdateJobSubTypes(int id, List<string> jobSubTypes)
{
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null)
{
dc.JobSubTypes.Clear();
var dc = Database.DeviceComponents.Include(c => c.JobSubTypes).Where(i => i.Id == id).FirstOrDefault();
if (dc == null)
return BadRequest("Invalid Device Component Id");
if (JobSubTypes != null)
dc.JobSubTypes.Clear();
if (jobSubTypes != null)
{
var jsts = Database.JobSubTypes.Where(jst => jobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id));
foreach (var jst in jsts)
{
var jsts = Database.JobSubTypes.Where(jst => JobSubTypes.Contains(jst.JobTypeId + "_" + jst.Id));
foreach (var jst in jsts)
{
dc.JobSubTypes.Add(jst);
}
dc.JobSubTypes.Add(jst);
}
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);
Database.SaveChanges();
return Json(Models.DeviceModel.ComponentModel.FromDeviceComponent(dc));
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
public virtual ActionResult ComponentUpdate(int id, string Description, string Cost)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentUpdate(int id, string description, string cost)
{
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null)
{
var dc = Database.DeviceComponents.Include(c => c.JobSubTypes).Where(i => i.Id == id).FirstOrDefault();
if (dc == null)
return BadRequest("Invalid Device Component Id");
if (string.IsNullOrEmpty(Description))
Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out var cost);
if (string.IsNullOrEmpty(description))
description = "?";
if (!string.IsNullOrEmpty(cost) && cost.Contains("$"))
cost = cost.Substring(cost.IndexOf("$") + 1);
decimal.TryParse(cost, out var costValue);
dc.Description = Description;
dc.Cost = cost;
dc.Description = description;
dc.Cost = costValue;
Database.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);
return Json(Models.DeviceModel.ComponentModel.FromDeviceComponent(dc));
}
[DiscoAuthorize(Claims.Config.DeviceModel.ConfigureComponents)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentRemove(int id)
{
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(c => c.Id == id).FirstOrDefault();
if (dc != null)
{
dc.JobSubTypes.Clear();
Database.DeviceComponents.Remove(dc);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
}
return Json("Invalid Device Component Id", JsonRequestBehavior.AllowGet);
var dc = Database.DeviceComponents.Include(c => c.JobSubTypes).Where(c => c.Id == id).FirstOrDefault();
if (dc == null)
return BadRequest("Invalid Device Component Id");
dc.JobSubTypes.Clear();
Database.DeviceComponents.Remove(dc);
Database.SaveChanges();
return Ok();
}
#endregion
#region Index
[DiscoAuthorize(Claims.Config.DeviceModel.Show)]
[DiscoAuthorizeAny(Claims.Config.DeviceModel.Show, Claims.Config.Enrolment.ShowStatus)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Index()
{
var deviceModels = Database.DeviceModels.ToArray().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToArray();
return Json(deviceModels, JsonRequestBehavior.AllowGet);
var deviceModels = Database.DeviceModels.AsEnumerable().Select(dm => Models.DeviceModel._DeviceModel.FromDeviceModel(dm)).ToList();
return Json(deviceModels);
}
#endregion
@@ -40,6 +40,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pAssignedUsersLinkedGroup = "assigneduserslinkedgroup";
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
Authorization.Require(Claims.Config.DeviceProfile.Configure);
@@ -114,62 +115,70 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(deviceProfile.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDescription(int id, string Description = null, bool? redirect = null)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateName(int id, string ProfileName = null, bool? redirect = null)
{
return Update(id, pName, ProfileName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateShortName(int id, string ShortName = null, bool? redirect = null)
{
return Update(id, pShortName, ShortName, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDistributionType(int id, string DistributionType = null, bool? redirect = null)
{
return Update(id, pDistributionType, DistributionType, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateCertificateProviders(int id, string CertificateProviders = null, bool? redirect = null)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateCertificateProviders(int id, string certificateProviders = null, bool? redirect = null)
{
return Update(id, pCertificateProviders, CertificateProviders, redirect);
return Update(id, pCertificateProviders, certificateProviders, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateCertificateAuthorityProviders(int id, string CertificateAuthorityProviders = null, bool? redirect = null)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateCertificateAuthorityProviders(int id, string certificateAuthorityProviders = null, bool? redirect = null)
{
return Update(id, pCertificateAuthorityProviders, CertificateAuthorityProviders, redirect);
return Update(id, pCertificateAuthorityProviders, certificateAuthorityProviders, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
public virtual ActionResult UpdateWirelessProfileProviders(int id, string WirelessProfileProviders = null, bool? redirect = null)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWirelessProfileProviders(int id, string wirelessProfileProviders = null, bool? redirect = null)
{
return Update(id, pWirelessProfileProviders, WirelessProfileProviders, redirect);
return Update(id, pWirelessProfileProviders, wirelessProfileProviders, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure), HttpPost, ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOrganisationalUnit(int id, string OrganisationalUnit = null, bool enforce = false, bool? redirect = null)
{
var updateResult = Update(id, pOrganisationalUnit, OrganisationalUnit, redirect);
@@ -187,13 +196,14 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDefaultOrganisationAddress(int id, string DefaultOrganisationAddress = null, bool? redirect = null)
{
return Update(id, pDefaultOrganisationAddress, DefaultOrganisationAddress, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DeviceProfile.Configure, Claims.Config.DeviceProfile.ConfigureComputerNameTemplate)]
[ValidateAntiForgeryToken]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateComputerNameTemplate(int id, string ComputerNameTemplate = null, bool? redirect = null)
{
var deviceProfile = Database.DeviceProfiles.Find(id);
@@ -219,11 +229,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.GetValueOrDefault(false))
return RedirectToAction(MVC.Config.DeviceProfile.Index(deviceProfile.Id));
else
return Json("OK");
return Ok();
}
[DiscoAuthorizeAll(Claims.Config.DeviceProfile.Configure, Claims.Config.DeviceProfile.ConfigureComputerNameTemplate)]
[ValidateAntiForgeryToken]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult TestComputerNameTemplate(int id, string ComputerNameTemplate = null, string UserSpecifiedDeviceSerialNumber = null)
{
Database.Configuration.LazyLoadingEnabled = true;
@@ -317,36 +327,42 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateEnforceComputerNameConvention(int id, string EnforceComputerNameConvention = null, bool? redirect = null)
{
return Update(id, pEnforceComputerNameConvention, EnforceComputerNameConvention, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateEnforceOrganisationalUnit(int id, string EnforceOrganisationalUnit = null, bool? redirect = null)
{
return Update(id, pEnforceOrganisationalUnit, EnforceOrganisationalUnit, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateProvisionADAccount(int id, string ProvisionADAccount = null, bool? redirect = null)
{
return Update(id, pProvisionADAccount, ProvisionADAccount, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUserLocalAdmin(int id, string AssignedUserLocalAdmin = null, bool? redirect = null)
{
return Update(id, pAssignedUserLocalAdmin, AssignedUserLocalAdmin, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAllowUntrustedReimageJobEnrolment(int id, string AllowUntrustedReimageJobEnrolment = null, bool? redirect = null)
{
return Update(id, pAllowUntrustedReimageJobEnrolment, AllowUntrustedReimageJobEnrolment, redirect);
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDevicesLinkedGroup(int id, string GroupId = null, bool redirect = false)
{
try
@@ -368,17 +384,18 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUsersLinkedGroup(int id, string GroupId = null, bool redirect = false)
{
try
@@ -400,49 +417,49 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
#region Update Properties
private void UpdateDescription(DeviceProfile deviceProfile, string Description)
private void UpdateDescription(DeviceProfile deviceProfile, string description)
{
if (string.IsNullOrWhiteSpace(Description))
if (string.IsNullOrWhiteSpace(description))
deviceProfile.Description = null;
else
deviceProfile.Description = Description;
deviceProfile.Description = description;
Database.SaveChanges();
}
private void UpdateName(DeviceProfile deviceProfile, string Name)
private void UpdateName(DeviceProfile deviceProfile, string name)
{
if (string.IsNullOrWhiteSpace(Name))
if (string.IsNullOrWhiteSpace(name))
throw new Exception("Profile name cannot be empty");
else
deviceProfile.Name = Name;
deviceProfile.Name = name;
Database.SaveChanges();
}
private void UpdateShortName(DeviceProfile deviceProfile, string ShortName)
private void UpdateShortName(DeviceProfile deviceProfile, string shortName)
{
if (string.IsNullOrWhiteSpace(ShortName))
if (string.IsNullOrWhiteSpace(shortName))
throw new Exception("Profile short name cannot be empty");
else
deviceProfile.ShortName = ShortName;
deviceProfile.ShortName = shortName;
Database.SaveChanges();
}
private void UpdateDistributionType(DeviceProfile deviceProfile, string DistributionType)
private void UpdateDistributionType(DeviceProfile deviceProfile, string distributionType)
{
if (int.TryParse(DistributionType, out var iDt))
if (int.TryParse(distributionType, out var iDt))
{
deviceProfile.DistributionType = (DeviceProfile.DistributionTypes)iDt;
Database.SaveChanges();
@@ -451,9 +468,9 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Distribution Type Number");
}
private void UpdateCertificateProviders(DeviceProfile deviceProfile, string CertificateProviderIds)
private void UpdateCertificateProviders(DeviceProfile deviceProfile, string certificateProviderIds)
{
if (string.IsNullOrWhiteSpace(CertificateProviderIds))
if (string.IsNullOrWhiteSpace(certificateProviderIds))
{
deviceProfile.CertificateProviders = null;
}
@@ -461,7 +478,7 @@ namespace Disco.Web.Areas.API.Controllers
{
// Validate
var validatedProviders = new List<PluginFeatureManifest>();
foreach (var certificateProviderId in CertificateProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
foreach (var certificateProviderId in certificateProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var featureManifest = Plugins.GetPluginFeature(certificateProviderId, typeof(CertificateProviderFeature));
if (featureManifest == null)
@@ -487,9 +504,9 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges();
}
private void UpdateCertificateAuthorityProviders(DeviceProfile deviceProfile, string CertificateAuthorityProviderIds)
private void UpdateCertificateAuthorityProviders(DeviceProfile deviceProfile, string certificateAuthorityProviderIds)
{
if (string.IsNullOrWhiteSpace(CertificateAuthorityProviderIds))
if (string.IsNullOrWhiteSpace(certificateAuthorityProviderIds))
{
deviceProfile.CertificateAuthorityProviders = null;
}
@@ -497,7 +514,7 @@ namespace Disco.Web.Areas.API.Controllers
{
// Validate
var validatedProviders = new List<PluginFeatureManifest>();
foreach (var certificateAuthorityProviderId in CertificateAuthorityProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
foreach (var certificateAuthorityProviderId in certificateAuthorityProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var featureManifest = Plugins.GetPluginFeature(certificateAuthorityProviderId, typeof(CertificateAuthorityProviderFeature));
if (featureManifest == null)
@@ -523,9 +540,9 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges();
}
private void UpdateWirelessProfileProviders(DeviceProfile deviceProfile, string WirelessProfileProviderIds)
private void UpdateWirelessProfileProviders(DeviceProfile deviceProfile, string wirelessProfileProviderIds)
{
if (string.IsNullOrWhiteSpace(WirelessProfileProviderIds))
if (string.IsNullOrWhiteSpace(wirelessProfileProviderIds))
{
deviceProfile.WirelessProfileProviders = null;
}
@@ -533,7 +550,7 @@ namespace Disco.Web.Areas.API.Controllers
{
// Validate
var validatedProviders = new List<PluginFeatureManifest>();
foreach (var wirelessProfileProviderId in WirelessProfileProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
foreach (var wirelessProfileProviderId in wirelessProfileProviderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var featureManifest = Plugins.GetPluginFeature(wirelessProfileProviderId, typeof(WirelessProfileProviderFeature));
if (featureManifest == null)
@@ -559,28 +576,28 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges();
}
private void UpdateOrganisationalUnit(DeviceProfile deviceProfile, string OrganisationalUnit)
private void UpdateOrganisationalUnit(DeviceProfile deviceProfile, string organisationalUnit)
{
if (string.IsNullOrWhiteSpace(OrganisationalUnit))
OrganisationalUnit = ActiveDirectory.Context.PrimaryDomain.DefaultComputerContainer;
if (string.IsNullOrWhiteSpace(organisationalUnit))
organisationalUnit = ActiveDirectory.Context.PrimaryDomain.DefaultComputerContainer;
if (OrganisationalUnit != deviceProfile.OrganisationalUnit)
if (organisationalUnit != deviceProfile.OrganisationalUnit)
{
deviceProfile.OrganisationalUnit = OrganisationalUnit;
deviceProfile.OrganisationalUnit = organisationalUnit;
Database.SaveChanges();
}
}
private void UpdateDefaultOrganisationAddress(DeviceProfile deviceProfile, string DefaultOrganisationAddress)
private void UpdateDefaultOrganisationAddress(DeviceProfile deviceProfile, string defaultOrganisationAddress)
{
if (string.IsNullOrEmpty(DefaultOrganisationAddress))
if (string.IsNullOrEmpty(defaultOrganisationAddress))
{
deviceProfile.DefaultOrganisationAddress = null;
}
else
{
// Validate
if (int.TryParse(DefaultOrganisationAddress, out var daoId))
if (int.TryParse(defaultOrganisationAddress, out var daoId))
{
var oa = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId);
if (oa != null)
@@ -602,9 +619,9 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges();
}
private void UpdateEnforceComputerNameConvention(DeviceProfile deviceProfile, string EnforceComputerNameConvention)
private void UpdateEnforceComputerNameConvention(DeviceProfile deviceProfile, string enforceComputerNameConvention)
{
if (bool.TryParse(EnforceComputerNameConvention, out var bValue))
if (bool.TryParse(enforceComputerNameConvention, out var bValue))
{
deviceProfile.EnforceComputerNameConvention = bValue;
@@ -614,9 +631,9 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Value");
}
private void UpdateEnforceOrganisationalUnit(DeviceProfile deviceProfile, string EnforceOrganisationalUnit)
private void UpdateEnforceOrganisationalUnit(DeviceProfile deviceProfile, string enforceOrganisationalUnit)
{
if (bool.TryParse(EnforceOrganisationalUnit, out var bValue))
if (bool.TryParse(enforceOrganisationalUnit, out var bValue))
{
deviceProfile.EnforceOrganisationalUnit = bValue;
@@ -626,9 +643,9 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Value");
}
private void UpdateProvisionADAccount(DeviceProfile deviceProfile, string ProvisionADAccount)
private void UpdateProvisionADAccount(DeviceProfile deviceProfile, string provisionADAccount)
{
if (bool.TryParse(ProvisionADAccount, out var bValue))
if (bool.TryParse(provisionADAccount, out var bValue))
{
deviceProfile.ProvisionADAccount = bValue;
@@ -638,9 +655,9 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Value");
}
private void UpdateAssignedUserLocalAdmin(DeviceProfile deviceProfile, string AssignedUserLocalAdmin)
private void UpdateAssignedUserLocalAdmin(DeviceProfile deviceProfile, string assignedUserLocalAdmin)
{
if (bool.TryParse(AssignedUserLocalAdmin, out var bValue))
if (bool.TryParse(assignedUserLocalAdmin, out var bValue))
{
deviceProfile.AssignedUserLocalAdmin = bValue;
@@ -650,9 +667,9 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Value");
}
private void UpdateAllowUntrustedReimageJobEnrolment(DeviceProfile deviceProfile, string AllowUntrustedReimageJobEnrolment)
private void UpdateAllowUntrustedReimageJobEnrolment(DeviceProfile deviceProfile, string allowUntrustedReimageJobEnrolment)
{
if (bool.TryParse(AllowUntrustedReimageJobEnrolment, out var bValue))
if (bool.TryParse(allowUntrustedReimageJobEnrolment, out var bValue))
{
deviceProfile.AllowUntrustedReimageJobEnrolment = bValue;
@@ -662,16 +679,16 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Boolean Value");
}
private ScheduledTaskStatus UpdateDevicesLinkedGroup(DeviceProfile DeviceProfile, string DevicesLinkedGroup)
private ScheduledTaskStatus UpdateDevicesLinkedGroup(DeviceProfile deviceProfile, string devicesLinkedGroup)
{
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceProfileDevicesManagedGroup.GetKey(DeviceProfile), DevicesLinkedGroup, null);
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceProfileDevicesManagedGroup.GetKey(deviceProfile), devicesLinkedGroup, null);
if (DeviceProfile.DevicesLinkedGroup != configJson)
if (deviceProfile.DevicesLinkedGroup != configJson)
{
DeviceProfile.DevicesLinkedGroup = configJson;
deviceProfile.DevicesLinkedGroup = configJson;
Database.SaveChanges();
var managedGroup = DeviceProfileDevicesManagedGroup.Initialize(DeviceProfile);
var managedGroup = DeviceProfileDevicesManagedGroup.Initialize(deviceProfile);
if (managedGroup != null) // Sync Group
return ADManagedGroupsSyncTask.ScheduleSync(managedGroup);
}
@@ -679,16 +696,16 @@ namespace Disco.Web.Areas.API.Controllers
return null;
}
private ScheduledTaskStatus UpdateAssignedUsersLinkedGroup(DeviceProfile DeviceProfile, string AssignedUsersLinkedGroup)
private ScheduledTaskStatus UpdateAssignedUsersLinkedGroup(DeviceProfile deviceProfile, string assignedUsersLinkedGroup)
{
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceProfileAssignedUsersManagedGroup.GetKey(DeviceProfile), AssignedUsersLinkedGroup, null);
var configJson = ADManagedGroup.ValidConfigurationToJson(DeviceProfileAssignedUsersManagedGroup.GetKey(deviceProfile), assignedUsersLinkedGroup, null);
if (DeviceProfile.AssignedUsersLinkedGroup != configJson)
if (deviceProfile.AssignedUsersLinkedGroup != configJson)
{
DeviceProfile.AssignedUsersLinkedGroup = configJson;
deviceProfile.AssignedUsersLinkedGroup = configJson;
Database.SaveChanges();
var managedGroup = DeviceProfileAssignedUsersManagedGroup.Initialize(DeviceProfile);
var managedGroup = DeviceProfileAssignedUsersManagedGroup.Initialize(deviceProfile);
if (managedGroup != null) // Sync Group
return ADManagedGroupsSyncTask.ScheduleSync(managedGroup);
}
@@ -700,6 +717,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DeviceProfile.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -712,7 +730,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Device Profile Number");
}
@@ -721,7 +739,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -730,6 +748,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Defaults
[DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Default(int id, bool? redirect = null)
{
try
@@ -742,7 +761,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Device Profile Number");
}
@@ -751,11 +770,12 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DeviceProfile.ConfigureDefaults)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DefaultAddDeviceOffline(int id, bool? redirect = false)
{
try
@@ -778,14 +798,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DeviceProfile.Index(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -21,7 +21,7 @@ using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
@@ -40,6 +40,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pIsHidden = "ishidden";
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false)
{
try
@@ -97,18 +98,19 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(resultTask.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Upload), HttpGet]
[DiscoAuthorize(Claims.Config.DocumentTemplate.Upload)]
[HttpGet]
public virtual ActionResult Template(string id)
{
if (string.IsNullOrEmpty(id))
@@ -128,7 +130,8 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Upload, Claims.Config.DocumentTemplate.Configure), HttpPost]
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Upload, Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Template(string id, bool redirect, HttpPostedFileBase Template)
{
try
@@ -144,18 +147,19 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(documentTemplate.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Show), HttpGet]
[DiscoAuthorize(Claims.Config.DocumentTemplate.Show)]
[HttpGet]
public virtual ActionResult TemplatePreview(string id)
{
if (string.IsNullOrEmpty(id))
@@ -180,41 +184,49 @@ namespace Disco.Web.Areas.API.Controllers
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
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)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateFilterExpression(string id, string FilterExpression = null, bool redirect = false)
{
return Update(id, pFilterExpression, FilterExpression, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnGenerateExpression(string id, string OnGenerateExpression = null, bool redirect = false)
{
return Update(id, pOnGenerateExpression, OnGenerateExpression, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnImportAttachmentExpression(string id, string OnImportAttachmentExpression = null, bool redirect = false)
{
return Update(id, pOnImportAttachmentExpression, OnImportAttachmentExpression, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateFlattenForm(string id, string FlattenForm = null, bool redirect = false)
{
return Update(id, pFlattenForm, FlattenForm, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIsHidden(string id, string IsHidden = null, bool redirect = false)
{
return Update(id, pIsHidden, IsHidden, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateScope(string id, string Scope = null, bool redirect = false)
{
return Update(id, pScope, Scope, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateJobSubTypes(string id, List<string> JobSubTypes = null, bool redirect = false)
{
try
@@ -228,19 +240,20 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(documentTemplate.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDevicesLinkedGroup(string id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
@@ -262,18 +275,19 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateUsersLinkedGroup(string id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
@@ -295,14 +309,14 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
@@ -493,7 +507,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages), OutputCache(NoStore = true, Duration = 0)]
public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber)
public virtual ActionResult ImporterThumbnail(Guid SessionId, int PageNumber)
{
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages");
var filename = Path.Combine(dataStoreSessionPagesCacheLocation, $"{SessionId}-{PageNumber}");
@@ -504,6 +518,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImporterUndetectedFiles()
{
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
@@ -577,47 +592,51 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
[HttpGet]
public virtual ActionResult ImporterUndetectedFile(string id, bool? Source, bool? Thumbnail)
{
if (!string.IsNullOrEmpty(id))
if (!Regex.IsMatch(id, @"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_\d+$"))
return BadRequest("Invalid page identifier");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
if (Source.HasValue && Source.Value)
{
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
if (Source.HasValue && Source.Value)
var filename = Path.Combine(undetectedLocation, $"{id}.pdf");
if (System.IO.File.Exists(filename))
return File(filename, DocumentTemplate.PdfMimeType);
else
return HttpNotFound();
}
else
{
if (Thumbnail.HasValue && Thumbnail.Value)
{
var filename = Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
var filename = Path.Combine(undetectedLocation, $"{id}_thumbnail.png");
if (System.IO.File.Exists(filename))
return File(filename, DocumentTemplate.PdfMimeType);
return File(filename, "image/png");
else
return HttpNotFound();
return File(Links.ClientSource.Style.Images.Status.fileBroken256_png, "image/png");
}
else
{
if (Thumbnail.HasValue && Thumbnail.Value)
{
var filename = Path.Combine(undetectedLocation, string.Concat(id, "_thumbnail.png"));
if (System.IO.File.Exists(filename))
return File(filename, "image/png");
else
return File(Links.ClientSource.Style.Images.Status.fileBroken256_png, "image/png");
}
var filename = Path.Combine(undetectedLocation, $"{id}.jpg");
if (System.IO.File.Exists(filename))
return File(filename, "image/jpeg");
else
{
var filename = Path.Combine(undetectedLocation, string.Concat(id, ".jpg"));
if (System.IO.File.Exists(filename))
return File(filename, "image/jpeg");
else
return File(Links.ClientSource.Style.Images.Status.fileBroken256_png, "image/png");
}
return File(Links.ClientSource.Style.Images.Status.fileBroken256_png, "image/png");
}
}
return HttpNotFound();
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImporterUndetectedAssign(string id, string DocumentTemplateId, string DataId)
{
if (!Regex.IsMatch(id, @"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_\d+$"))
return BadRequest("Invalid page identifier");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
var filename = Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
var filename = Path.Combine(undetectedLocation, $"{id}.pdf");
var identifier = DocumentUniqueIdentifier.Create(Database, DocumentTemplateId, DataId, UserService.CurrentUser.UserId, DateTime.Now, 0);
if (Disco.Services.Documents.AttachmentImport.Importer.ImportPdfAttachment(identifier, Database, filename) != null)
@@ -626,48 +645,53 @@ namespace Disco.Web.Areas.API.Controllers
System.IO.File.Delete(filename);
// Delete Thumbnail/Preview
var thumbnailFilename = Path.Combine(undetectedLocation, string.Concat(id, "_thumbnail.png"));
var thumbnailFilename = Path.Combine(undetectedLocation, $"{id}_thumbnail.png");
if (System.IO.File.Exists(thumbnailFilename))
System.IO.File.Delete(thumbnailFilename);
var previewFilename = Path.Combine(undetectedLocation, string.Concat(id, ".jpg"));
var previewFilename = Path.Combine(undetectedLocation, $"{id}.jpg");
if (System.IO.File.Exists(previewFilename))
System.IO.File.Delete(previewFilename);
return Json("OK");
return Ok();
}
else
{
return Json("Unable to Import File with the supplied parameters");
return BadRequest("Unable to Import File with the supplied parameters");
}
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.UndetectedPages)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImporterUndetectedDelete(string id)
{
if (!Regex.IsMatch(id, @"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_\d+$"))
return BadRequest("Invalid page identifier");
var undetectedLocation = DataStore.CreateLocation(Database, "DocumentDropBox_Unassigned");
var filename = Path.Combine(undetectedLocation, string.Concat(id, ".pdf"));
var filename = Path.Combine(undetectedLocation, $"{id}.pdf");
if (System.IO.File.Exists(filename))
{
// Delete File
System.IO.File.Delete(filename);
// Delete Thumbnail/Preview
var thumbnailFilename = Path.Combine(undetectedLocation, string.Concat(id, "_thumbnail.png"));
var thumbnailFilename = Path.Combine(undetectedLocation, $"{id}_thumbnail.png");
if (System.IO.File.Exists(thumbnailFilename))
System.IO.File.Delete(thumbnailFilename);
var previewFilename = Path.Combine(undetectedLocation, string.Concat(id, ".jpg"));
var previewFilename = Path.Combine(undetectedLocation, $"{id}.jpg");
if (System.IO.File.Exists(previewFilename))
System.IO.File.Delete(previewFilename);
return Json("OK");
return Ok();
}
else
{
return Json("File Not Found");
return BadRequest("File Not Found");
}
}
[DiscoAuthorizeAll(Claims.Config.DeviceModel.Show, Claims.Config.DocumentTemplate.BulkGenerate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerateDeviceModel(string id, int deviceGroupId)
{
var template = Database.DocumentTemplates.FirstOrDefault(t => t.Id == id);
@@ -701,6 +725,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorizeAll(Claims.Config.DeviceProfile.Show, Claims.Config.DocumentTemplate.BulkGenerate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerateDeviceProfile(string id, int deviceGroupId)
{
var template = Database.DocumentTemplates.FirstOrDefault(t => t.Id == id);
@@ -734,6 +759,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorizeAll(Claims.Config.DeviceBatch.Show, Claims.Config.DocumentTemplate.BulkGenerate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerateDeviceBatch(string id, int deviceGroupId)
{
var template = Database.DocumentTemplates.FirstOrDefault(t => t.Id == id);
@@ -767,11 +793,12 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.BulkGenerate)]
public virtual ActionResult BulkGenerate(string id, string DataIds = null, bool InsertBlankPage = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerate(string id, string dataIds = null, bool insertBlankPage = false)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
if (string.IsNullOrEmpty(DataIds))
if (string.IsNullOrEmpty(dataIds))
throw new ArgumentNullException("DataIds");
var documentTemplate = Database.DocumentTemplates.Find(id);
if (documentTemplate == null)
@@ -792,35 +819,34 @@ namespace Disco.Web.Areas.API.Controllers
throw new InvalidOperationException("Unknown DocumentType Scope");
}
var dataIds = DataIds.Split(new string[] { Environment.NewLine, ",", ";" }, StringSplitOptions.RemoveEmptyEntries).Select(d => d.Trim()).Where(d => !string.IsNullOrEmpty(d)).ToList();
var ids = dataIds.Split(new string[] { Environment.NewLine, ",", ";" }, StringSplitOptions.RemoveEmptyEntries).Select(d => d.Trim()).Where(d => !string.IsNullOrEmpty(d)).ToList();
var timeStamp = DateTime.Now;
var taskStatus = DocumentBulkGenerateTask.ScheduleNow(BI.Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate, documentTemplate, UserService.CurrentUser, timeStamp, InsertBlankPage, dataIds);
var taskStatus = DocumentBulkGenerateTask.ScheduleNow(BI.Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate, documentTemplate, UserService.CurrentUser, timeStamp, insertBlankPage, ids);
var fileName = $"{documentTemplate.Id}_Bulk_{timeStamp:yyyyMMdd-HHmmss}.pdf";
taskStatus.SetFinishedUrl(Url.Action(MVC.Config.DocumentTemplate.Index(documentTemplate.Id, taskStatus.SessionId, fileName)));
taskStatus.SetFinishedUrl(Url.Action(MVC.Config.DocumentTemplate.Index(documentTemplate.Id, Guid.Parse(taskStatus.SessionId), fileName)));
if (!taskStatus.WaitUntilFinished(TimeSpan.FromSeconds(1)))
return RedirectToAction(MVC.Config.Logging.TaskStatus(taskStatus.SessionId));
var stream = DocumentBulkGenerateTask.GetCached(Database, taskStatus.SessionId);
var stream = DocumentBulkGenerateTask.GetCached(Database, Guid.Parse(taskStatus.SessionId));
return File(stream, "application/pdf", fileName);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.BulkGenerate)]
public virtual ActionResult BulkGenerateDownload(string id, string fileName)
public virtual ActionResult BulkGenerateDownload(Guid id, string fileName)
{
var stream = DocumentBulkGenerateTask.GetCached(Database, id);
return File(stream, "application/pdf", fileName);
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.BulkGenerate, Claims.User.Actions.GenerateDocuments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerateAddUsers(string userIds)
{
if (string.IsNullOrWhiteSpace(userIds))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var dataIds = userIds.Split(new string[] { Environment.NewLine, ",", ";" }, StringSplitOptions.RemoveEmptyEntries).Select(d => d.Trim()).Where(d => !string.IsNullOrEmpty(d)).ToList();
var results = new List<BulkGenerateUserModel>(dataIds.Count);
@@ -893,7 +919,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddGroupMembers(string groupId)
{
if (string.IsNullOrWhiteSpace(groupId))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
var accountId = ActiveDirectory.ParseDomainAccountId(groupId);
@@ -954,7 +980,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddUserFlag(int flagId)
{
if (flagId <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
@@ -1008,7 +1034,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddDeviceProfile(int deviceProfileId)
{
if (deviceProfileId <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
@@ -1062,7 +1088,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddDeviceBatch(int deviceBatchId)
{
if (deviceBatchId <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
@@ -1116,7 +1142,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddDocumentAttachment(string documentTemplateId, DateTime? threshold)
{
if (string.IsNullOrWhiteSpace(documentTemplateId))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
@@ -1229,7 +1255,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateGetUserDetailValues(string key)
{
if (string.IsNullOrWhiteSpace(key))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = Database.UserDetails.Where(d => d.Scope == "Details" && d.Key == key).Select(d => d.Value).Distinct().ToList();
@@ -1241,7 +1267,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult BulkGenerateAddUserDetail(string key, string value)
{
if (string.IsNullOrWhiteSpace(key))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return BadRequest();
var results = new List<BulkGenerateUserModel>();
@@ -1279,9 +1305,10 @@ namespace Disco.Web.Areas.API.Controllers
return Json(results);
}
public virtual ActionResult Generate(string id, string TargetId)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Generate(string id, string targetId)
{
Disco.Services.DocumentTemplateExtensions.GetTemplateAndTarget(Database, Authorization, id, TargetId, out var template, out var target, out _);
Disco.Services.DocumentTemplateExtensions.GetTemplateAndTarget(Database, Authorization, id, targetId, out var template, out var target, out _);
// generate document
var timestamp = DateTime.Now;
@@ -1296,6 +1323,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(string id, bool? redirect = false)
{
try
@@ -1308,7 +1336,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Document Template Id");
}
@@ -1317,12 +1345,12 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[HttpPost, ValidateAntiForgeryToken]
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult RemoveOnImportUserFlagRule([Required] string id, Guid? ruleId = null)
{
try
@@ -1334,16 +1362,16 @@ namespace Disco.Web.Areas.API.Controllers
template.RemoveOnImportUserFlagRule(Database, ruleId.Value);
return new HttpStatusCodeResult(HttpStatusCode.OK);
return Ok();
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message);
return BadRequest(ex.Message);
}
}
[HttpPost, ValidateAntiForgeryToken]
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AddOnImportUserFlagRule([Required] string id, bool? addFlag = null, int? userFlagId = null, string comments = null)
{
try
@@ -1379,14 +1407,14 @@ namespace Disco.Web.Areas.API.Controllers
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message);
return BadRequest(ex.Message);
}
}
#endregion
#region Handlers
[HttpPost]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult GenerateDocumentHandlerUi(string templateId, string targetId, string handlerId)
{
Disco.Services.DocumentTemplateExtensions.GetTemplateAndTarget(Database, Authorization, templateId, targetId, out var template, out var target, out var targetUser);
@@ -1403,15 +1431,13 @@ namespace Disco.Web.Areas.API.Controllers
if (handlerPartialView == null)
throw new NotSupportedException("Handler does not have a Generation Options UI");
var model = handler.GetGenerationOptionsUiModel(template, target, targetUser, CurrentUser);
return this.PrecompiledPartialView(handlerPartialView, model);
}
}
[HttpPost]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DocumentHandlers(string templateId, string targetId)
{
Disco.Services.DocumentTemplateExtensions.GetTemplateAndTarget(Database, Authorization, templateId, targetId, out var template, out var target, out _);
@@ -24,6 +24,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pInsertBlankPages = "insertblankpages";
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(string id, string key, string value = null, bool redirect = false)
{
try
@@ -69,24 +70,26 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.ShowPackage(package.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDescription(string id, string Description = null, bool redirect = false)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDocumentTemplates(string id, List<string> DocumentTemplates = null, bool redirect = false)
{
try
@@ -104,43 +107,49 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.ShowPackage(package.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateFilterExpression(string id, string FilterExpression = null, bool redirect = false)
{
return Update(id, pFilterExpression, FilterExpression, redirect);
}
[DiscoAuthorizeAll(Claims.Config.DocumentTemplate.Configure, Claims.Config.DocumentTemplate.ConfigureFilterExpression)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnGenerateExpression(string id, string OnGenerateExpression = null, bool redirect = false)
{
return Update(id, pOnGenerateExpression, OnGenerateExpression, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIsHidden(string id, string IsHidden = null, bool redirect = false)
{
return Update(id, pIsHidden, IsHidden, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsertBlankPages(string id, string InsertBlankPages = null, bool redirect = false)
{
return Update(id, pInsertBlankPages, InsertBlankPages, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateScope(string id, string Scope = null, bool redirect = false)
{
return Update(id, pScope, Scope, redirect);
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateJobSubTypes(string id, List<string> JobSubTypes = null, bool redirect = false)
{
try
@@ -158,32 +167,31 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.DocumentTemplate.ShowPackage(package.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
#region Update Properties
private void UpdateDescription(DocumentTemplatePackage Package, string Description)
private void UpdateDescription(DocumentTemplatePackage Package, string description)
{
if (!string.IsNullOrWhiteSpace(Description))
if (string.IsNullOrWhiteSpace(description))
throw new Exception("Invalid Description");
description = description.Trim();
if (Package.Description != description)
{
var description = Description.Trim();
if (Package.Description != description)
{
Package.Description = description;
DocumentTemplatePackages.UpdatePackage(Package);
}
Package.Description = description;
DocumentTemplatePackages.UpdatePackage(Package);
}
throw new Exception("Invalid Description");
}
private void UpdateDocumentTemplates(DocumentTemplatePackage Package, List<string> DocumentTemplates)
{
@@ -349,12 +357,13 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.DocumentTemplate.BulkGenerate)]
public virtual ActionResult BulkGenerate(string id, string DataIds = null, bool InsertBlankPage = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkGenerate(string id, string dataIds = null)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(DataIds))
throw new ArgumentNullException(nameof(DataIds));
if (string.IsNullOrEmpty(dataIds))
throw new ArgumentNullException(nameof(dataIds));
var package = DocumentTemplatePackages.GetPackage(id);
@@ -376,19 +385,20 @@ namespace Disco.Web.Areas.API.Controllers
throw new InvalidOperationException("Unknown DocumentType Scope");
}
var dataIds = DataIds.Split(new string[] { Environment.NewLine, ",", ";" }, StringSplitOptions.RemoveEmptyEntries).Select(d => d.Trim()).Where(d => !string.IsNullOrEmpty(d)).ToList();
var ids = dataIds.Split(new string[] { Environment.NewLine, ",", ";" }, StringSplitOptions.RemoveEmptyEntries).Select(d => d.Trim()).Where(d => !string.IsNullOrEmpty(d)).ToList();
var timeStamp = DateTime.Now;
var pdf = package.GeneratePdfPackageBulk(Database, UserService.CurrentUser, timeStamp, InsertBlankPage, dataIds);
var pdf = package.GeneratePdfPackageBulk(Database, UserService.CurrentUser, timeStamp, null, ids);
return File(pdf, "application/pdf", $"{package.Id}_Bulk_{timeStamp:yyyyMMdd-HHmmss}.pdf");
}
public virtual ActionResult Generate(string id, string TargetId)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Generate(string id, string targetId)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrWhiteSpace(TargetId))
throw new ArgumentNullException(nameof(TargetId));
if (string.IsNullOrWhiteSpace(targetId))
throw new ArgumentNullException(nameof(targetId));
var package = DocumentTemplatePackages.GetPackage(id);
if (package == null)
@@ -410,9 +420,9 @@ namespace Disco.Web.Areas.API.Controllers
}
// resolve target
var target = package.ResolveScopeTarget(Database, TargetId);
var target = package.ResolveScopeTarget(Database, targetId);
if (target == null)
throw new ArgumentException("Target not found", nameof(TargetId));
throw new ArgumentException("Target not found", nameof(targetId));
var timestamp = DateTime.Now;
var document = default(Stream);
@@ -426,6 +436,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.DocumentTemplate.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(string id, bool? redirect = false)
{
try
@@ -445,7 +456,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.DocumentTemplate.Index(null));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Document Template Package Id");
}
@@ -454,7 +465,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -8,9 +8,8 @@ namespace Disco.Web.Areas.API.Controllers
{
public partial class EnrolmentController : AuthorizedDatabaseController
{
[HttpPost]
[ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Device.Actions.EnrolDevices)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ResolveSessionPending(string sessionId, bool approve, int? deviceProfileId, int? deviceBatchId, string reason)
{
if (approve && deviceProfileId == null)
@@ -18,11 +17,11 @@ namespace Disco.Web.Areas.API.Controllers
WindowsDeviceEnrolment.ResolvePendingEnrolment(sessionId, approve, CurrentUser.UserId, deviceProfileId, deviceBatchId, reason);
return new HttpStatusCodeResult(200);
return Ok();
}
[HttpPost]
[DiscoAuthorize(Claims.Config.Enrolment.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult PendingTimeoutMinutes(int PendingTimeoutMinutes)
{
try
@@ -31,7 +30,7 @@ namespace Disco.Web.Areas.API.Controllers
{
Database.DiscoConfiguration.Bootstrapper.PendingTimeout = TimeSpan.FromMinutes(PendingTimeoutMinutes);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
@@ -40,7 +39,53 @@ namespace Disco.Web.Areas.API.Controllers
}
catch (Exception ex)
{
return Json($"Error: {ex.Message}");
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.Enrolment.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult MacSshUsername(string MacSshUsername)
{
try
{
if (!string.IsNullOrWhiteSpace(MacSshUsername))
{
Database.DiscoConfiguration.Bootstrapper.MacSshUsername = MacSshUsername;
Database.SaveChanges();
return Ok();
}
else
{
throw new Exception("The Username cannot be null or empty");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.Enrolment.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult MacSshPassword(string MacSshPassword)
{
try
{
if (!string.IsNullOrWhiteSpace(MacSshPassword))
{
Database.DiscoConfiguration.Bootstrapper.MacSshPassword = MacSshPassword;
Database.SaveChanges();
return Ok();
}
else
{
throw new Exception("The Password cannot be null or empty");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
@@ -33,7 +33,7 @@ namespace Disco.Web.Areas.API.Controllers
{
var errorState = ModelState.First(m => m.Value.Errors.Any());
var error = errorState.Value.Errors.First();
return new HttpStatusCodeResult(400, $"{errorState.Key}: {error.Exception?.Message ?? error.ErrorMessage}");
return BadRequest($"{errorState.Key}: {error.Exception?.Message ?? error.ErrorMessage}");
}
SavedExports.UpdateSavedExport(Database, model.ToSavedExport());
@@ -20,7 +20,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult TypeDescriptor(string type, bool staticMembersOnly = false)
{
if (string.IsNullOrWhiteSpace(type))
return new HttpStatusCodeResult(400, "Type is required");
return BadRequest("Type is required");
var t = Type.GetType(type, false);
@@ -28,15 +28,15 @@ namespace Disco.Web.Areas.API.Controllers
{
var typeNameParts = type.Split(new string[] { ", " }, StringSplitOptions.None);
if (typeNameParts.Length < 2)
return Json("Invalid Type Specified");
return BadRequest("Invalid Type Specified");
if (!ExpressionExtensionProviderFeature.TryGetExtensionAssembly(typeNameParts[1], out var assembly))
return Json("Invalid Type Specified");
return BadRequest("Invalid Type Specified");
t = assembly.GetType(typeNameParts[0]);
if (t == null)
return Json("Invalid Type Specified");
return BadRequest("Invalid Type Specified");
}
return Json(ExpressionTypeDescriptor.Build(t, staticMembersOnly));
+116 -90
View File
@@ -78,6 +78,7 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
try
@@ -287,7 +288,6 @@ 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));
else
{
if (resultData != null)
@@ -296,7 +296,7 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
}
}
@@ -305,22 +305,25 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Job.Properties.ExpectedClosedDate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateExpectedClosedDate(int id, string ExpectedClosedDate, bool? redirect = null)
{
return Update(id, pExpectedClosedDate, ExpectedClosedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.DeviceHeldLocation)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDeviceHeldLocation(int id, string DeviceHeldLocation, bool? redirect = null)
{
return Update(id, pDeviceHeldLocation, DeviceHeldLocation, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.Flags)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateFlags(int id, string Flags, bool? redirect = null)
{
return Update(id, pFlags, Flags, redirect);
@@ -328,61 +331,73 @@ namespace Disco.Web.Areas.API.Controllers
#region NonWarranty
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeRequired)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyAccountingChargeRequired(int id, string AccountingChargeRequiredDate, bool? redirect = null)
{
return Update(id, pNonWarrantyAccountingChargeRequired, AccountingChargeRequiredDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargeAdded)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyAccountingChargeAdded(int id, string AccountingChargeAddedDate, bool? redirect = null)
{
return Update(id, pNonWarrantyAccountingChargeAdded, AccountingChargeAddedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.AccountingChargePaid)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyAccountingChargePaid(int id, string AccountingChargePaidDate, bool? redirect = null)
{
return Update(id, pNonWarrantyAccountingChargePaid, AccountingChargePaidDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderRaised)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyPurchaseOrderRaised(int id, string PurchaseOrderRaisedDate, bool? redirect = null)
{
return Update(id, pNonWarrantyPurchaseOrderRaised, PurchaseOrderRaisedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderReference)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyPurchaseOrderReference(int id, string PurchaseOrderReference, bool? redirect = null)
{
return Update(id, pNonWarrantyPurchaseOrderReference, PurchaseOrderReference, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.PurchaseOrderSent)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyPurchaseOrderSent(int id, string PurchaseOrderSentDate, bool? redirect = null)
{
return Update(id, pNonWarrantyPurchaseOrderSent, PurchaseOrderSentDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InvoiceReceived)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyInvoiceReceived(int id, string InvoiceReceivedDate, bool? redirect = null)
{
return Update(id, pNonWarrantyInvoiceReceived, InvoiceReceivedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerName)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyRepairerName(int id, string RepairerName, bool? redirect = null)
{
return Update(id, pNonWarrantyRepairerName, RepairerName, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerLoggedDate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyRepairerLoggedDate(int id, string RepairerLoggedDate, bool? redirect = null)
{
return Update(id, pNonWarrantyRepairerLoggedDate, RepairerLoggedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerReference)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyRepairerReference(int id, string RepairerReference, bool? redirect = null)
{
return Update(id, pNonWarrantyRepairerReference, RepairerReference, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.RepairerCompletedDate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyRepairerCompletedDate(int id, string RepairerCompletedDate, bool? redirect = null)
{
return Update(id, pNonWarrantyRepairerCompletedDate, RepairerCompletedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.IsInsuranceClaim)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateNonWarrantyIsInsuranceClaim(int id, bool IsInsuranceClaim, bool? redirect = null)
{
return Update(id, pNonWarrantyIsInsuranceClaim, IsInsuranceClaim.ToString(), redirect);
@@ -392,91 +407,109 @@ namespace Disco.Web.Areas.API.Controllers
#region Insurance
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceLossOrDamageDate(int id, string LossOrDamageDate, bool? redirect = null)
{
return Update(id, pInsuranceLossOrDamageDate, LossOrDamageDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceEventLocation(int id, string EventLocation, bool? redirect = null)
{
return Update(id, pInsuranceEventLocation, EventLocation, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceDescription(int id, string Description, bool? redirect = null)
{
return Update(id, pInsuranceDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceThirdPartyCaused(int id, string ThirdPartyCaused, bool? redirect = null)
{
return Update(id, pInsuranceThirdPartyCaused, ThirdPartyCaused, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceThirdPartyCausedName(int id, string ThirdPartyCausedName, bool? redirect = null)
{
return Update(id, pInsuranceThirdPartyCausedName, ThirdPartyCausedName, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceThirdPartyCausedWhy(int id, string ThirdPartyCausedWhy, bool? redirect = null)
{
return Update(id, pInsuranceThirdPartyCausedWhy, ThirdPartyCausedWhy, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceWitnessesNamesAddresses(int id, string WitnessesNamesAddresses, bool? redirect = null)
{
return Update(id, pInsuranceWitnessesNamesAddresses, WitnessesNamesAddresses, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceBurglaryTheftMethodOfEntry(int id, string BurglaryTheftMethodOfEntry, bool? redirect = null)
{
return Update(id, pInsuranceBurglaryTheftMethodOfEntry, BurglaryTheftMethodOfEntry, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsurancePropertyLastSeenDate(int id, string PropertyLastSeenDate, bool? redirect = null)
{
return Update(id, pInsurancePropertyLastSeenDate, PropertyLastSeenDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsurancePoliceNotified(int id, string PoliceNotified, bool? redirect = null)
{
return Update(id, pInsurancePoliceNotified, PoliceNotified, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsurancePoliceNotifiedStation(int id, string PoliceNotifiedStation, bool? redirect = null)
{
return Update(id, pInsurancePoliceNotifiedStation, PoliceNotifiedStation, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsurancePoliceNotifiedDate(int id, string PoliceNotifiedDate, bool? redirect = null)
{
return Update(id, pInsurancePoliceNotifiedDate, PoliceNotifiedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsurancePoliceNotifiedCrimeReportNo(int id, string PoliceNotifiedCrimeReportNo, bool? redirect = null)
{
return Update(id, pInsurancePoliceNotifiedCrimeReportNo, PoliceNotifiedCrimeReportNo, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceRecoverReduceAction(int id, string RecoverReduceAction, bool? redirect = null)
{
return Update(id, pInsuranceRecoverReduceAction, RecoverReduceAction, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceOtherInterestedParties(int id, string OtherInterestedParties, bool? redirect = null)
{
return Update(id, pInsuranceOtherInterestedParties, OtherInterestedParties, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceDetails)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceDateOfPurchase(int id, string DateOfPurchase, bool? redirect = null)
{
return Update(id, pInsuranceDateOfPurchase, DateOfPurchase, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceClaimFormSentDate(int id, string ClaimFormSentDate, bool? redirect = null)
{
return Update(id, pInsuranceClaimFormSentDate, ClaimFormSentDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.InsuranceClaimFormSent)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInsuranceClaimFormSentUserId(int id, string ClaimFormSentUserId, bool? redirect = null)
{
return Update(id, pInsuranceClaimFormSentUserId, ClaimFormSentUserId, redirect);
@@ -486,21 +519,25 @@ namespace Disco.Web.Areas.API.Controllers
#region Warranty
[DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalName)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyExternalName(int id, string ExternalName, bool? redirect = null)
{
return Update(id, pWarrantyExternalName, ExternalName, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalLoggedDate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyExternalLoggedDate(int id, string ExternalLoggedDate, bool? redirect = null)
{
return Update(id, pWarrantyExternalLoggedDate, ExternalLoggedDate, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalReference)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyExternalReference(int id, string ExternalReference, bool? redirect = null)
{
return Update(id, pWarrantyExternalReference, ExternalReference, redirect);
}
[DiscoAuthorize(Claims.Job.Properties.WarrantyProperties.ExternalCompletedDate)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateWarrantyExternalCompletedDate(int id, string ExternalCompletedDate, bool? redirect = null)
{
return Update(id, pWarrantyExternalCompletedDate, ExternalCompletedDate, redirect);
@@ -1424,6 +1461,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Job Actions
[DiscoAuthorize(Claims.Job.Actions.UpdateSubTypes)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSubTypes(int id, List<string> SubTypes = null, bool? AddComponents = null, bool? redirect = null)
{
try
@@ -1448,18 +1486,19 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Job.Show(job.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Job.Properties.Flags)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateFlag(int id, long? Flag, string Reason, bool? redirect = null)
{
try
@@ -1508,7 +1547,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Job.Show(job.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
@@ -1520,11 +1559,12 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Job.Properties.WaitingForUserAction)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult WaitingForUserAction(int id, string Reason, bool? redirect = null)
{
try
@@ -1544,18 +1584,19 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Job.Show(job.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Job.Properties.NotWaitingForUserAction)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult NotWaitingForUserAction(int id, string Resolution, bool? redirect = null)
{
try
@@ -1575,18 +1616,19 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Job.Show(job.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Job.Properties.DeviceReadyForReturn)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DeviceReadyForReturn(int id, bool redirect)
{
Database.Configuration.LazyLoadingEnabled = true;
@@ -1601,17 +1643,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Properties.DeviceHeld)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DeviceHeld(int id, bool redirect)
{
var j = Database.Jobs.Find(id);
@@ -1625,17 +1668,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Properties.DeviceReturned)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DeviceReturned(int id, bool redirect)
{
var j = Database.Jobs.Find(id);
@@ -1649,17 +1693,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Actions.ForceClose)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ForceClose(int id, string Reason, bool? redirect = null)
{
var j = Database.Jobs.Find(id);
@@ -1674,17 +1719,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Actions.Close)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Close(int id, bool redirect)
{
var j = Database.Jobs.Find(id);
@@ -1699,17 +1745,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Actions.Reopen)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Reopen(int id, bool redirect)
{
var j = Database.Jobs
@@ -1725,17 +1772,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Actions.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool redirect)
{
var j = Database.Jobs.Find(id);
@@ -1750,17 +1798,18 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Actions.ConvertHWarToHNWar)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ConvertHWarToHNWar(int id, bool redirect)
{
var j = Database.Jobs.Find(id);
@@ -1775,14 +1824,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Job.Show(j.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
return Json("Job's state doesn't allow this action", JsonRequestBehavior.AllowGet);
return BadRequest("Job's state doesn't allow this action");
}
}
return Json("Invalid Job Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
#endregion
@@ -1872,7 +1921,7 @@ namespace Disco.Web.Areas.API.Controllers
}
#endregion
#region Job Attachements
#region Job Attachments
[DiscoAuthorize(Claims.Job.ShowAttachments), OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 172800)]
public virtual ActionResult AttachmentDownload(int id)
@@ -1907,7 +1956,8 @@ namespace Disco.Web.Areas.API.Controllers
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Job.Actions.AddAttachments), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Job.Actions.AddAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentUpload(int id, string comments)
{
var j = Database.Jobs.Find(id);
@@ -1987,6 +2037,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyAttachments, Claims.Job.Actions.RemoveOwnAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentRemove(int id)
{
var ja = Database.JobAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
@@ -1999,9 +2050,9 @@ namespace Disco.Web.Areas.API.Controllers
ja.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.Job.Actions.AddAttachments)]
@@ -2028,11 +2079,7 @@ namespace Disco.Web.Areas.API.Controllers
}
catch (InvalidOperationException ex)
{
return Json(new
{
Success = false,
ErrorMessage = ex.Message,
});
return BadRequest(ex.Message);
}
}
@@ -2041,55 +2088,58 @@ namespace Disco.Web.Areas.API.Controllers
#region Job Components
[DiscoAuthorizeAll(Claims.Job.Properties.NonWarrantyProperties.AddComponents, Claims.Job.Properties.NonWarrantyProperties.EditComponents)]
public virtual ActionResult ComponentAdd(int id, string Description, string Cost)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentAdd(int id, string description, string cost)
{
var j = Database.Jobs.Find(id);
if (j != null)
{
if (string.IsNullOrEmpty(Description))
Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out var cost);
if (string.IsNullOrEmpty(description))
description = "?";
if (!string.IsNullOrEmpty(cost) && cost.Contains("$"))
cost = cost.Substring(cost.IndexOf("$") + 1);
decimal.TryParse(cost, out var costValue);
var jc = new JobComponent()
{
JobId = j.Id,
Description = Description,
Cost = cost,
Description = description,
Cost = costValue,
TechUserId = CurrentUser.UserId
};
Database.JobComponents.Add(jc);
Database.SaveChanges();
return Json(new Models.Job.ComponentModel { Result = "OK", Component = Models.Job._ComponentModel.FromJobComponent(jc) }, JsonRequestBehavior.AllowGet);
return Json(Models.Job.ComponentModel.FromJobComponent(jc));
}
return Json(new Models.Job.ComponentModel { Result = "Invalid Job Number" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Number");
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.EditComponents)]
public virtual ActionResult ComponentUpdate(int id, string Description, string Cost)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentUpdate(int id, string description, string cost)
{
var jc = Database.JobComponents.Find(id);
if (jc != null)
{
if (string.IsNullOrEmpty(Description))
Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out var cost);
if (string.IsNullOrEmpty(description))
description = "?";
if (!string.IsNullOrEmpty(cost) && cost.Contains("$"))
cost = cost.Substring(cost.IndexOf("$") + 1);
decimal.TryParse(cost, out var costValue);
jc.Description = Description;
jc.Cost = cost;
jc.Description = description;
jc.Cost = costValue;
Database.SaveChanges();
return Json(new Models.Job.ComponentModel { Result = "OK", Component = Models.Job._ComponentModel.FromJobComponent(jc) }, JsonRequestBehavior.AllowGet);
return Json(Models.Job.ComponentModel.FromJobComponent(jc));
}
return Json(new Models.Job.ComponentModel { Result = "Invalid Job Component Number" }, JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Component Number");
}
[DiscoAuthorize(Claims.Job.Properties.NonWarrantyProperties.EditComponents)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ComponentRemove(int id)
{
var jc = Database.JobComponents.Find(id);
@@ -2097,9 +2147,9 @@ namespace Disco.Web.Areas.API.Controllers
{
Database.JobComponents.Remove(jc);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
return Json("Invalid Job Component Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Component Number");
}
#endregion
@@ -2116,30 +2166,6 @@ namespace Disco.Web.Areas.API.Controllers
#endregion
[DiscoAuthorize(Claims.Job.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdf(int id, string DocumentTemplateId)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplateId))
throw new ArgumentNullException(nameof(DocumentTemplateId));
// Obsolete: Use API\DocumentTemplate\Generate instead
return RedirectToAction(MVC.API.DocumentTemplate.Generate(DocumentTemplateId, id.ToString()));
}
[DiscoAuthorize(Claims.Job.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdfPackage(int id, string DocumentTemplatePackageId)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplatePackageId))
throw new ArgumentNullException(nameof(DocumentTemplatePackageId));
// Obsolete: Use API\DocumentTemplatePackage\Generate instead
return RedirectToAction(MVC.API.DocumentTemplatePackage.Generate(DocumentTemplatePackageId, id.ToString()));
}
[DiscoAuthorize(Claims.Job.Properties.DeviceHeldLocation)]
public virtual ActionResult DeviceHeldLocations()
{
@@ -12,6 +12,7 @@ namespace Disco.Web.Areas.API.Controllers
public partial class JobPreferencesController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateInitialCommentsTemplate(string initialCommentsTemplate, bool redirect = false)
{
string expression = null;
@@ -32,10 +33,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLongRunningJobDaysThreshold(int LongRunningJobDaysThreshold, bool redirect = false)
{
Database.DiscoConfiguration.JobPreferences.LongRunningJobDaysThreshold = LongRunningJobDaysThreshold;
@@ -44,10 +46,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateStaleJobMinutesThreshold(int StaleJobMinutesThreshold, bool redirect = false)
{
Database.DiscoConfiguration.JobPreferences.StaleJobMinutesThreshold = StaleJobMinutesThreshold;
@@ -56,10 +59,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLodgmentIncludeAllAttachmentsByDefault(bool includeAllAttachmentsByDefault, bool redirect = false)
{
Database.DiscoConfiguration.JobPreferences.LodgmentIncludeAllAttachmentsByDefault = includeAllAttachmentsByDefault;
@@ -68,10 +72,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDefaultNoticeboardTheme(string DefaultNoticeboardTheme, bool redirect = false)
{
Database.DiscoConfiguration.JobPreferences.DefaultNoticeboardTheme = DefaultNoticeboardTheme;
@@ -82,10 +87,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLocationMode(LocationModes LocationMode, bool redirect = false)
{
Database.DiscoConfiguration.JobPreferences.LocationMode = LocationMode;
@@ -94,13 +100,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
public virtual ActionResult UpdateLocationList(string[] LocationList, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLocationList(string[] locationList, bool redirect = false)
{
var list = LocationList
var list = locationList
.Where(i => !string.IsNullOrWhiteSpace(i))
.Select(i => i.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
@@ -112,10 +119,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult ImportLocationList(string LocationList, bool AutomaticList = false, bool Override = false, bool redirect = false)
{
IEnumerable<string> list;
@@ -152,10 +160,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnCreateExpression(string OnCreateExpression, bool redirect = false)
{
string expression = null;
@@ -176,10 +185,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnDeviceReadyForReturnExpression(string OnDeviceReadyForReturnExpression, bool redirect = false)
{
string expression = null;
@@ -200,10 +210,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.JobPreferences.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnCloseExpression(string OnCloseExpression, bool redirect = false)
{
string expression = null;
@@ -224,7 +235,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.JobPreferences.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
}
}
@@ -20,6 +20,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pDefaultSLAExpiry = "defaultslaexpiry";
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
Authorization.Require(Claims.Config.JobQueue.Configure);
@@ -64,55 +65,62 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.JobQueue.Index(jobQueue.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateName(int id, string QueueName = null, bool? redirect = null)
{
return Update(id, pName, QueueName, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDescription(int id, string Description = null, bool? redirect = null)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdatePriority(int id, string Priority = null, bool? redirect = null)
{
return Update(id, pPriority, Priority, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDefaultSLAExpiry(int id, string DefaultSLAExpiry = null, bool? redirect = null)
{
return Update(id, pDefaultSLAExpiry, DefaultSLAExpiry, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIcon(int id, string Icon = null, bool? redirect = null)
{
return Update(id, pIcon, Icon, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconColour(int id, string IconColour = null, bool? redirect = null)
{
return Update(id, pIconColour, IconColour, redirect);
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconAndColour(int id, string Icon = null, string IconColour = null, bool redirect = false)
{
try
@@ -127,23 +135,24 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Job Queue Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Queue Id");
}
if (redirect)
return RedirectToAction(MVC.Config.JobQueue.Index(jobQueue.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSubjects(int id, string[] Subjects = null, bool redirect = false)
{
try
@@ -158,23 +167,24 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Job Queue Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Queue Id");
}
if (redirect)
return RedirectToAction(MVC.Config.JobQueue.Index(jobQueue.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.JobQueue.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateJobSubTypes(int id, List<string> JobSubTypes = null, bool redirect = false)
{
try
@@ -186,50 +196,50 @@ namespace Disco.Web.Areas.API.Controllers
}
else
{
return Json("Invalid Job Queue Id", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Job Queue Id");
}
if (redirect)
return RedirectToAction(MVC.Config.JobQueue.Index(jobQueue.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
#region Update Properties
private void UpdateIconAndColour(JobQueue jobQueue, string Icon, string IconColour)
private void UpdateIconAndColour(JobQueue jobQueue, string icon, string iconColour)
{
if (string.IsNullOrWhiteSpace(Icon))
throw new ArgumentNullException("Icon");
if (string.IsNullOrWhiteSpace(IconColour))
throw new ArgumentNullException("IconColour");
if (string.IsNullOrWhiteSpace(icon))
throw new ArgumentNullException(nameof(icon));
if (string.IsNullOrWhiteSpace(iconColour))
throw new ArgumentNullException(nameof(iconColour));
jobQueue.Icon = Icon;
jobQueue.IconColour = IconColour;
jobQueue.Icon = icon;
jobQueue.IconColour = iconColour;
JobQueueService.UpdateJobQueue(Database, jobQueue);
}
private void UpdateIcon(JobQueue jobQueue, string Icon)
private void UpdateIcon(JobQueue jobQueue, string icon)
{
if (string.IsNullOrWhiteSpace(Icon))
if (string.IsNullOrWhiteSpace(icon))
throw new ArgumentNullException("Icon");
jobQueue.Icon = Icon;
jobQueue.Icon = icon;
JobQueueService.UpdateJobQueue(Database, jobQueue);
}
private void UpdateIconColour(JobQueue jobQueue, string IconColour)
private void UpdateIconColour(JobQueue jobQueue, string iconColour)
{
if (string.IsNullOrWhiteSpace(IconColour))
if (string.IsNullOrWhiteSpace(iconColour))
throw new ArgumentNullException("IconColour");
jobQueue.IconColour = IconColour;
jobQueue.IconColour = iconColour;
JobQueueService.UpdateJobQueue(Database, jobQueue);
}
@@ -277,25 +287,25 @@ namespace Disco.Web.Areas.API.Controllers
JobQueueService.UpdateJobQueue(Database, jobQueue);
}
private void UpdateSubjects(JobQueue jobQueue, string[] Subjects)
private void UpdateSubjects(JobQueue jobQueue, string[] subjects)
{
string subjectIds = null;
// Validate Subjects
if (Subjects != null && Subjects.Length > 0)
if (subjects != null && subjects.Length > 0)
{
var subjects = Subjects
var subjectRecords = subjects
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Trim())
.Select(s => Tuple.Create(s, ActiveDirectory.RetrieveADObject(s, Quick: true)))
.Where(s => s.Item2 is ADUserAccount || s.Item2 is ADGroup)
.ToList();
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
var invalidSubjects = subjectRecords.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0)
throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var proposedSubjects = subjectRecords.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
subjectIds = string.Join(",", proposedSubjects);
@@ -340,6 +350,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorize(Claims.Config.JobQueue.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -353,7 +364,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid Job Queue Id");
}
@@ -362,7 +373,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
@@ -16,6 +16,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pSla = "sla";
const string pPriority = "priority";
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
try
@@ -52,40 +53,45 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return Redirect($"{Url.Action(MVC.Job.Show(jobQueueJob.JobId))}#jobDetailTab-Queues");
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorizeAny(Claims.Job.Properties.JobQueueProperties.EditAnyComments, Claims.Job.Properties.JobQueueProperties.EditOwnComments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAddedComment(int id, string AddedComment = null, bool? redirect = null)
{
return Update(id, pAddedComment, AddedComment, redirect);
}
[DiscoAuthorizeAny(Claims.Job.Properties.JobQueueProperties.EditAnyComments, Claims.Job.Properties.JobQueueProperties.EditOwnComments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateRemovedComment(int id, string RemovedComment = null, bool? redirect = null)
{
return Update(id, pRemovedComment, RemovedComment, redirect);
}
[DiscoAuthorizeAny(Claims.Job.Properties.JobQueueProperties.EditAnySLA, Claims.Job.Properties.JobQueueProperties.EditOwnSLA)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSla(int id, string SLA = null, bool? redirect = null)
{
return Update(id, pSla, SLA, redirect);
}
[DiscoAuthorizeAny(Claims.Job.Properties.JobQueueProperties.EditAnyPriority, Claims.Job.Properties.JobQueueProperties.EditOwnPriority)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdatePriority(int id, string Priority = null, bool? redirect = null)
{
return Update(id, pPriority, Priority, redirect);
}
[DiscoAuthorizeAny(Claims.Job.Properties.JobQueueProperties.EditAnySLA, Claims.Job.Properties.JobQueueProperties.EditOwnSLA,
Claims.Job.Properties.JobQueueProperties.EditAnyPriority, Claims.Job.Properties.JobQueueProperties.EditOwnPriority)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateSlaAndPriority(int id, string Sla = null, string Priority = null, bool? redirect = null)
{
try
@@ -106,14 +112,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return Redirect($"{Url.Action(MVC.Job.Show(jobQueueJob.JobId))}#jobDetailTab-Queues");
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
@@ -175,6 +181,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorizeAny(Claims.Job.Actions.AddAnyQueues, Claims.Job.Actions.AddOwnQueues)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AddJob(int id, int JobId, string Comment, int? SLAExpiresMinutes, JobQueuePriority Priority)
{
DateTime? SLAExpires = (SLAExpiresMinutes.HasValue && SLAExpiresMinutes.Value > 0) ? DateTime.Now.AddMinutes(SLAExpiresMinutes.Value) : (DateTime?)null;
@@ -197,6 +204,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyQueues, Claims.Job.Actions.RemoveOwnQueues)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult RemoveJob(int id, string Comment, bool? CloseJob = null)
{
Database.Configuration.LazyLoadingEnabled = true;
@@ -21,7 +21,8 @@ namespace Disco.Web.Areas.API.Controllers
return Json(m, JsonRequestBehavior.AllowGet);
}
[HttpPost, ValidateAntiForgeryToken, DiscoAuthorize(Claims.Config.Logging.Show)]
[DiscoAuthorize(Claims.Config.Logging.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult RetrieveEvents(string Format, DateTime? Start = null, DateTime? End = null, int? ModuleId = null, List<int> EventTypeIds = null, int? Take = null)
{
if (string.Equals(Format, "json", StringComparison.OrdinalIgnoreCase))
@@ -31,7 +31,8 @@ namespace Disco.Web.Areas.API.Controllers
}
}
[HttpPost, DiscoAuthorize(Claims.Config.Plugin.Install), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.Plugin.Install)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAll()
{
var status = UpdatePluginTask.UpdateAllPlugins();
@@ -39,7 +40,8 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[HttpPost, DiscoAuthorize(Claims.Config.Plugin.Install), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.Plugin.Install)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(string pluginId)
{
if (string.IsNullOrEmpty(pluginId))
@@ -50,7 +52,8 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[HttpPost, DiscoAuthorize(Claims.Config.Plugin.Uninstall), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.Plugin.Uninstall)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Uninstall(string id, bool uninstallData)
{
if (string.IsNullOrEmpty(id))
@@ -63,7 +66,8 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[HttpPost, DiscoAuthorize(Claims.Config.Plugin.Install), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.Plugin.Install)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Install(string pluginId)
{
if (string.IsNullOrEmpty(pluginId))
@@ -92,7 +96,8 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
}
[HttpPost, DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal), ValidateAntiForgeryToken]
[DiscoAuthorizeAll(Claims.Config.Plugin.Install, Claims.Config.Plugin.InstallLocal)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult InstallLocal(HttpPostedFileBase plugin, bool immediateRestart = false)
{
if (plugin == null || plugin.ContentLength <= 0 || string.IsNullOrWhiteSpace(plugin.FileName))
@@ -19,6 +19,7 @@ namespace Disco.Web.Areas.API.Controllers
public partial class SystemController : AuthorizedDatabaseController
{
[DiscoAuthorize(Claims.Config.System.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateLastNetworkLogonDates()
{
var taskStatus = ADNetworkLogonDatesUpdateTask.ScheduleImmediately();
@@ -27,6 +28,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.DiscoAdminAccount)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAttachmentThumbnails()
{
var ts = Disco.Services.Documents.AttachmentImport.ThumbnailUpdateTask.ScheduleImmediately();
@@ -35,6 +37,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.DiscoAdminAccount)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateADDeviceDescriptions()
{
var ts = ADDeviceDescriptionUpdateTask.ScheduleImmediately();
@@ -63,6 +66,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorize(Claims.Config.System.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateCheck()
{
var ts = UpdateQueryTask.ScheduleNow();
@@ -70,7 +74,8 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(ts.SessionId));
}
[HttpPost, ValidateAntiForgeryToken, DiscoAuthorize(Claims.Config.System.Show)]
[DiscoAuthorize(Claims.Config.System.Show)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult OnlineServicesConnectStart()
{
OnlineServicesConnect.QueueStart();
@@ -82,6 +87,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Organisation Name
[DiscoAuthorize(Claims.Config.Organisation.ConfigureName)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOrganisationName(string OrganisationName, bool redirect = false)
{
if (string.IsNullOrWhiteSpace(OrganisationName))
@@ -96,7 +102,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
#endregion
@@ -117,7 +123,8 @@ namespace Disco.Web.Areas.API.Controllers
}
}
}
[DiscoAuthorize(Claims.Config.Organisation.ConfigureLogo), HttpPost]
[DiscoAuthorize(Claims.Config.Organisation.ConfigureLogo)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult OrganisationLogo(bool redirect, HttpPostedFileBase Image, bool? ResetLogo = null)
{
if (ResetLogo.HasValue && ResetLogo.Value)
@@ -127,7 +134,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
if (Image != null && Image.ContentLength > 0)
@@ -139,25 +146,26 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("Invalid Content Type", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Content Type");
}
}
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("No Image Supplied", JsonRequestBehavior.AllowGet);
return BadRequest("No Image Supplied");
}
#endregion
#region Organisation Addresses
[HttpPost, ValidateAntiForgeryToken, DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
[DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOrganisationAddress(Disco.Models.BI.Config.OrganisationAddress organisationAddress, bool redirect = false)
{
if (organisationAddress == null)
@@ -171,7 +179,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
else
{
@@ -193,7 +201,8 @@ namespace Disco.Web.Areas.API.Controllers
return Json(em.ToString(), JsonRequestBehavior.AllowGet);
}
}
[HttpPost, ValidateAntiForgeryToken, DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
[DiscoAuthorize(Claims.Config.Organisation.ConfigureAddresses)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult DeleteOrganisationAddress(int id, bool redirect = false)
{
// Remove References in Device Profiles
@@ -207,7 +216,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
#endregion
@@ -215,6 +224,7 @@ namespace Disco.Web.Areas.API.Controllers
#region MultiSiteMode
[DiscoAuthorize(Claims.Config.Organisation.ConfigureMultiSiteMode)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateMultiSiteMode(bool MultiSiteMode, bool redirect = false)
{
Database.DiscoConfiguration.MultiSiteMode = MultiSiteMode;
@@ -226,7 +236,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.Organisation.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
#endregion
@@ -236,6 +246,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Active Directory
[DiscoAuthorize(Claims.Config.System.ConfigureActiveDirectory)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateActiveDirectorySearchScope(List<string> Containers, bool redirect = false)
{
ActiveDirectory.Context.UpdateSearchContainers(Database, Containers);
@@ -244,10 +255,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.System.ConfigureActiveDirectory)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateActiveDirectorySearchAllServers(bool SearchAllServers, bool redirect = false)
{
try
@@ -268,18 +280,19 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.System.ConfigureActiveDirectory)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateActiveDirectorySearchWildcardSuffixOnly(bool SearchWildcardSuffixOnly, bool redirect = false)
{
ActiveDirectory.Context.UpdateWildcardSearchSuffixOnly(Database, SearchWildcardSuffixOnly);
@@ -289,7 +302,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorizeAny(Claims.Config.System.ConfigureActiveDirectory, Claims.Config.DeviceProfile.Configure)]
@@ -341,7 +354,8 @@ namespace Disco.Web.Areas.API.Controllers
return Json(Models.Shared.SubjectDescriptorModel.FromActiveDirectoryObject(subject), JsonRequestBehavior.AllowGet);
}
[DiscoAuthorizeAny(Claims.Config.UserFlag.Configure)]
[DiscoAuthorizeAny(Claims.Config.UserFlag.Configure, Claims.Config.DeviceFlag.Configure, Claims.Config.DeviceProfile.Configure, Claims.Config.DocumentTemplate.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult SyncActiveDirectoryManagedGroup(string id, string redirectUrl = null)
{
@@ -361,6 +375,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Proxy Settings
[DiscoAuthorize(Claims.Config.System.ConfigureProxy)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateProxySettings(string ProxyAddress, int? ProxyPort, string ProxyUsername, string ProxyPassword, bool redirect = false)
{
// Default Proxy Port
@@ -387,14 +402,15 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
#endregion
#region Email Settings
[DiscoAuthorize(Claims.Config.System.ConfigureEmail), ValidateInput(false), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.System.ConfigureEmail), ValidateInput(false)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateEmailSettings(string SmtpServer, int? SmtpPort, string FromAddress, string ReplyToAddress, bool EnableSsl, string Username, string Password, bool redirect = false)
{
// Default Port
@@ -419,10 +435,11 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
[DiscoAuthorize(Claims.Config.System.ConfigureEmail), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.Config.System.ConfigureEmail)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult SendTestEmail(string Recipient, bool redirect = false)
{
if (string.IsNullOrWhiteSpace(Recipient))
@@ -433,7 +450,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect)
return RedirectToAction(MVC.Config.SystemConfig.Index());
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
#endregion
@@ -139,7 +139,8 @@ namespace Disco.Web.Areas.API.Controllers
return HttpNotFound("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.User.Actions.AddAttachments), ValidateAntiForgeryToken]
[DiscoAuthorize(Claims.User.Actions.AddAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentUpload(string id, string domain, string comments)
{
id = ActiveDirectory.ParseDomainAccountId(id, domain);
@@ -224,6 +225,7 @@ namespace Disco.Web.Areas.API.Controllers
}
[DiscoAuthorizeAny(Claims.User.Actions.RemoveAnyAttachments, Claims.User.Actions.RemoveOwnAttachments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult AttachmentRemove(int id)
{
var ua = Database.UserAttachments.Include("TechUser").Where(m => m.Id == id).FirstOrDefault();
@@ -236,9 +238,9 @@ namespace Disco.Web.Areas.API.Controllers
ua.OnDelete(Database);
Database.SaveChanges();
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
return Json("Invalid Attachment Number", JsonRequestBehavior.AllowGet);
return BadRequest("Invalid Attachment Number");
}
[DiscoAuthorize(Claims.User.Actions.AddAttachments)]
@@ -267,44 +269,12 @@ namespace Disco.Web.Areas.API.Controllers
}
catch (InvalidOperationException ex)
{
return Json(new
{
Success = false,
ErrorMessage = ex.Message,
});
return BadRequest(ex.Message);
}
}
#endregion
[DiscoAuthorize(Claims.User.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdf(string id, string domain, string DocumentTemplateId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplateId))
throw new ArgumentNullException(nameof(DocumentTemplateId));
var userId = ActiveDirectory.ParseDomainAccountId(id, domain);
// Obsolete: Use API\DocumentTemplate\Generate instead
return RedirectToAction(MVC.API.DocumentTemplate.Generate(DocumentTemplateId, userId));
}
[DiscoAuthorize(Claims.User.Actions.GenerateDocuments)]
public virtual ActionResult GeneratePdfPackage(string id, string domain, string DocumentTemplatePackageId)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(DocumentTemplatePackageId))
throw new ArgumentNullException(nameof(DocumentTemplatePackageId));
var userId = ActiveDirectory.ParseDomainAccountId(id, domain);
// Obsolete: Use API\DocumentTemplatePackage\Generate instead
return RedirectToAction(MVC.API.DocumentTemplatePackage.Generate(DocumentTemplatePackageId, userId));
}
public virtual ActionResult Photo(string userId)
{
if (string.IsNullOrEmpty(userId))
@@ -40,14 +40,14 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return Redirect($"{Url.Action(MVC.User.Show(userFlagAssignment.UserId))}#UserDetailTab-Flags");
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
@@ -24,6 +24,7 @@ namespace Disco.Web.Areas.API.Controllers
const string pOnUnassignmentExpression = "onunassignmentexpression";
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Update(int id, string key, string value = null, bool? redirect = null)
{
Authorization.Require(Claims.Config.UserFlag.Configure);
@@ -68,93 +69,101 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.UserFlag.Index(flag.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#region Update Shortcut Methods
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateName(int id, string FlagName = null, bool? redirect = null)
{
return Update(id, pName, FlagName, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateDescription(int id, string Description = null, bool? redirect = null)
{
return Update(id, pDescription, Description, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
public virtual ActionResult UpdateIcon(int id, string Icon = null, bool? redirect = null)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIcon(int id, string icon = null, bool? redirect = null)
{
return Update(id, pIcon, Icon, redirect);
return Update(id, pIcon, icon, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
public virtual ActionResult UpdateIconColour(int id, string IconColour = null, bool? redirect = null)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconColour(int id, string iconColour = null, bool? redirect = null)
{
return Update(id, pIconColour, IconColour, redirect);
return Update(id, pIconColour, iconColour, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
public virtual ActionResult UpdateIconAndColour(int id, string Icon = null, string IconColour = null, bool redirect = false)
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateIconAndColour(int id, string icon = null, string iconColour = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
throw new ArgumentOutOfRangeException(nameof(id));
var UserFlag = Database.UserFlags.Find(id);
if (UserFlag != null)
{
UpdateIconAndColour(UserFlag, Icon, IconColour);
UpdateIconAndColour(UserFlag, icon, iconColour);
}
else
{
throw new ArgumentException("Invalid User Flag Id", "id");
throw new ArgumentException("Invalid User Flag Id", nameof(id));
}
if (redirect)
return RedirectToAction(MVC.Config.UserFlag.Index(UserFlag.Id));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnAssignmentExpression(int id, string OnAssignmentExpression = null, bool redirect = false)
{
return Update(id, pOnAssignmentExpression, OnAssignmentExpression, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateOnUnassignmentExpression(int id, string OnUnassignmentExpression = null, bool redirect = false)
{
return Update(id, pOnUnassignmentExpression, OnUnassignmentExpression, redirect);
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUsersLinkedGroup(int id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
throw new ArgumentOutOfRangeException(nameof(id));
var UserFlag = Database.UserFlags.Find(id);
if (UserFlag == null)
throw new ArgumentException("Invalid User Flag Id", "id");
throw new ArgumentException("Invalid User Flag Id", nameof(id));
var syncTaskStatus = UpdateAssignedUsersLinkedGroup(UserFlag, GroupId, FilterBeginDate);
@@ -167,27 +176,28 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorize(Claims.Config.UserFlag.Configure)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult UpdateAssignedUserDevicesLinkedGroup(int id, string GroupId = null, DateTime? FilterBeginDate = null, bool redirect = false)
{
try
{
if (id < 0)
throw new ArgumentOutOfRangeException("id");
throw new ArgumentOutOfRangeException(nameof(id));
var UserFlag = Database.UserFlags.Find(id);
if (UserFlag == null)
throw new ArgumentException("Invalid User Flag Id", "id");
throw new ArgumentException("Invalid User Flag Id", nameof(id));
var syncTaskStatus = UpdateAssignedUserDevicesLinkedGroup(UserFlag, GroupId, FilterBeginDate);
@@ -200,14 +210,14 @@ namespace Disco.Web.Areas.API.Controllers
return RedirectToAction(MVC.Config.Logging.TaskStatus(syncTaskStatus.SessionId));
}
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
catch (Exception ex)
{
if (redirect)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
#endregion
@@ -347,6 +357,7 @@ namespace Disco.Web.Areas.API.Controllers
#region Actions
[DiscoAuthorizeAll(Claims.Config.UserFlag.Configure, Claims.Config.UserFlag.Delete)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Delete(int id, bool? redirect = false)
{
try
@@ -360,7 +371,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
return RedirectToAction(MVC.Config.Logging.TaskStatus(status.SessionId));
else
return Json("OK", JsonRequestBehavior.AllowGet);
return Ok();
}
throw new Exception("Invalid User Flag Id");
}
@@ -369,11 +380,12 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value)
throw;
else
return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
return BadRequest(ex.Message);
}
}
[DiscoAuthorizeAll(Claims.Config.UserFlag.Configure, Claims.User.Actions.AddFlags, Claims.User.Actions.RemoveFlags, Claims.User.ShowFlagAssignments)]
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult BulkAssignUsers(int id, bool Override, string UserIds = null, string Comments = null)
{
if (id < 0)