I would like to find a subset of auth0 users who have a metadata field value contained in a list that I am passing in.
Simplified example, Find all users where the metadata field value is 1, 2, or 3.
In my case the list of values I would like to query against is several hundred long and I don’t think concatenating OR clauses in the query syntax of the user filter is a realistic option due to length restrictions.
If there is a way to accomplish this I would very much love to know!
To find Auth0 users based on a metadata field value contained in a list of several hundred options, you can use the Auth0 Management API’s “Get Users” endpoint with a query parameter (q) for filtering. Auth0 supports a simplified query syntax where you can specify conditions like metadata.fieldName:(value1 OR value2 OR … OR valueN) to find users. For instance, if your metadata field is named myField and you want to find users with values 1, 2, or 3 in myField, your query would be q=metadata.myField:(1 OR 2 OR 3). This approach avoids the need to concatenate numerous OR clauses manually, making it efficient and straightforward to filter users based on your criteria. Ensure you handle pagination if the result set is large, as the API response will be paginated by default.
from dotenv import load_dotenv
import os
from auth0.authentication import GetToken
from auth0.management import Auth0
load_dotenv()
DOMAIN = os.getenv('AUTH0_DOMAIN')
CLIENT_ID=os.getenv('AUTH0_CLIENT_ID')
CLIENT_SECRET=os.getenv('AUTH0_CLIENT_SECRET')
get_token = GetToken(DOMAIN, CLIENT_ID, client_secret=CLIENT_SECRET)
token = get_token.client_credentials('https://{}/api/v2/'.format(DOMAIN))
mgmt_api_token = token['access_token']
auth0 = Auth0(DOMAIN, mgmt_api_token)
data = auth0.users.list()
values_to_check = ['value1', 'value2', 'value3']
matching_users = [
user['email'] for user in data['users']
if 'user_metadata' in user and any(value in values_to_check for value in user['user_metadata'].values())
]
print(matching_users)
Regretfully the total of users in the system is greater than the 1000 limit of the management api functionality. Which is why I was trying to break down the requests into smaller chunks that I knew would be under 1000 users.
Given the number of users, you could look into using the /v2/jobs/post-users-exports endpoint instead. This will at least allow you to get all users and then filter accordingly.