As the subject suggests, has anyone tried implementing field level security with NHibernate? If so, I would love to see a code example -- I'm not interested in the security authorization mechanism persay but I'm rather curious regarding NHibernate's integration with it. I would like to have the security checks ran when the entity is hydrated rather than in the ui layer as I've seen in other examples. My newbie approach is listed below. Does anyone else have a better solution (a custom proxy might be cleaner)?
public class Entity
{
public virtual int Id { get; set; }
}
public class SecureEntity : Entity
{
public virtual bool IsViewableByCurrentUser { get; set; }
}
public class Document : SecureEntity
{
public virtual string Title { get; set; }
}
public class Company : SecureEntity
{
protected virtual Document _secrectCompanyDocument { get; private set; }
public virtual Document SecretCompanyDocument
{
//if the current user doesn't have view permission then return null
get { return _secrectCompanyDocument.IsViewableByCurrentUser ? _secrectCompanyDocument : null; }
}
}
public class SecureEntityPostLoad : IPostLoadEventListener
{
public void OnPostLoad(PostLoadEvent postLoadEvent)
{
SecureEntity secureEntity = postLoadEvent.Entity as SecureEntity;
if (secureEntity != null)
{
//replace with a call to ISecurityTasks.IsViewableByCurrentUser(secureEntity);
secureEntity.IsViewableByCurrentUser = true;
}
}
}
class Program
{
static void Main(string[] args)
{
ISessionFactory sessionFactory = NHibernateInitializer.Initialize().BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
var company = session.Get<Company>(1);
var title = company.SecretCompanyDocument.Title;
}
}
}