Reputation: 3803
I have a model in MVC which looks like this
public class PdfFile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Data { get; set; } //this is a ByteArray of the PDF file
public int DataCount { get; set; }
public DateTime Created { get; set; }
public DateTime LockedOn { get; set; }
public string CreatedBy { get; set; }
public string SecurityInfo { get; set; } // actually a xml to check security level
public string UserGroup { get; set; }
}
and In my DbContext I have
public DbSet<PdfFile> PdfSet { get; set; }
and in my Identity model I have a variable UserGroup
public string UserGroup { get; set; }
Now in my controller everytime I have to check if a user has permission to access the Pdf File I have to do
[Authorize]
[NoUserGroupNoAccess] // this is a custom filter to ensure that the user has a UserGroup & is not null or empty
public ActionResult SendSingleItem(int? id)
{
var model = db.PdfSet.Find(id);
if (model != null && model.UserGroup == User.UserGroup)
{
return View(model);
}
return null;
}
Now imagine this scenario where everytime I have to access the model either for edit details, delete etc I have to check
if (model.UserGroup == User.UserGroup) // plus I have to check XML in secureinfo for individual for each user when editing or deleting
for lists i have to do
var dblist = db.PdfSet.ToList();
dblist = dblist.Where(u => u.UserGroup == User.UserGroup).ToList();
This makes the controller code very ugly and hard to debug on error Is there any way I can do these checks in my DbContext directly when Editing, Creating, Deleting, Accessing the record?
I am not even sure if this is the correct method to do security check for Users.
Upvotes: 2
Views: 1259
Reputation: 11544
I agree with you it makes code ugly and hard to maintain but it's not a good idea to couple data access with cross-cutting concerns and consider using role. Create a role and determine the role has access to which part of the application then assign a user to a role. Create a role and name it PdfAccess
and use the Authorize
attribute with the role:
[Authorize("PdfAccess")]
[NoUserGroupNoAccess]
public ActionResult SendSingleItem(int? id)
Upvotes: 3