Check many permissions at once
Decide what a page shows with one request: every button of a toolbar, or every row of a table.
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
What it shows
- A toolbar has four buttons: view, edit, delete and share. Each button needs one permission.
- Your backend sends the four permissions in one request. The answer has one result for each.
- The page shows a button when its result is true. Maya holds a role with three of the permissions, so the delete button stays hidden.
- Two more requests answer a compound rule: "any of" these permissions, and "all of" them.
Your backend can send the results with the data of the page. The browser then needs no request of its own.
Before you start
- An API key with the scope
authz:check. Create it in the portal: open API keys, under Applications & developer tools. - Four permissions, a role that holds three of them, and one user. The setup script creates them. Its API key also needs
admin:permissions:write,admin:roles:writeandadmin:users:write.
| 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 scope authz:check. |
EDITOR_USER_ID | The ID of a user who holds three of the four permissions. The setup script prints it. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node authorization/bulk-checks/setup.mjs
setup.mjs
// Creates what the recipe needs: four permissions, a role that holds three of
// them, and one test user with the role. Run it again at any time.
//
// node authorization/bulk-checks/setup.mjs
//
// The API key needs the scopes admin:permissions:write, admin:roles:write
// and admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
for (const [slug, name] of [
['documents.view', 'View documents'],
['documents.edit', 'Edit documents'],
['documents.delete', 'Delete documents'],
['documents.share', 'Share documents'],
]) {
await ensure('/admin/permissions', (p) => p.slug === slug, { name, slug });
}
const role = await ensure('/admin/roles', (r) => r.slug === 'document-editor', {
name: 'Document editor',
slug: 'document-editor',
description: 'May view, edit and share documents, and may not delete them.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, {
permissions: ['documents.view', 'documents.edit', 'documents.share'],
});
const editor = await ensure('/admin/users', (u) => u.email === 'document-editor@example.com', {
email: 'document-editor@example.com',
name: 'Maya Chen',
// The recipe never signs in as this user, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
await call('PUT', `/admin/users/${editor.id}/roles`, { roles: [role.slug] });
console.log(`Four permissions, the role ${role.slug}, and one user are ready.`);
printEnv({ EDITOR_USER_ID: editor.id });
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 programs were run with built-in permissions. On a new organization the setup script stops at the step that adds the new permissions to the role. The curl version prints the JSON answers of the three requests.
- Node.js
- Python
- Go
- curl
authorization/bulk-checks/js/toolbar.mjs
// Ask about every button of a toolbar with one request, then ask two
// compound questions.
//
// node authorization/bulk-checks/js/toolbar.mjs
import { LumoAuthBackend } from '@lumoauth/backend';
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});
// One permission for each button: view, edit, delete, share.
const buttons = (process.env.PERMISSIONS ?? 'documents.view,documents.edit,documents.delete,documents.share').split(',');
// The key asks about another person, so it names that person as the subject.
const subject = { userId: process.env.EDITOR_USER_ID };
// One request for the whole toolbar.
const { results } = await lumo.permissions.checkBulk(buttons, undefined, subject);
for (const permission of buttons) {
console.log(`${permission} -> ${results[permission] ? 'show' : 'hide'}`);
}
// "Any of" and "all of", each with one request.
const editOrDelete = [buttons[1], buttons[2]];
const any = await lumo.permissions.checkAny(editOrDelete, undefined, subject);
const all = await lumo.permissions.checkAll(editOrDelete, undefined, subject);
console.log(`any of ${editOrDelete.join(', ')} -> ${any ? 'allowed' : 'denied'}`);
console.log(`all of ${editOrDelete.join(', ')} -> ${all ? 'allowed' : 'denied'}`);
node authorization/bulk-checks/js/toolbar.mjs
authorization/bulk-checks/python/toolbar.py
"""Ask about every button of a toolbar with one request, then ask two
compound questions.
python authorization/bulk-checks/python/toolbar.py
"""
import os
from lumoauth import LumoAuth
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumo = LumoAuth()
# One permission for each button: view, edit, delete, share.
buttons = os.environ.get("PERMISSIONS", "documents.view,documents.edit,documents.delete,documents.share").split(",")
# The key asks about another person, so it names that person as the subject.
user_id = os.environ["EDITOR_USER_ID"]
# One request for the whole toolbar.
results = lumo.permissions.check_bulk(buttons, user_id=user_id)["results"]
for permission in buttons:
print(f"{permission} -> {'show' if results[permission] else 'hide'}")
# "Any of" and "all of", each with one request.
edit_or_delete = [buttons[1], buttons[2]]
any_of = lumo.permissions.check_any(edit_or_delete, user_id=user_id)
all_of = lumo.permissions.check_all(edit_or_delete, user_id=user_id)
print(f"any of {', '.join(edit_or_delete)} -> {'allowed' if any_of else 'denied'}")
print(f"all of {', '.join(edit_or_delete)} -> {'allowed' if all_of else 'denied'}")
python authorization/bulk-checks/python/toolbar.py
authorization/bulk-checks/go/main.go
// Ask about every button of a toolbar with one request, then ask two
// compound questions.
//
// go run ./authorization/bulk-checks/go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func answer(allowed bool) string {
if allowed {
return "allowed"
}
return "denied"
}
func main() {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
client, err := lumoauth.New()
if err != nil {
log.Fatal(err)
}
// One permission for each button: view, edit, delete, share.
permissions := os.Getenv("PERMISSIONS")
if permissions == "" {
permissions = "documents.view,documents.edit,documents.delete,documents.share"
}
buttons := strings.Split(permissions, ",")
// The key asks about another person, so it names that person as the subject.
subject := &lumoauth.CheckOptions{UserID: os.Getenv("EDITOR_USER_ID")}
// One request for the whole toolbar.
ctx := context.Background()
bulk, err := client.Permissions.CheckBulk(ctx, buttons, subject)
if err != nil {
log.Fatal(err)
}
for _, permission := range buttons {
show := "hide"
if bulk.Results[permission] {
show = "show"
}
fmt.Printf("%s -> %s\n", permission, show)
}
// "Any of" and "all of", each with one request.
editOrDelete := []string{buttons[1], buttons[2]}
anyOf, err := client.Permissions.CheckAny(ctx, editOrDelete, subject)
if err != nil {
log.Fatal(err)
}
allOf, err := client.Permissions.CheckAll(ctx, editOrDelete, subject)
if err != nil {
log.Fatal(err)
}
fmt.Printf("any of %s -> %s\n", strings.Join(editOrDelete, ", "), answer(anyOf))
fmt.Printf("all of %s -> %s\n", strings.Join(editOrDelete, ", "), answer(allOf))
}
go run ./authorization/bulk-checks/go
authorization/bulk-checks/http/toolbar.sh
#!/bin/sh
# Ask about every button of a toolbar with one request, then ask two compound
# questions, with curl.
#
# sh authorization/bulk-checks/http/toolbar.sh
set -eu
# One permission for each button: view, edit, delete, share.
BUTTONS="${PERMISSIONS:-documents.view,documents.edit,documents.delete,documents.share}"
# The lists as JSON: all four, then the second and the third.
ALL_BUTTONS="\"$(printf '%s\n' "$BUTTONS" | sed 's/,/", "/g')\""
EDIT_OR_DELETE="\"$(printf '%s\n' "$BUTTONS" | cut -d, -f2,3 | sed 's/,/", "/g')\""
# The key asks about another person, so each request names that person.
SUBJECT="{\"type\": \"user\", \"id\": \"$EDITOR_USER_ID\"}"
# These endpoints are not under /orgs/{org}: the API key names the organization.
authz() {
curl --silent --show-error "$LUMOAUTH_URL/api/v1/authz/$1" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
--data "{\"permissions\": [$2], \"subject\": $SUBJECT}"
echo
}
# One request for the whole toolbar. The answer has one result for each permission.
authz check-bulk "$ALL_BUTTONS"
# "Any of" and "all of", each with one request.
authz check-any "$EDIT_OR_DELETE"
authz check-all "$EDIT_OR_DELETE"
sh authorization/bulk-checks/http/toolbar.sh
Check the result
Output
documents.view -> show
documents.edit -> show
documents.delete -> hide
documents.share -> show
any of documents.edit, documents.delete -> allowed
all of documents.edit, documents.delete -> denied
- Add
documents.deleteto the role in the portal, and run the program again: the third line says "show", and "all of" is allowed. - To ask from the browser, with the token of the signed-in person, use the same call on the client of
@lumoauth/react. The page usePermission shows it. The network panel of the browser then shows one request for the whole toolbar.
Limits
- One request takes at most 100 permissions. A longer list gets the answer 400 with the code
TOO_MANY_PERMISSIONS: split it. - The results hide controls. Check the permission again in the API that does the work, because a browser can be changed.
- "Any of" and "all of" answer with one yes or no. They do not say which permission decided.
- The endpoint that lists every permission of a person,
GET /api/v1/authz/permissions, takes only an access token with the scopeauthz:read. An API key cannot call it.