Retrieve Logins Count per Application

Problem statement

This article explains whether it is possible to retrieve the logins count per application.

Solution

There is no out-of-the-box way to do this.

One solution would be to create an action that would add the logins count per application to the user’s profile:

exports.onExecutePostLogin = async (event, api) => {
  const loginsCount = event.user.app_metadata.applicationLoginsCount || {};
  const currentApplication = event.client.name;

  if(!loginsCount.hasOwnProperty(currentApplication)) {
    loginsCount[currentApplication] = 0;
  }

  loginsCount[currentApplication]++;

  api.user.setAppMetadata('applicationLoginsCount', loginsCount);
}

This would result in each user’s app_metadata having an applicationLoginsCount attribute that includes the logins count per application:

    "app_metadata": {
        "applicationLoginsCount": {
            "Example app": 2,
            "Another app": 1
        }
    }

One can then use the User Import / Export extension and include the app_metadata.applicationLoginsCount field in the output:

With the data exported, it’s then possible to process the data to retrieve the total login count per application. Here’s an example in Python:

import json

def count_entries(json_data):
    counts = {}
    for entry in json_data:
        applicationLoginsCount = entry.get("applicationLoginsCount", {})
        for app, count in applicationLoginsCount:
            counts[app] = counts.get(app, 0) + count
    return counts

file_path = "export.json"  # Replace with user export filename
data = []
with open(file_path, "r") as file:
    for line in file:
        data.append(json.loads(line))

result = count_entries(data)

for app, count in result.items():
    print(f"{count} {app}")