Search code examples
coldfusioncfmlcoldbox

How to I Store, Retrieve, and Update Session User Data Using Cbauth in a Coldbox App?


Cbauth is a Forgebox module commonly used in Coldbox applications to handle user authentication.

To retrieve information on the currently logged in user, you can call auth().getUser(). This method calls retrieveUserById() in the app defined user service class. In my case, retrieveUserById() goes to the database, retrieves the user data and then returns an assembled User entity object.

In my project, I would like to display the first name and an avatar of the currently logged in user on every page. I'd like to avoid going back to the database on each page request because caching at least some user data (or maybe even the entire User entity) would be more efficient.

Is there a way within Cbauth to store custom data in the user's session scope, request it, and later update it (e.g. if the user updates their name while logged in)

Here's what I've tried so far:

According to the docs, Cbauth has an interceptor called postAuthentication which does pass sessionStorage as an argument. I believe I could leverage this to store additional data for the current user. However, when I try to reference user in the interceptor I get an Element USER is undefined in ARGUMENTS error message.

// After a user authenticates, store the user entity in the session (does not work)
function postAuthentication( user, sessionStorage, requestStorage ) {
    arguments.sessionStorage.user = arguments.user;
}

Additionally, I don't see any way to retrieve the cached session data once it has been stored. Any help or pointers to examples where Cbauth has been implemented successfully would be greatly appreciated!


Solution

  • The data you are trying to reference is inside the interceptData struct. The method signature of any interceptor is as follows:

    function interceptorName( required struct interceptData, required buffer, event, rc, prc );
    

    So you would access user as arguments.interceptData.user and store it using arguments.sessionStorage.setVar( "user", arguments.interceptData.user ); (sessionStorage is not the session scope. It is a facade provided by cbstorages.

    Here's the full interceptor signature modified from above:

    function postAuthentication( interceptData ) {
        arguments.interceptData.sessionStorage.setVar(
            "user",
            arguments.interceptData.user
        );
    }