From a441de1a450e73d496fe1edc78e1eb7a7e727f1f Mon Sep 17 00:00:00 2001 From: James Kolpack Date: Wed, 22 Jan 2014 21:48:15 -0500 Subject: [PATCH] Security for user editing only their own content --- Web/Attributes/LogOwnerAuthorizeAttribute.cs | 32 ++++++++++++++++++++ Web/Controllers/CreateLogController.cs | 4 +++ Web/Views/CreateLog/EditPast.cshtml | 2 +- Web/Web.csproj | 1 + 4 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 Web/Attributes/LogOwnerAuthorizeAttribute.cs diff --git a/Web/Attributes/LogOwnerAuthorizeAttribute.cs b/Web/Attributes/LogOwnerAuthorizeAttribute.cs new file mode 100644 index 0000000..1a85512 --- /dev/null +++ b/Web/Attributes/LogOwnerAuthorizeAttribute.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security; +using System.Web; +using System.Web.Mvc; +using MileageTraker.Web.DAL; +using MileageTraker.Web.Models; + +namespace MileageTraker.Web.Attributes +{ + public class LogOwnerAuthorizeAttribute : AuthorizeAttribute + { + protected override bool AuthorizeCore(HttpContextBase httpContext) + { + var authorized = base.AuthorizeCore(httpContext); + if (!authorized) + { + return false; + } + + var rd = httpContext.Request.RequestContext.RouteData; + + var id = int.Parse(rd.Values["id"].ToString()); + var dataService = new DataService(); + var log = dataService.GetLog(id); + + var userName = httpContext.User.Identity.Name; + return log.User.Username == userName; + } + } +} \ No newline at end of file diff --git a/Web/Controllers/CreateLogController.cs b/Web/Controllers/CreateLogController.cs index 49791fc..64ae75a 100644 --- a/Web/Controllers/CreateLogController.cs +++ b/Web/Controllers/CreateLogController.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Security; using System.Web.Mvc; using MileageTraker.Web.Attributes; using MileageTraker.Web.Models; @@ -36,6 +37,7 @@ namespace MileageTraker.Web.Controllers return View(model); } + [LogOwnerAuthorize] public ActionResult EditPast(int id) { var log = DataService.GetLog(id); @@ -53,6 +55,8 @@ namespace MileageTraker.Web.Controllers if (ModelState.IsValid) { var log = DataService.GetLog(viewModel.LogId); + if (log.User.Username != User.Identity.Name) + throw new SecurityException(); viewModel.SetProperties(log); if (viewModel.Purpose != null) diff --git a/Web/Views/CreateLog/EditPast.cshtml b/Web/Views/CreateLog/EditPast.cshtml index ec5a6be..5c16d69 100644 --- a/Web/Views/CreateLog/EditPast.cshtml +++ b/Web/Views/CreateLog/EditPast.cshtml @@ -16,7 +16,7 @@ @Html.EditorForModel()
- @Html.ActionLink("Cancel", "Index", new {}, new { @class = "btn btn-mini" }) + @Html.ActionLink("Cancel", "Index", new {}, new { @class = "btn" })
} diff --git a/Web/Web.csproj b/Web/Web.csproj index fee8cae..1e37a61 100644 --- a/Web/Web.csproj +++ b/Web/Web.csproj @@ -112,6 +112,7 @@ +