Currently I am writing a web application in MVC 4. I am using a generic repository pattern. It works well. So I have something like the followings,
public class AddressRepository : IAddressRepository
{
private AISDbContext context = new AISDbContext();
public IQueryable<Address> GetAddresses()
{
return context.Address;
}
}
But now I need to add something that filters the data more. Based on the logged in user's role, this data should be more filtered.
something like this..
public IQueryable<Address> GetAddresses()
{
return context.Address.where(x=>x.haspermissions = CURENTUSER.Role);
}
Now I could always add another function like this, but I want to try an be general. I want to know if I can just use the first bit of code and inherit from another class, that just applies the security trimming. This way I do not have to rewrite all my queries, I simply tell each class to inherit from the security trimmer. hope that makes sense..
Thanks
updated code
public class AddressRepository : SecureRepositoryBase<Address>, IAddressRepository
{
private AISDbContext context = new AISDbContext();
public IQueryable<Address> GetAll()
{
return base.RetrieveSecure(context.Address, 1);
}
}
public abstract class SecureRepositoryBase<T> where T : ISecuredEntity
{
public IQueryable<T> RetrieveSecure(IQueryable<T> entities, int currentUser)
{
return entities.Where(e => e.InspectorId == currentUser);
}
}
public interface ISecuredEntity
{
int? InspectorId { get; set; }
}
public class Address: ISecuredEntity
{
public int COESNo { get; set; }
public int Postcode { get; set; }
public int AuditAuthNo { get; set; }
public bool? SelectedForAudit { get; set; }
public int? RECId { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public int? CustomerSuburbId { get; set; }
public int? InspectorId { get; set; }
public DateTime? AuditDate { get; set; }
public int? AuditType { get; set; }
public int? UploadType { get; set; }
public string COESImage { get; set; }
public DateTime CreatedDate { get; set; }
public int? CreatedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public int? ModifiedBy { get; set; }
public virtual UserDetails Inspector { get; set; }
public virtual Postcodes CustomerSuburb { get; set; }
public virtual ResponsiblePerson RPerson { get; set; }
public virtual UserProfile CreatedByUser { get; set; }
public virtual UserProfile ModifiedByUser { get; set; }
}