Manage users from your backend
Create, find, change and block users from your own code, with a scoped API key.
What it shows
- Your backend creates the user Lena Hoffmann, with no password. When the address exists from an earlier run, it finds that user instead.
- It changes the name of the user. A
PATCHchanges only the fields that it sends. - It blocks the user. LumoAuth ends the sessions of the user and revokes the tokens that were issued to the user.
- It lists the blocked users whose email address, name or username contains
hoffmann, page by page.
The JavaScript and Python programs use the generated API clients, which are made from the description of the Admin API. The CLI script uses lumo users, and the HTTP script uses curl.
Before you start
- An API key with the scopes
admin:users:readandadmin:users:write. Create it in the portal under Applications & developer tools, API keys. - For the CLI script: the
lumoCLI andjq. For the HTTP script: curl andjq.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scopes admin:users:read and admin:users:write. |
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The JavaScript program uses the generated client for every call. In Python, create_user and patch_user of the generated client send no body, so the program uses requests for these two calls.
- Node.js
- Python
- lumo CLI
- curl
accounts/users-with-the-admin-api/js/users.mjs
// Create a user, change the name, block the user, and find the user in the
// list again, with the generated client @lumoauth/api-client.
//
// node accounts/users-with-the-admin-api/js/users.mjs
//
// The API key needs the scopes admin:users:read and admin:users:write.
import { AdminUsersApi, Configuration } from '@lumoauth/api-client';
const orgId = process.env.LUMOAUTH_ORG_ID;
const users = new AdminUsersApi(
new Configuration({
basePath: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
apiKey: process.env.LUMOAUTH_API_KEY,
}),
);
const email = 'lena.hoffmann@example.com';
// 1. Create the user. Without a password, the person signs in with another
// method or sets a password through a reset link. createUser has no body
// parameter, so the body goes in the request options of the client.
let user;
try {
const created = await users.createUser(
{ orgId },
{ data: { email, name: 'Lena Hoffmann', givenName: 'Lena', familyName: 'Hoffmann' } },
);
user = created.data.data;
} catch (error) {
// 409: a user with this address exists, from an earlier run.
if (error.response?.status !== 409) throw error;
const found = await users.listUsers({ orgId, search: email });
user = found.data.data.find((u) => u.email === email);
}
console.log(`user: ${user.email} (${user.id})`);
// 2. Change the name. PATCH changes only the fields that you send.
const updated = await users.patchUser(
{ orgId, userId: user.id },
{ data: { name: 'Lena Hoffmann-Weber', familyName: 'Hoffmann-Weber' } },
);
console.log(`updated: ${updated.data.data.name}`);
// 3. Block the user. This ends the sessions of the user and revokes the
// tokens that were issued to the user.
await users.blockUser({ orgId, userId: user.id });
console.log(`blocked: ${user.email}`);
// 4. List the blocked users whose email, name or username contains
// "hoffmann", page by page. The search is case-sensitive.
const rows = [];
for (let page = 1; ; page++) {
const { data } = await users.listUsers({ orgId, search: 'hoffmann', blocked: true, page, limit: 25 });
rows.push(...data.data);
if (!data.pagination.hasNextPage) break;
}
console.log(`blocked users matching "hoffmann": ${rows.length}`);
for (const row of rows) console.log(` ${row.email} ${row.name}`);
node accounts/users-with-the-admin-api/js/users.mjs
accounts/users-with-the-admin-api/python/users.py
# Create a user, change the name, block the user, and find the user in the
# list again, with the generated client lumoauth-api-client.
#
# python accounts/users-with-the-admin-api/python/users.py
#
# The API key needs the scopes admin:users:read and admin:users:write.
import os
import lumoauth_api_client as lumo
import requests
base_url = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev")
org_id = os.environ["LUMOAUTH_ORG_ID"]
api_key = os.environ["LUMOAUTH_API_KEY"]
client = lumo.ApiClient(lumo.Configuration(host=base_url, api_key={"ApiKeyAuth": api_key}))
users = lumo.AdminUsersApi(client)
# create_user and patch_user of the generated client send no body, so these
# two calls use requests.
admin_users = f"{base_url}/orgs/{org_id}/api/v1/admin/users"
headers = {"X-API-Key": api_key}
email = "lena.hoffmann@example.com"
# 1. Create the user. Without a password, the person signs in with another
# method or sets a password through a reset link.
answer = requests.post(
admin_users,
headers=headers,
json={"email": email, "name": "Lena Hoffmann", "givenName": "Lena", "familyName": "Hoffmann"},
)
if answer.status_code == 409:
# A user with this address exists, from an earlier run.
found = users.list_users(org_id, search=email)
user_id = next(u.id for u in found.data if u.email == email)
else:
answer.raise_for_status()
user_id = answer.json()["data"]["id"]
print(f"user: {email} ({user_id})")
# 2. Change the name. PATCH changes only the fields that you send.
answer = requests.patch(
f"{admin_users}/{user_id}",
headers=headers,
json={"name": "Lena Hoffmann-Weber", "familyName": "Hoffmann-Weber"},
)
answer.raise_for_status()
print(f"updated: {answer.json()['data']['name']}")
# 3. Block the user. This ends the sessions of the user and revokes the
# tokens that were issued to the user.
users.block_user(org_id, user_id)
print(f"blocked: {email}")
# 4. List the blocked users whose email, name or username contains
# "hoffmann", page by page. The search is case-sensitive.
rows = []
page = 1
while True:
answer = users.list_users(org_id, search="hoffmann", blocked=True, page=page, limit=25)
rows.extend(answer.data)
if not answer.pagination.has_next_page:
break
page += 1
print(f'blocked users matching "hoffmann": {len(rows)}')
for row in rows:
print(f" {row.email} {row.name}")
python accounts/users-with-the-admin-api/python/users.py
accounts/users-with-the-admin-api/cli/users.sh
#!/bin/sh
# Create a user, change the name, block the user, and find the user in the
# list again, with the lumo CLI.
#
# sh accounts/users-with-the-admin-api/cli/users.sh
#
# The script needs the lumo CLI and jq. The API key needs the scopes
# admin:users:read and admin:users:write.
set -eu
# The CLI reads its own three variables. With them it needs no `lumo login`.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
EMAIL=lena.hoffmann@example.com
# 1. Create the user. Without a password, the person signs in with another
# method or sets a password through a reset link. With -o json, a refusal
# is printed as JSON too, with the HTTP status.
if ANSWER=$(lumo users create --email "$EMAIL" --name "Lena Hoffmann" \
--given-name Lena --family-name Hoffmann -o json); then
USER_ID=$(printf '%s\n' "$ANSWER" | jq -r .data.id)
elif [ "$(printf '%s\n' "$ANSWER" | jq -r .status)" = 409 ]; then
# A user with this address exists, from an earlier run.
USER_ID=$(lumo users get "$EMAIL" -o json | jq -r .data.id)
else
echo "$ANSWER" >&2
exit 1
fi
echo "user: $EMAIL ($USER_ID)"
# 2. Change the name. Only the flags that you pass are changed.
NAME=$(lumo users update "$USER_ID" --name "Lena Hoffmann-Weber" \
--family-name Hoffmann-Weber -o json | jq -r .data.name)
echo "updated: $NAME"
# 3. Block the user. This ends the sessions of the user and revokes the
# tokens that were issued to the user.
lumo users block "$USER_ID" -o json > /dev/null
echo "blocked: $EMAIL"
# 4. List the blocked users whose email, name or username contains
# "hoffmann", page by page. The search is case-sensitive.
ROWS=""
PAGE=1
while :; do
ANSWER=$(lumo users list --search hoffmann --blocked --page "$PAGE" --limit 25 -o json)
ROWS="$ROWS$(printf '%s\n' "$ANSWER" | jq -r '.data[] | " \(.email) \(.name)"')
"
[ "$(printf '%s\n' "$ANSWER" | jq -r .pagination.hasNextPage)" = true ] || break
PAGE=$((PAGE + 1))
done
echo "blocked users matching \"hoffmann\": $(printf '%s' "$ROWS" | grep -c .)"
printf '%s' "$ROWS"
sh accounts/users-with-the-admin-api/cli/users.sh
accounts/users-with-the-admin-api/http/users.sh
#!/bin/sh
# Create a user, change the name, block the user, and find the user in the
# list again, with curl.
#
# sh accounts/users-with-the-admin-api/http/users.sh
#
# The script needs curl and jq. The API key needs the scopes
# admin:users:read and admin:users:write.
set -eu
API="${LUMOAUTH_URL:-https://app.lumoauth.dev}/orgs/$LUMOAUTH_ORG_ID/api/v1/admin/users"
EMAIL=lena.hoffmann@example.com
# One call to the Admin API: prints the answer, then the status on a last line.
call() {
curl -sS -w '\n%{http_code}' -H "X-API-Key: $LUMOAUTH_API_KEY" -H 'Content-Type: application/json' "$@"
}
# 1. Create the user. Without a password, the person signs in with another
# method or sets a password through a reset link.
ANSWER=$(call -X POST "$API" \
-d "{\"email\": \"$EMAIL\", \"name\": \"Lena Hoffmann\", \"givenName\": \"Lena\", \"familyName\": \"Hoffmann\"}")
STATUS=$(printf '%s\n' "$ANSWER" | tail -n 1)
if [ "$STATUS" = 201 ]; then
USER_ID=$(printf '%s\n' "$ANSWER" | sed '$d' | jq -r .data.id)
elif [ "$STATUS" = 409 ]; then
# A user with this address exists, from an earlier run.
USER_ID=$(call -G "$API" --data-urlencode "search=$EMAIL" | sed '$d' |
jq -r --arg email "$EMAIL" '.data[] | select(.email == $email) | .id')
else
echo "$ANSWER" >&2
exit 1
fi
echo "user: $EMAIL ($USER_ID)"
# 2. Change the name. PATCH changes only the fields that you send.
NAME=$(call -X PATCH "$API/$USER_ID" -d '{"name": "Lena Hoffmann-Weber", "familyName": "Hoffmann-Weber"}' |
sed '$d' | jq -r .data.name)
echo "updated: $NAME"
# 3. Block the user. This ends the sessions of the user and revokes the
# tokens that were issued to the user.
call -X POST "$API/$USER_ID/block" > /dev/null
echo "blocked: $EMAIL"
# 4. List the blocked users whose email, name or username contains
# "hoffmann", page by page. The search is case-sensitive.
ROWS=""
PAGE=1
while :; do
ANSWER=$(call -G "$API" -d search=hoffmann -d blocked=true -d page="$PAGE" -d limit=25 | sed '$d')
ROWS="$ROWS$(printf '%s\n' "$ANSWER" | jq -r '.data[] | " \(.email) \(.name)"')
"
[ "$(printf '%s\n' "$ANSWER" | jq -r .pagination.hasNextPage)" = true ] || break
PAGE=$((PAGE + 1))
done
echo "blocked users matching \"hoffmann\": $(printf '%s' "$ROWS" | grep -c .)"
printf '%s' "$ROWS"
sh accounts/users-with-the-admin-api/http/users.sh
Check the result
Output
user: lena.hoffmann@example.com (01a21fe2-6db0-7771-acc8-387816ffa0d4)
updated: Lena Hoffmann-Weber
blocked: lena.hoffmann@example.com
blocked users matching "hoffmann": 1
lena.hoffmann@example.com Lena Hoffmann-Weber
- Run the program again. The output is the same: the user exists, so step 1 finds it.
- In the portal, open Users and search for Lena. The row shows the new name and the state Blocked.
- In the portal, open Audit logs. The entries
user.created,user.updatedanduser.blockedname your API key as the actor. - A person who is signed in when you block them loses the session at once. Their refresh token answers
invalid_grant, and their access token is refused.
Limits
- The Admin API takes a password only as plain text, and checks it against the password policy of the organization. It has no field for a password hash from another system. People from another system sign in with a passwordless method or set a password with Forgot password?. See Move users from another provider.
- The search is case-sensitive:
hoffmannfinds the email address,Hoffmannfinds the name. - A user does not have free-form metadata. A request with a non-empty
metadataobject is refused. - Changing the email address, the active state or the verified state needs a caller who holds every permission of the user.
- To undo step 3, call
POST /admin/users/{userId}/unblock, or runlumo users unblock.