Appearance
9. Accounts and sign-in
In part 6 the guard trusted whatever senderIdentity a request named. Real customers sign in. In this part the shop gets an HTTP API with accounts, passwords and sessions, and the hand-written guard is replaced by the kit: tenants, accounts, groups, invitation links, and a middleware that decides every request.
The story: Ann opens her shop on your platform. She creates a group of customers and puts an invitation link on her website. Bob and Cleo sign up and join through it. Each may work only on their own orders.
Copy the kit
The kit is source code you copy into your project, not a dependency:
sh
npx @kernable/sdk add kit
npm install @node-rs/argon2 @simplewebauthn/server openid-clientsh
.venv/bin/kernable-sdk add kit
.venv/bin/pip install -r kit/requirements.txtsh
cargo install kernable-sdk
kernable-sdk add kit # then add the crate `kit` to your workspace and as a dependencyStop the guard from part 6 and the confirmations reactor from part 4: from now on the kit's middleware decides, and a reactor needs an identity of its own under it (see Identities).
Say what a query is about
GetOrder { id: "o1" } is about order o1, but only the shop's code knows that id names an order. Declare it once, in the domain:
ts
// GetOrder { id } is about the order `id`: the SDK sends that order with the query, signed, and a
// middleware decides on it as on a command's aggregate (part 9).
shopDomain.query("GetOrder").target("order", "id");py
# GetOrder {"id": ...} is about the order `id`: the SDK sends that order with the query, signed, and a
# middleware decides on it as on a command's aggregate (part 9).
shop_domain.query("GetOrder").target("order", "id")rs
// GetOrder { id } is about the order `id`: the SDK sends that order with the query, signed, and a
// middleware decides on it as on a command's aggregate (part 9).
fn target(shop_domain: &Domain) {
shop_domain.query("GetOrder").target("order", "id");
}Now a rule can say "only the order's owner may read it", for queries as for commands.
The API
One new process, api, runs the kit's domains and its example HTTP server. It declares who owns an order, from the shop's own events:
ts
// Who owns an order: the customer it was placed for. Declared before the kit's domains start.
relation("shop.order", "owner").set("shop.OrderPlaced", (e) => e.data.customerId);py
# Who owns an order: the customer it was placed for. Declared before the kit's domains start.
relation("shop.order", "owner").set("shop.OrderPlaced", lambda e: e.data["customer_id"])rs
// Who owns an order: the customer it was placed for. Declared before the kit's domains start.
relation("shop.order", "owner").set("shop.OrderPlaced", |e| ids(&e.data["customerId"]));The kit sends mail for email verification, password resets and invitations. In development, the API writes each mail to a file in mail/ instead:
ts
// In development the kit's mails go to files in mail/, named by address, instead of a mail server.
mkdirSync("mail", { recursive: true });
useMailer({ async send(mail) { writeFileSync(`mail/${mail.to}`, mail.token); } });py
# In development the kit's mails go to files in mail/, named by address, instead of a mail server.
class FileMailer:
def send(self, mail) -> None:
with open(os.path.join("mail", mail.to), "w") as f:
f.write(mail.token)
os.makedirs("mail", exist_ok=True)
use_mailer(FileMailer())rs
/// In development the kit's mails go to files in mail/, named by address, instead of a mail server.
struct FileMailer;
impl Mailer for FileMailer {
fn send(&self, mail: Mail) {
std::fs::write(format!("mail/{}", mail.to), mail.token).expect("mail/ is writable");
}
}Groups say which types someone may send. One rule of the shop is about the data instead: a new order's customer is whoever places it, or a customer could order in someone else's name. The API runs a small middleware of the shop for it. It comes after the kit's (order 0 against the kit's -30), so the sender is already checked when it compares:
ts
// A rule of the shop that no group expresses: a new order's customer is whoever places it. A
// middleware of the shop's own, after the kit's (order 0), so the sender is checked already.
const ownOrders = shopDomain.readModel("own-orders").middleware({ types: ["shop.Place"] }, (check) => {
if ((check.data as { customerId?: string }).customerId !== check.request.senderIdentity) {
throw new Rejected("An order is placed by its own customer", "forbidden");
}
});
void new Kernable().listener(ownOrders).run();py
# A rule of the shop that no group expresses: a new order's customer is whoever places it. A
# middleware of the shop's own, after the kit's (order 0), so the sender is checked already.
own_orders = shop_domain.read_model("own-orders")
@own_orders.middleware(["shop.Place"])
def _(check: Check):
if check.data.get("customerId") != check.request.sender_identity:
raise Rejected("An order is placed by its own customer", "forbidden")
threading.Thread(target=Kernable().listener(own_orders).run, daemon=True).start()rs
// A rule of the shop that no group expresses: a new order's customer is whoever places it. A
// middleware of the shop's own, after the kit's (order 0), so the sender is checked already.
let own_orders = shop().domain.read_model("own-orders");
own_orders.middleware(MiddlewareOptions::new(&["shop.Place"]), |check| {
let own = check.data["customerId"].as_str() == Some(check.request.sender_identity.as_str());
async move {
if !own {
return Err(Rejected::new("An order is placed by its own customer")
.code("forbidden")
.into());
}
Ok(())
}
});
let rules = Kernable::new(Options::default())?;
tokio::spawn(async move { rules.listener(&own_orders).run().await });Like the kit's middleware, it fails closed: while it is away, every Place is refused.
Then it starts the kit, sets up the platform once (bootstrap: the platform tenant, open sign-up, the API's own identity and key) and serves HTTP on port 3000:
ts
// The kit's domains: its aggregates, read models, reactors and the authorization middleware.
const kit = new Kernable().app({ service: "kit", domains: kitDomains() });
void kit.run();
await kit.ready;
// The API's client knows the shop's schemas too: GetOrder declares the order it is about.
const kernable = new Kernable().use(...kitSchemas(), shopDomain);
// Once: the platform tenant, the sign-up policy, and the API's own identity and key.
const { api: service } = await bootstrap(kernable, { signUp: { accounts: "open", tenants: "active" } });
const api = new KitApi({ kernable, keys: newSigningKeys(), service });
exampleServer(api, kernable).listen(Number(process.env.PORT ?? 3000));py
# The kit's domains: its aggregates, read models, reactors and the authorization middleware.
kit = Kernable().app(service="kit", domains=kit_domains())
threading.Thread(target=kit.run, daemon=True).start()
if not kit.ready.wait(30):
sys.exit("the kit's service did not connect")
# The API's client knows the shop's schemas too: GetOrder declares the order it is about.
kernable = Kernable().use(*kit_domains(), shop_domain)
# Once: the platform tenant, the sign-up policy, and the API's own identity and key.
service = bootstrap(kernable, sign_up={"accounts": "open", "tenants": "active"})["api"]
api = KitApi(kernable, new_signing_keys(), service)
example_server(api, kernable, int(os.environ.get("PORT", "3000"))).serve_forever()rs
// The kit's domains: its aggregates, read models, reactors and the authorization middleware.
let domains = kit::kit_domains();
let mut definition = App::new().service("kit");
for d in &domains {
definition = definition.domain(d);
}
let kit = Kernable::new(Options::default())?.app(definition)?;
let running = kit.clone();
tokio::spawn(async move { running.run().await });
kit.ready().await;
// The API's client knows the shop's schemas too: GetOrder declares the order it is about.
let kernable = Kernable::new(Options::default())?.with_domain(&shop().domain);
for d in &domains {
kernable.with_domain(d);
}
// Once: the platform tenant, the sign-up policy, and the API's own identity and key.
let policy = SignUpPolicy {
accounts: AccountSignUp::Open,
tenants: TenantSignUp::Active,
};
let booted = bootstrap(&kernable, policy, "Platform", None).await?;
let api = KitApi::new(
kernable.clone(),
new_signing_keys(),
&booted.api_identity,
&booted.api_key_id,
);
let port = std::env::var("PORT").unwrap_or_else(|_| "3000".into());
let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
axum::serve(listener, server::router(api, kernable)).await?;Start the worker, the read models and the API (node api.ts, .venv/bin/python api.py or cargo run -q --bin api). The example server's routes:
| Route | Does |
|---|---|
POST /register, POST /verify, POST /sign-in | sign up, confirm the email with the mailed token, sign in for an access token |
POST /tenants | open a tenant the caller owns |
POST /invitation-links, POST /invitation-links/join | create an invitation link; join a tenant through one |
GET /me | the caller's request context in a tenant |
POST /commands/<domain>/<aggregateType>/<Type> | send a command as the caller |
POST /queries/<domain>/<Type> | ask a query as the caller |
A request carries Authorization: Bearer <access token> and, inside a tenant, X-Tenant: <tenant ID>. The API turns them into the request context; it decides nothing itself.
Try it
A small client of the API, for the people of the story:
ts
// A small client of the API: a person's access token and, inside the shop, its tenant.
type Person = { email: string; token?: string; tenant?: string };
async function call(method: string, path: string, body: object | null, as?: Person): Promise<[number, any]> {
const headers: Record<string, string> = { "content-type": "application/json" };
if (as?.token) headers.authorization = `Bearer ${as.token}`;
if (as?.tenant) headers["x-tenant"] = as.tenant;
const res = await fetch(`${API}${path}`, { method, headers, body: body ? JSON.stringify(body) : undefined });
return [res.status, res.status === 204 ? null : await res.json()];
}
// Registers, confirms the email with the token from the mail (a file in development), signs in.
async function signUp(name: string): Promise<Person> {
const email = `${name.toLowerCase()}@example.com`;
await call("POST", "/register", { email, name, password: "correct horse battery" });
await call("POST", "/verify", { token: readFileSync(`mail/${email}`, "utf8") });
const [status, signedIn] = await call("POST", "/sign-in", { email, password: "correct horse battery" });
console.log(`${name} signs up and signs in: ${status}`);
return { email, token: signedIn.accessToken };
}py
# A small client of the API: a person's access token and, inside the shop, its tenant.
def call(method: str, path: str, body: dict | None, person: dict | None = None):
headers = {"content-type": "application/json"}
if person and person.get("token"):
headers["authorization"] = f"Bearer {person['token']}"
if person and person.get("tenant"):
headers["x-tenant"] = person["tenant"]
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(f"{API}{path}", data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(request) as res:
status, raw = res.status, res.read()
except urllib.error.HTTPError as err:
status, raw = err.code, err.read()
return status, (json.loads(raw) if raw and status != 204 else None)
# Registers, confirms the email with the token from the mail (a file in development), signs in.
def sign_up(name: str) -> dict:
email = f"{name.lower()}@example.com"
call("POST", "/register", {"email": email, "name": name, "password": "correct horse battery"})
with open(f"mail/{email}") as f:
call("POST", "/verify", {"token": f.read()})
status, signed_in = call("POST", "/sign-in", {"email": email, "password": "correct horse battery"})
print(f"{name} signs up and signs in: {status}")
return {"email": email, "token": signed_in["access_token"]}rs
/// A small client of the API: a person's access token and, inside the shop, its tenant.
#[derive(Clone, Default)]
struct Person {
token: Option<String>,
tenant: Option<String>,
}
struct Client {
http: reqwest::Client,
api: String,
}
impl Client {
async fn call(
&self,
method: &str,
path: &str,
body: Option<Value>,
person: &Person,
) -> Result<(u16, Value), BoxError> {
let url = format!("{}{path}", self.api);
let mut request = match method {
"GET" => self.http.get(url),
_ => self.http.post(url),
};
if let Some(token) = &person.token {
request = request.bearer_auth(token);
}
if let Some(tenant) = &person.tenant {
request = request.header("x-tenant", tenant);
}
if let Some(body) = body {
request = request.json(&body);
}
let res = request.send().await?;
let status = res.status().as_u16();
let body = if status == 204 {
Value::Null
} else {
res.json().await?
};
Ok((status, body))
}
/// Registers, confirms the email with the token from the mail (a file in development), signs in.
async fn sign_up(&self, name: &str) -> Result<Person, BoxError> {
let email = format!("{}@example.com", name.to_lowercase());
let password = "correct horse battery";
let nobody = Person::default();
let register = json!({ "email": email, "name": name, "password": password });
self.call("POST", "/register", Some(register), &nobody)
.await?;
let token = std::fs::read_to_string(format!("mail/{email}"))?;
self.call("POST", "/verify", Some(json!({ "token": token })), &nobody)
.await?;
let sign_in = json!({ "email": email, "password": password });
let (status, signed_in) = self
.call("POST", "/sign-in", Some(sign_in), &nobody)
.await?;
println!("{name} signs up and signs in: {status}");
Ok(Person {
token: signed_in["accessToken"].as_str().map(str::to_owned),
tenant: None,
})
}
}Ann opens her shop. A tenant is one customer of your platform, here Ann's shop; Ann is its owner and may do everything in it. She creates the group Customers: they may place orders, and add items to, submit and read only the orders they own. Then she creates an invitation link with that group:
ts
const ann = await signUp("Ann");
const [opened, shop] = await call("POST", "/tenants", { slug: "anns-shop", name: "Ann's shop" }, ann);
ann.tenant = shop.tenant;
console.log(`Ann opens her shop: ${opened}`);
// Customers may place orders, and work only on orders they own.
const [grouped] = await call("POST", "/commands/group/group/CreateGroup", {
aggregateId: "customers",
data: {
name: "Customers",
permissions: [
{ pattern: "shop.Place" },
{ pattern: "shop.AddItem", when: "owner" },
{ pattern: "shop.Submit", when: "owner" },
{ pattern: "shop.GetOrder", when: "owner" },
],
},
}, ann);
console.log(`Ann creates the group Customers: ${grouped}`);
const [linked, link] = await call("POST", "/invitation-links", { groups: [{ group: "customers" }], label: "the shop's website" }, ann);
console.log(`Ann creates an invitation link: ${linked}`);py
ann = sign_up("Ann")
opened, shop = call("POST", "/tenants", {"slug": "anns-shop", "name": "Ann's shop"}, ann)
ann["tenant"] = shop["tenant"]
print(f"Ann opens her shop: {opened}")
# Customers may place orders, and work only on orders they own.
grouped, _ = call("POST", "/commands/group/group/CreateGroup", {
"aggregate_id": "customers",
"data": {
"name": "Customers",
"permissions": [
{"pattern": "shop.Place"},
{"pattern": "shop.AddItem", "when": "owner"},
{"pattern": "shop.Submit", "when": "owner"},
{"pattern": "shop.GetOrder", "when": "owner"},
],
},
}, ann)
print(f"Ann creates the group Customers: {grouped}")
linked, link = call("POST", "/invitation-links", {"groups": [{"group": "customers"}], "label": "the shop's website"}, ann)
print(f"Ann creates an invitation link: {linked}")rs
let mut ann = client.sign_up("Ann").await?;
let open = json!({ "slug": "anns-shop", "name": "Ann's shop" });
let (opened, shop) = client.call("POST", "/tenants", Some(open), &ann).await?;
let tenant = shop["tenant"].as_str().map(str::to_owned);
ann.tenant = tenant.clone();
println!("Ann opens her shop: {opened}");
// Customers may place orders, and work only on orders they own.
let group = json!({
"aggregateId": "customers",
"data": {
"name": "Customers",
"permissions": [
{ "pattern": "shop.Place" },
{ "pattern": "shop.AddItem", "when": "owner" },
{ "pattern": "shop.Submit", "when": "owner" },
{ "pattern": "shop.GetOrder", "when": "owner" },
],
},
});
let (grouped, _) = client
.call(
"POST",
"/commands/group/group/CreateGroup",
Some(group),
&ann,
)
.await?;
println!("Ann creates the group Customers: {grouped}");
let new_link = json!({ "groups": [{ "group": "customers" }], "label": "the shop's website" });
let (linked, link) = client
.call("POST", "/invitation-links", Some(new_link), &ann)
.await?;
println!("Ann creates an invitation link: {linked}");Bob and Cleo sign up and join through the link. Bob places an order and works on it; Cleo tries to touch it:
ts
const bob = await signUp("Bob");
const cleo = await signUp("Cleo");
for (const [name, person] of [["Bob", bob], ["Cleo", cleo]] as const) {
const [joined] = await call("POST", "/invitation-links/join", { token: link.token }, person);
person.tenant = shop.tenant;
console.log(`${name} joins through the link: ${joined}`);
}
const [, me] = await call("GET", "/me", null, bob);
const [placed] = await call("POST", "/commands/shop/order/Place", { aggregateId: "o1", data: { customerId: me.senderIdentity } }, bob);
console.log(`Bob places o1: ${placed}`);
const [added] = await call("POST", "/commands/shop/order/AddItem", { aggregateId: "o1", data: { sku: "apple", qty: 2 } }, bob);
console.log(`Bob adds two apples: ${added}`);
const [cleoAdds, cleoAddsBody] = await call("POST", "/commands/shop/order/AddItem", { aggregateId: "o1", data: { sku: "pear", qty: 1 } }, cleo);
console.log(`Cleo adds to o1: ${cleoAdds} ${cleoAddsBody.error}`);
const [bobReads, order] = await call("POST", "/queries/shop/GetOrder", { data: { id: "o1" } }, bob);
console.log(`Bob reads o1: ${bobReads} ${order.status}, ${JSON.stringify(order.items)}`);
const [cleoReads, refused] = await call("POST", "/queries/shop/GetOrder", { data: { id: "o1" } }, cleo);
console.log(`Cleo reads o1: ${cleoReads} ${refused.error}`);py
bob = sign_up("Bob")
cleo = sign_up("Cleo")
for name, person in (("Bob", bob), ("Cleo", cleo)):
joined, _ = call("POST", "/invitation-links/join", {"token": link["token"]}, person)
person["tenant"] = shop["tenant"]
print(f"{name} joins through the link: {joined}")
_, me = call("GET", "/me", None, bob)
placed, _ = call("POST", "/commands/shop/order/Place", {"aggregate_id": "o1", "data": {"customerId": me["sender_identity"]}}, bob)
print(f"Bob places o1: {placed}")
added, _ = call("POST", "/commands/shop/order/AddItem", {"aggregate_id": "o1", "data": {"sku": "apple", "qty": 2}}, bob)
print(f"Bob adds two apples: {added}")
cleo_adds, cleo_adds_body = call("POST", "/commands/shop/order/AddItem", {"aggregate_id": "o1", "data": {"sku": "pear", "qty": 1}}, cleo)
print(f"Cleo adds to o1: {cleo_adds} {cleo_adds_body['error']}")
bob_reads, order = call("POST", "/queries/shop/GetOrder", {"data": {"id": "o1"}}, bob)
print(f"Bob reads o1: {bob_reads} {order['status']}, {json.dumps(order['items'], separators=(',', ':'))}")
cleo_reads, refused = call("POST", "/queries/shop/GetOrder", {"data": {"id": "o1"}}, cleo)
print(f"Cleo reads o1: {cleo_reads} {refused['error']}")rs
let mut bob = client.sign_up("Bob").await?;
let mut cleo = client.sign_up("Cleo").await?;
for (name, person) in [("Bob", &mut bob), ("Cleo", &mut cleo)] {
let join = json!({ "token": link["token"] });
let (joined, _) = client
.call("POST", "/invitation-links/join", Some(join), person)
.await?;
person.tenant = tenant.clone();
println!("{name} joins through the link: {joined}");
}
let (_, me) = client.call("GET", "/me", None, &bob).await?;
let place = json!({ "aggregateId": "o1", "data": { "customerId": me["senderIdentity"] } });
let (placed, _) = client
.call("POST", "/commands/shop/order/Place", Some(place), &bob)
.await?;
println!("Bob places o1: {placed}");
let add =
|sku: &str, qty: i64| json!({ "aggregateId": "o1", "data": { "sku": sku, "qty": qty } });
let (added, _) = client
.call(
"POST",
"/commands/shop/order/AddItem",
Some(add("apple", 2)),
&bob,
)
.await?;
println!("Bob adds two apples: {added}");
let (cleo_adds, cleo_adds_body) = client
.call(
"POST",
"/commands/shop/order/AddItem",
Some(add("pear", 1)),
&cleo,
)
.await?;
println!(
"Cleo adds to o1: {cleo_adds} {}",
text(&cleo_adds_body["error"])
);
let get = json!({ "data": { "id": "o1" } });
let (bob_reads, order) = client
.call("POST", "/queries/shop/GetOrder", Some(get.clone()), &bob)
.await?;
println!(
"Bob reads o1: {bob_reads} {}, {}",
text(&order["status"]),
order["items"]
);
let (cleo_reads, refused) = client
.call("POST", "/queries/shop/GetOrder", Some(get), &cleo)
.await?;
println!("Cleo reads o1: {cleo_reads} {}", text(&refused["error"]));Bob tries to place an order in Cleo's name:
ts
const [, cleoMe] = await call("GET", "/me", null, cleo);
const [forCleo, forCleoBody] = await call("POST", "/commands/shop/order/Place", { aggregateId: "o2", data: { customerId: cleoMe.senderIdentity } }, bob);
console.log(`Bob places o2 in Cleo's name: ${forCleo} ${forCleoBody.error}`);py
_, cleo_me = call("GET", "/me", None, cleo)
for_cleo, for_cleo_body = call("POST", "/commands/shop/order/Place", {"aggregate_id": "o2", "data": {"customerId": cleo_me["sender_identity"]}}, bob)
print(f"Bob places o2 in Cleo's name: {for_cleo} {for_cleo_body['error']}")rs
let (_, cleo_me) = client.call("GET", "/me", None, &cleo).await?;
let for_cleo =
json!({ "aggregateId": "o2", "data": { "customerId": cleo_me["senderIdentity"] } });
let (status, body) = client
.call("POST", "/commands/shop/order/Place", Some(for_cleo), &bob)
.await?;
println!(
"Bob places o2 in Cleo's name: {status} {}",
text(&body["error"])
);Finally, Explain tells Cleo why she may not read the order, and a request without an access token is refused before anything else:
ts
const [, why] = await call("POST", "/queries/group/Explain", {
data: { identityId: cleoMe.senderIdentity, type: "shop.GetOrder", aggregateType: "order", aggregateId: "o1" },
}, cleo);
console.log(`Why not? allowed: ${why.allowed}, ${why.code}`);
const [anonymous, nobody] = await call("POST", "/commands/shop/order/Place", { aggregateId: "o3", data: {} }, { email: "", tenant: shop.tenant });
console.log(`Without signing in: ${anonymous} ${nobody.error}`);py
_, why = call("POST", "/queries/group/Explain", {
"data": {"identityId": cleo_me["sender_identity"], "type": "shop.GetOrder", "aggregateType": "order", "aggregateId": "o1"},
}, cleo)
print(f"Why not? allowed: {str(why['allowed']).lower()}, {why['code']}")
anonymous, nobody = call("POST", "/commands/shop/order/Place", {"aggregate_id": "o3", "data": {}}, {"tenant": shop["tenant"]})
print(f"Without signing in: {anonymous} {nobody['error']}")rs
let explain = json!({
"data": {
"identityId": cleo_me["senderIdentity"],
"type": "shop.GetOrder",
"aggregateType": "order",
"aggregateId": "o1",
},
});
let (_, why) = client
.call("POST", "/queries/group/Explain", Some(explain), &cleo)
.await?;
println!(
"Why not? allowed: {}, {}",
why["allowed"],
text(&why["code"])
);
let anonymous = Person {
token: None,
tenant: tenant.clone(),
};
let place = json!({ "aggregateId": "o3", "data": {} });
let (status, nobody) = client
.call(
"POST",
"/commands/shop/order/Place",
Some(place),
&anonymous,
)
.await?;
println!("Without signing in: {status} {}", text(&nobody["error"]));text
Ann signs up and signs in: 200
Ann opens her shop: 201
Ann creates the group Customers: 200
Ann creates an invitation link: 201
Bob signs up and signs in: 200
Cleo signs up and signs in: 200
Bob joins through the link: 200
Cleo joins through the link: 200
Bob places o1: 200
Bob adds two apples: 200
Cleo adds to o1: 403 forbidden
Bob reads o1: 200 draft, {"apple":2}
Cleo reads o1: 403 forbidden
Bob places o2 in Cleo's name: 403 forbidden
Why not? allowed: false, forbidden
Without signing in: 401 unauthenticatedtext
Ann signs up and signs in: 200
Ann opens her shop: 201
Ann creates the group Customers: 200
Ann creates an invitation link: 201
Bob signs up and signs in: 200
Cleo signs up and signs in: 200
Bob joins through the link: 200
Cleo joins through the link: 200
Bob places o1: 200
Bob adds two apples: 200
Cleo adds to o1: 403 forbidden
Bob reads o1: 200 draft, {"apple":2}
Cleo reads o1: 403 forbidden
Bob places o2 in Cleo's name: 403 forbidden
Why not? allowed: false, forbidden
Without signing in: 401 unauthenticatedtext
Ann signs up and signs in: 200
Ann opens her shop: 201
Ann creates the group Customers: 200
Ann creates an invitation link: 201
Bob signs up and signs in: 200
Cleo signs up and signs in: 200
Bob joins through the link: 200
Cleo joins through the link: 200
Bob places o1: 200
Bob adds two apples: 200
Cleo adds to o1: 403 forbidden
Bob reads o1: 200 draft, {"apple":2}
Cleo reads o1: 403 forbidden
Bob places o2 in Cleo's name: 403 forbidden
Why not? allowed: false, forbidden
Without signing in: 401 unauthenticatedWhat decided
- Who is asking comes from the access token, checked by the API without the kernel. The middleware still checks that the session is active: signing out ends it at once.
- Ann is the tenant's owner: owners hold every permission in their tenant.
- Bob may add to
o1because he is its owner: the relationownerwas set from theOrderPlacedevent. The same holds for reading it, becauseGetOrderdeclares the order it is about. - Cleo is a customer too, but not
o1's owner:forbidden, for the command and the query. - Bob's order in Cleo's name passes the kit (customers may place orders) and is refused by the shop's own middleware, which compares the order's customer with the sender.
- Bob and Cleo got the group through the link, without Ann inviting each of them. Ann can limit a link (how many may join, until when) and revoke it at any time.
Every sign-in, failed attempt, membership and join is an event in the log. To see the domains in detail, continue with the kit's documentation.
Next: 10. A business process.
