Question

I've looked around how to log the username of the current user in the revision entity table of Envers. However, there's little information and the information I did manage to find wasn't that helpful.

I have a revision entity and listener which looks like this:

[RevisionEntity(typeof(EnversRevisionListener))]
public class EnversRevisionEntity : DefaultRevisionEntity
{
    public virtual string UserName { get; set; }
}

public class EnversRevisionListener : IRevisionListener
{
    private string _userName = "unknown";

    public EnversRevisionListener(string userName)
        : base()
    {
        _userName = userName;
    }

    public void NewRevision(object revisionEntity)
    {
        var casted = revisionEntity as EnversRevisionEntity;

        if (casted != null)
        {
            casted.UserName = _userName;
        }
    }
}

I want to use these two inside an ASP.NET environment. The configuration and sessions factory are created once as that is an expensive action. For each transaction, a new session is opened.

From this NHE Jira issue and this, related, SO question I understand that it is possible to register the username with the listener when configuring nHibernate.

However, that's not good enough for me as that would register the username of whoever connects to the application first for each and every transaction.

I need to be able to provide the username related to a specific transaction to the listener.

Previously, I used poor man's auditing using nHibernate's pre- and post-update event listeners. Here I faced a similar problem as these listeners are also associated with the session factory and not the session. Therefore I switched to old style interceptors, which can be associated with the session inside OpenSession. This allowed me to add the current user to the interceptor.

However, I don't know how to solve the same problem for Envers. I hope someone can help.

Was it helpful?

Solution

You can use Thread.CurrentPrinicpal property (MSDN). ASP.NET membership mechanism sets it to identity associated with currently logged user

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top