Deny login when active session exists

I am trying to make a post-login action that check if any sessions related to the user exists. If any sessions exist the new users should be denied.

I tried this:
exports.onExecutePostLogin = async (event, api) => {

const ManagementClient = require(‘auth0’).ManagementClient;

const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
});

const sessions = await management.getUserSessions({ user_id: event.user.user_id });

// If there are existing sessions, reject the login attempt
if (sessions.length > 0) {
api.access.deny(User aready logged in on (${sessions.length}) other device);
}

};

but it says that the functions does not exist. The goal is to never have more than one session at a time by the same user. I want to do this, to restrict the user to use one device at a time.

Can anyone help with this?

Hi @moj,

Welcome to the Auth0 Community!

Firstly, with the ManagementClient, there are no methods that can get the user’s session, nor is there a method called getUserSessions (Reference: management | auth0).

Instead, you can call the event.session property in your action script to get details about the user’s current session. From there, you can inquire whether the user was previously logged in somewhere else. Using the user_metadata to store this information could also be helpful.

Let me know if you have any questions.

Thanks,
Rueben

1 Like

Thank you for the answer.

I’m not sure how I would inquire whether the user was previously logged in somewhere else. Would you store the session id’s in the user meta data?

Could you elaborate on how i would implement this?

Hi @moj,

Thanks for your reply.

I have done some testing and found that the event.session object does not return enough information about the user’s session to inquire whether it’s an active session.

Not only do we need the session_id to determine whether the session is the one that exists, but we also need to ensure that the session is active by checking the expires_at property.

To do this, you will need to use the Management API in your Action script to get the user’s session.

I hope this helps!

Cheers,
Rueben

Have you figured this? @moj

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