Auth0 Home Blog Docs

Last_login not available in user object in custom rule

rules

#1

I have created a custom Rule that looks like this:

function (user, context, callback) {
context.idToken[‘https://www.kiva.org/last_login’] = user.last_login;
callback(null, user, context);
}

But last_login is not defined on the user object so it’s not working. The fields on the user object are: _id, email, clientID, update_at, name, picture, user_id, nickname, identities, created_at, global_client_id, and persistent. However, when I look at the raw JSON of the user I’m fetching, it includes last_login (and also last_ip, logins_count, and other fields). Why is last_login unavailable? Is there some other way I can include last_login in the returned ID Token?


#3

Hello!

This is because there would be a caveat: rules execute after a successful authentication, meaning that the last_login value would be the value for the current time and date.

What you could do is set the value to the app_metadata, and grab it from there. Your rule would look something like this:

    user.app_metadata = user.app_metadata || {};

    // Grab the current value of last login and print it
    var previous_login = user.app_metadata.previous_login
    console.log(previous_login)

    // Write the new value to the metadata
    user.app_metadata.previous_login = Date.now()

    // Persist the app_metadata update
    auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
        .then(function(){
            callback(null, user, context);
        })
        .catch(function(err){
            callback(err);
        });
}

You can also try implementing some logic before it prints to actually check that the value exists, and print “First login!” otherwise.


#4

Hey @ledlie!

What @joseantonio.rey mentioned is totally correct. In addition to that, looking at our docs and user object properties, here you’ve got an official description of last_login property:

last_login : The timestamp of when the user last logged in. Using this property from inside a Rule using the user object, its value will be the one associated with the login that triggered the rule (since rules execute after the actual login).

Here’s the reference point:

Let us know if that helped!