Last_login not available in user object in custom rule

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?

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.

1 Like

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!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.

Hey there everybody!

A quick update regarding this one. last_login property has been deleted from Rules documentation and you should be using that instead: