This tutorial adds consents management to an application on Ulabase. Every user must accept the current Terms of Service and Privacy Policy before they can use the app. The acceptance is recorded with the version they agreed to and the date.
Almost all of it is server-side configuration: four JSON documents, no code and no deploy. The client only reacts to a status code, so the same tutorial applies whether your frontend is React, Angular or anything else. The last part shows the frontend written twice, once with each.
The rule lives on the server. It applies to your web app, to your mobile client, to curl, and to the API integration a customer wrote against your service last year.
Here is the flow we are building:
- The user registers and receives a verification email.
- They click the link, get the
userrole, and land in the app already signed in. - The app asks who they are, and the answer is
451: they have not accepted anything yet. - The app shows an acceptance form. They accept, the app gets a fresh token, and they are in.
There are two flags: tos for the terms and pp for the privacy policy. Each has its own version, and one request accepts both.
You will need a service on Ulabase with the Guards plugin enabled from Service → Guards. The Free plan is enough.
Quick Start
The starters state all four server-side documents in ulabase.setup.consents.ts, so one command sets up a service. Clone the starter of your choice and point it at your service:
React:
git clone https://github.com/ulabase/starter-react.git
cd starter-react
npm install
Angular:
git clone https://github.com/ulabase/starter-ng.git
cd starter-ng
npm install
Edit src/environments/environment.ts (environment.dev.ts in the Angular starter) and set apiUrl to your Ulabase service URL. Then configure the service and start:
npm install -g ulabase # the ulabase command
ulabase login # a personal access token, from ulabase.com
ulabase setup --srv <srvId> --file ulabase.setup.consents.ts --dry-run # what is missing
ulabase setup --srv <srvId> --file ulabase.setup.consents.ts # make it so
npm run dev # React
npm start # Angular
Both starters carry two setup files. ulabase.setup.ts configures the accounts side only. ulabase.setup.consents.ts imports it and appends the four documents below, so the accounts steps have one definition.
The file you apply decides whether the gate exists. With the first file no rule exists, the server never answers 451, and nobody is asked to accept anything. The acceptance screen ships in both cases and stays hidden.
<srvId> is the six-character id of your service, the first label of its URL. Every step is a check and an apply, so re-running writes nothing. --dry-run lists what the service is missing and changes nothing. The setup also installs the Guards plugin, so there is nothing to enable by hand first.
Register a user and click the verification link: you land on the consents form. The app asked /users/me, the server answered 451, and the overlay appeared. Accept, and you are in.
To verify the server side before touching the frontend, run the curl checks in Check it before touching the frontend.
The Data Model
Two fields on the user document:
{
"latestConsents": {
"tos": "2026-07-01",
"pp": "2026-07-01",
"acceptedAt": { "$date": 1754438400000 }
},
"consents": [
{ "tos": "2026-07-01", "pp": "2026-07-01", "acceptedAt": { "$date": 1754438400000 } }
]
}
latestConsents is what the gate reads: a flat object, overwritten at every acceptance. consents is an append-only history, for the day someone asks what a user agreed to and when.
Neither field exists until the user accepts for the first time. The rule blocks on that absence.
Registration does not write the fields. There is one way to accept, and it is the same for a user who just signed up, one who arrived through Google, and one who has had an account for two years and meets a new version of the terms.
Part 1: The Server
The server side is four configuration documents. There is no application code and no deploy.
You do not have to type them. They are in the starters' ulabase.setup.consents.ts, and one command applies all four and installs the Guards plugin:
ulabase setup --srv <srvId> --file ulabase.setup.consents.ts
The rest of this section explains what that command does and why each document has its shape. Read it even if you let the command do the work: three of the four documents fail in ways that look like a different problem. The last part of this article lists those failures.
The setup file does one thing the console cannot. The two version strings appear four times below: twice in the permission's mergeRequest and twice in the rule's condition. They have to agree exactly.
When they differ, the acceptance is stamped with one version and the rule compares against another. The user is then blocked for good by a form that reported success.
In the setup file the versions are two constants at the top, and everything derives from them. To publish new terms you edit two strings and run the setup again.
The documents, one by one
1. A schema that validates the shape
Service → Schemas → New Schema. The _id, userConsentsSchema, goes in its own field, and the editor takes only the document:
{
"title": "User with consents",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["_id", "password", "roles", "profile"],
"properties": {
"_id": { "type": "string" },
"_etag": { "type": "object" },
"password": { "type": "string" },
"roles": { "type": "array", "items": { "type": "string" } },
"profile": {
"type": "object",
"required": ["name", "surname"],
"properties": {
"name": { "type": "string" },
"surname": { "type": "string" },
"avatarUrl": { "type": "string" }
}
},
"latestConsents": {
"type": "object",
"properties": {
"tos": { "type": "string" },
"pp": { "type": "string" },
"acceptedAt": { "type": "object", "properties": { "_$date": { "type": "number" } } }
},
"required": ["tos", "pp"]
},
"consents": { "type": "array" },
"socialAuths": { "type": "array" },
"teams": { "type": "array" },
"team": { "type": "object" }
}
}
Then apply it: Service → Collections → users → Schema, pointing at userConsentsSchema.
Note _$date with the underscore. acceptedAt is a BSON date. Inside a schema document the BSON type keys are escaped, so the parser does not read them as actual values while the schema is being stored. If you declare the field as {"type": "string"}, every acceptance is rejected.
latestConsents and consents are left out of required, along with the OAuth and team fields. The document is validated when it is inserted, before the initial team is attached. A schema that demands those fields rejects every registration.
2. A permission for the acceptance
No default permission authorizes PATCH /users/{userId}. A guard is never consulted on a request the ACL has already refused. Without this permission the acceptance gets a 403, and the user is locked out for good.
Service → Permissions:
{
"_id": "userCanPatchOwnConsents",
"predicate": "path-template('/users/{userId}') and method(PATCH) and (equals(@user._id, ${userId}) or equals(@user.sub, ${userId})) and bson-request-whitelist(consents)",
"roles": ["user"],
"priority": 1,
"mongo": {
"mergeRequest": {
"latestConsents": { "tos": "2026-07-01", "pp": "2026-07-01", "acceptedAt": "@now" },
"_$push": { "consents": { "tos": "2026-07-01", "pp": "2026-07-01", "acceptedAt": "@now" } }
}
}
}
bson-request-whitelist(consents) narrows the permission to a single field: it grants the acceptance and nothing else.
mergeRequest moves the decision of what is being accepted to the server. The client sends {"consents": []} and the server stamps the versions and the timestamp. Without it, a client could accept terms it was never shown, or backdate the acceptance to before the terms existed. For the same reason the versions never appear in the frontend code: the client has no say in them.
_$push is the MongoDB update operator $push. The permission document writes it with a leading underscore, and the server unescapes it before the merge. It appends each acceptance to the history array.
Write latestConsents as a nested object. Dotted keys like latestConsents.tos fail: MongoDB rejects a merged request that sets both a field and a path inside it, with 500 ConflictingUpdateOperators.
3. The two claims
Service → Users → JWT Claims: add both latestConsents/tos and latestConsents/pp.
If one of the two is missing, the comparison on it is false for every user who authenticates with a token, including the ones who just accepted. The rule blocks them permanently, and the condition gives no hint of the cause.
Keep the list to these two. A JWT payload is base64-encoded and unencrypted, so any client holding the token can read everything in it. Leave the consents history out: it is an array that grows at every acceptance, and no access decision reads it.
4. The rule
Service → Guards:
{
"id": "consentsGate",
"name": "Block users who have not accepted the current ToS and Privacy Policy",
"condition": "equals(@authenticated, 'true') and not path-prefix('/auth') and not path-prefix('/token') and not (method(PATCH) and path-template('/users/{userId}') and bson-request-whitelist(consents)) and not (equals(@user.latestConsents.tos, '2026-07-01') and equals(@user.latestConsents.pp, '2026-07-01'))",
"action": "block",
"status_code": 451,
"message": "You must accept the current Terms of Service and Privacy Policy",
"on_error": "allow"
}
The same condition, one clause per line:
equals(@authenticated, 'true')
and not path-prefix('/auth')
and not path-prefix('/token')
and not (method(PATCH) and path-template('/users/{userId}') and bson-request-whitelist(consents))
and not (equals(@user.latestConsents.tos, '2026-07-01') and equals(@user.latestConsents.pp, '2026-07-01'))
The first line is easy to leave out. A rule keyed on a user's state runs the same comparison for a caller who has no user, finds it false, and blocks them.
An anonymous visitor then sees a form they cannot complete, since completing it means writing to a user document they do not have. A webhook from a payment provider is refused too: the order it carried never moves, and nothing reports a problem.
@authenticated is the string 'true' when the request carries an account and 'false' when it does not.
Do not use
@roleshere. For a caller with no account it resolves to["$unauthenticated"], which looks like the right tool. But$is Undertow's sigil for an exchange attribute, soin(value='$unauthenticated', array=@roles)is read as an attribute of that name. It resolves to nothing and is false for everybody. Negated, as it would be here, it is true for every request and the line has no effect.
The next two lines are the exclusions. Without them the rule locks everyone out, you included. The last part of this article explains why.
The fourth line exempts the acceptance itself: the request that unblocks the user is made while they are still blocked.
/users/me is left out of the exclusions on purpose. Reading the user document is the first thing any client does, so a blocked user is refused immediately, whatever the app is and whether or not it has data of its own yet. This needs no setup on your side.
It also means the app never gets a user document, and the client half below is built around that.
The last line uses not (A and B): the user is blocked when either acceptance is missing. not A and not B would block only the users who accepted neither, and that bug is easy to ship.
The frontend keys on the 451. Any status your frontend can act on works, and 451 Unavailable For Legal Reasons has the right meaning.
Check it before touching the frontend
# a token — must succeed
curl -X GET 'https://<service>/token' -u '<email>:<password>'
# the user document — must be blocked with 451, and this is the one that matters
curl -X GET 'https://<service>/users/me' -H 'Authorization: Bearer <token>'
# the acceptance — must return 200
curl -X PATCH 'https://<service>/users/<email>' \
-H 'Authorization: Bearer <token>' -H 'Content-Type: application/json' \
-d '{"consents": []}'
# a fresh token, then the blocked request again — must now pass
curl -X GET 'https://<service>/token' -u '<email>:<password>'
curl -X GET 'https://<service>/users/me' -H 'Authorization: Bearer <new-token>'
If the second request comes back 401, the token is missing or expired, and the rule never got a user to look at. If it comes back 200, re-read the last line of the condition.
Part 2: The Client
Whatever your frontend is written in, it has three jobs:
- Notice the
451on the session check. - Show an acceptance screen while that is the case.
- On acceptance, send the
PATCHand get a new token.
Three consequences follow from blocking /users/me.
The app needs no probe. Restoring the session is the first thing any client does, and it is refused, so a blocked user is discovered before the app has rendered anything. You write no extra request and configure no path.
The gate sits above the router. A blocked user has no session, since the request that would establish one is the one being refused. Every route guard you have treats them as signed out and sends them to the login screen. Above the router, no guard stands between the user and the form.
The failure is absorbed before you see it. Session restoration runs on its own schedule, with no call site of yours to wrap in a try. The adapters swallow its errors deliberately: an app that hangs when the network drops for a moment is worse than one that shows a login screen. The kit gives you AuthConfig.onError, which sees every failure, including the ones no caller is waiting on. Without it, your app cannot tell "blocked" from "signed out".
The list of jobs has no version comparison. Nothing in the client knows what 2026-07-01 is, and nothing reads latestConsents. The versions exist only on the server, so the two sides cannot drift apart.
Both starters already carry the code below. The rule that makes it fire is in the second setup file, and applying it is a product decision: you decide which consents you collect and when you ask again. On a service set up with ulabase.setup.ts this code never runs, since no 451 arrives.
Both depend on the kit. The starters require 0.13.6 or later (^0.13.6 in their package.json), a version that ships acceptConsents, onError, api(), and the token claims the acceptance needs. Check the installed version with npm ls @ulabase/kit-react: a stale node_modules fails with Property 'acceptConsents' does not exist, and that message does not mention the version.
The same three jobs follow twice, once per framework. You can also go back to the Quick Start and read the finished code.
In React
git clone https://github.com/ulabase/starter-react.git
cd starter-react
npm install
Edit src/environments/environment.ts, set apiUrl to your service, and run npm run dev. The finished code is already there, and the walkthrough below explains each piece.
1. Catch the 451: src/consents-signal.ts
A flag, and a handler that raises it:
import type { ApiError } from '@ulabase/kit-react';
type Listener = (blocked: boolean) => void;
let blocked = false;
const listeners = new Set<Listener>();
export function isBlocked(): boolean {
return blocked;
}
export function setBlocked(next: boolean): void {
if (blocked === next) return;
blocked = next;
listeners.forEach(l => l(next));
}
export function subscribe(l: Listener): () => void {
listeners.add(l);
return () => listeners.delete(l);
}
/** Raises the flag on any 451 from the service. */
export const consentsOnError = (err: ApiError): void => {
if (err.status === 451) setBlocked(true);
};
Hand it to the provider in src/main.tsx:
import { consentsOnError } from './consents-signal';
<RhAuthProvider config={{ apiBaseUrl: environment.apiUrl, onError: consentsOnError }}>
<App />
</RhAuthProvider>
This is all the detection logic. If you bump the version in the rule tomorrow, this code stays as it is and needs no redeploy: the server starts answering 451 and the app reacts.
2. The form: src/ConsentsGate.tsx
import { useEffect, useState } from 'react';
import { useAuth } from '@ulabase/kit-react';
import { isBlocked, setBlocked, subscribe } from './consents-signal';
import './ConsentsGate.css';
export function ConsentsGate({ children }: { children: React.ReactNode }) {
const auth = useAuth();
const [blocked, setBlockedState] = useState(isBlocked);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [acceptedTos, setAcceptedTos] = useState(false);
const [acceptedPp, setAcceptedPp] = useState(false);
useEffect(() => subscribe(setBlockedState), []);
if (!blocked) return <>{children}</>;
const accept = async () => {
setBusy(true);
setError(null);
try {
await auth.acceptConsents();
// The token is new and /users/me answers now: load the session properly.
await auth.checkSession();
setBlocked(false);
} catch {
setError('We could not record your acceptance. Please try again.');
} finally {
setBusy(false);
}
};
const signOut = async () => {
setBlocked(false); // the flag outlives the session — clear it
await auth.logout();
};
return (
<div className="consents-overlay" role="dialog" aria-modal="true" aria-labelledby="consents-title">
<div className="consents-card">
<h1 id="consents-title">Before you continue</h1>
<p>Please review these documents and accept them to use the application.</p>
<label className="consents-check">
<input type="checkbox" checked={acceptedTos}
onChange={e => setAcceptedTos(e.target.checked)} />
<span>
I have read and accept the{' '}
<a href="/terms.html" target="_blank" rel="noreferrer">Terms of Service</a>
</span>
</label>
<label className="consents-check">
<input type="checkbox" checked={acceptedPp}
onChange={e => setAcceptedPp(e.target.checked)} />
<span>
I have read and accept the{' '}
<a href="/privacy.html" target="_blank" rel="noreferrer">Privacy Policy</a>
</span>
</label>
{error && <p className="field-error">{error}</p>}
<button type="button" className="btn-primary" onClick={accept}
disabled={busy || !acceptedTos || !acceptedPp}>
{busy ? 'Saving…' : 'I accept'}
</button>
<button type="button" className="btn-plain" onClick={signOut}>Sign out</button>
</div>
</div>
);
}
auth.acceptConsents() does four things in order:
- the
PATCHthat records the acceptance; GET /token?renew=true, for a token that reflects it (without it the rule keeps blocking, see the note below);GET /users/me, to read the document back as the server wrote it;setUser()with the result.
Where does it get the user id? auth.user is empty, since the user document was refused. acceptConsents() falls back to the token's sub claim, which is the user id, and which the client has held all along. So blocking /users/me costs nothing: the app needs the document to display the user, and the token already says who the user is.
signOut lowers the flag before logging out. The flag is module state, so it survives the logout. If it stays up, the next person to sign in on that tab meets the acceptance form before they have made a single request.
The CSS that turns it into a blocking dialog is at the end, shared with the Angular version.
3. Mount it above the router: src/App.tsx
import { ConsentsGate } from './ConsentsGate';
// at the end of the component, where it used to `return element;`
return <ConsentsGate>{element}</ConsentsGate>;
Mount it outside the shell. A blocked user never reaches the shell: AuthGuard sees no session and redirects to the login page. Above the router there is no guard in the way.
Register a new user and click the verification link. You land on the form: the first thing the app did was ask who you are, and the answer was 451.
In Angular
git clone https://github.com/ulabase/starter-ng.git
cd starter-ng
npm install
Edit src/environments/environment.dev.ts, set apiUrl to your service, and run ng serve. The three jobs are the same as in the React version.
1. The flag: src/app/consents.ts
import { signal } from '@angular/core';
import type { ApiError } from '@ulabase/kit-ng';
export const consentsBlocked = signal(false);
/** Raises the flag on any 451 from the service. */
export function consentsOnError(err: ApiError): void {
if (err.status === 451) consentsBlocked.set(true);
}
This is a plain module. onError is handed to provideRhAuth while the injector is still being assembled, so a service could not be injected yet. A signal works outside DI.
Register it in src/app/app.config.ts:
import { consentsOnError } from './consents';
// in appConfig.providers
provideRhAuth({ apiBaseUrl: environment.apiUrl, onError: consentsOnError }),
An interceptor does not help here. An Angular interceptor sees HttpClient traffic, and the kit now routes through it too. But authGuard swallows this failure before any interceptor result reaches the app. onError sees it.
2. The form: src/app/consents-gate.ts
import { Component, inject, signal } from '@angular/core';
import { RhAuthService } from '@ulabase/kit-ng';
import { consentsBlocked } from './consents';
@Component({
selector: 'app-consents-gate',
templateUrl: './consents-gate.html',
styleUrl: './consents-gate.css',
})
export class ConsentsGate {
protected readonly auth = inject(RhAuthService);
protected readonly blocked = consentsBlocked;
protected readonly busy = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly acceptedTos = signal(false);
protected readonly acceptedPp = signal(false);
protected accept(): void {
this.busy.set(true);
this.error.set(null);
this.auth.acceptConsents().subscribe({
next: () => window.location.assign('/'),
error: () => {
this.error.set('We could not record your acceptance. Please try again.');
this.busy.set(false);
},
});
}
protected signOut(): void {
consentsBlocked.set(false);
this.auth.logout().subscribe(() => window.location.assign('/auth/login'));
}
}
The template is in consents-gate.html, wrapped in @if (blocked()) { … }. It has the same two boxes, bound the Angular way:
<label class="consents-check">
<input type="checkbox" [checked]="acceptedTos()"
(change)="acceptedTos.set($any($event.target).checked)" />
<span>
I have read and accept the
<a href="/terms.html" target="_blank" rel="noreferrer">Terms of Service</a>
</span>
</label>
<button type="button" class="btn-primary" (click)="accept()"
[disabled]="busy() || !acceptedTos() || !acceptedPp()">
{{ busy() ? 'Saving…' : 'I accept' }}
</button>
Why a reload and no navigation? authGuard already cancelled the navigation that brought the user here. Its checkSession() errored on the 451, and a guard that errors stops without redirecting. There is no failed navigation to replay: router.navigateByUrl('/') from a URL that is already / does nothing.
The reload enters the app again with a new token and a readable user document. It is one line, and it runs once per acceptance.
RhAuthService.acceptConsents() does the same four steps as the React one. It takes the user id from the token's sub for the same reason: there is no user document yet.
3. Mount it at the root: src/app/app.html
<app-consents-gate />
@if (apiConfigured) {
<router-outlet />
} @else {
…
}
Add ConsentsGate to App's imports. The gate goes outside the outlet: with /users/me refused there is no session, authGuard fails, and nothing inside the outlet ever renders. A gate placed there would never be seen.
The documents themselves
The form has two boxes for two documents, and the user has to be able to read them before accepting. That constraint decides where the documents live.
Put them outside the application: public/terms.html and public/privacy.html, plain HTML files served as they are. Both starters ship placeholders. Replace them.
It is tempting to make them app routes, /terms and /privacy, styled like everything else. That fails. A blocked user has no session, so a route inside the app sits behind the gate. They click the link, a second tab opens, the app boots, /users/me comes back 451, and the overlay covers the terms. A static file has no session to check.
Give each document a version line matching the rule:
<h1>Terms of Service</h1>
<p class="version">Version 2026-07-01</p>
That date now appears in three places: the document, the Guards rule, and the permission's mergeRequest. They have to move together. If you change the rule and forget the document, users accept one version while the server records another. The record then gives a wrong answer to the question it exists for: what the user agreed to.
The checkboxes are user experience only. They enable the button and do nothing else. The request that follows carries no versions, and the server stamps both in one write. A user cannot accept one document without the other, since the permission does not offer that. To record them separately you need two permissions and two flags in the rule.
The CSS, for either
Put it in ConsentsGate.css (React) or consents-gate.css (Angular):
.consents-overlay {
position: fixed;
inset: 0;
/* Above everything the shell already stacks — in both starters that means
the header (100), the account dropdown (200) and the progress bar (300). */
z-index: 400;
display: grid;
place-items: center;
padding: 1rem;
background: rgb(0 0 0 / 0.55);
}
.consents-card {
width: min(32rem, 100%);
padding: 2rem;
border-radius: 0.75rem;
background: var(--surface, #fff);
box-shadow: 0 1.25rem 3rem rgb(0 0 0 / 0.25);
}
.consents-card h1 { margin-top: 0; }
.consents-check {
display: flex;
align-items: flex-start;
gap: 0.75rem;
margin: 1rem 0;
cursor: pointer;
line-height: 1.5;
}
.consents-check input {
/* Aligned to the first line of text, not to its box. */
margin-top: 0.15em;
width: 1.05em;
height: 1.05em;
flex: none;
cursor: pointer;
}
.consents-card .btn-plain {
display: block;
margin-top: 0.75rem;
padding: 0;
font: inherit;
background: none;
border: none;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
There is no close button and no backdrop click: the only ways out are accepting both documents or signing out.
In both versions the overlay is user experience. The enforcement is on the server: remove the overlay with the dev tools, and every request the app makes still comes back 451.
Seven Things That Will Bite You
The gate has to live above your guards
This failure is quiet and looks like a different problem. You configure everything, sign in as a user who has accepted nothing, and land on the login page, as if the password were wrong.
/users/me came back 451, so the session was never established. Every guard you have concluded that the user is signed out, and redirected. An overlay mounted inside the authenticated part of the app is behind the guard that just turned the user away. It has to sit above the router, where nothing stands between a blocked user and the form.
Nobody is listening
This one is quiet too. Session restoration happens on mount, on navigation and on a token refresh, without a call from your code. The adapters absorb its failures on purpose: an app that hangs when the network drops for a moment is worse than one that shows a login screen. So the 451 is caught and discarded, and no code of yours ever hears about it.
AuthConfig.onError exists for this: it sees every failure, including the ones no caller is waiting on. It also lets you tell a blocked user from an offline one, since status: 0 means the request never reached the service. Without it the app cannot distinguish the two.
The token is a snapshot
A JWT is issued once and carries the user as they were at that moment. Your user accepts, the write succeeds, and the rule keeps blocking them. The token in their browser still says they have not accepted, and the rule reads the token. This lasts for the whole life of that token.
So a new token has to follow the acceptance. acceptConsents() gets it with GET /token?renew=true. That is the right call in a browser, which holds a bearer token and has no credentials to send again.
Authenticating with a password is the other way to get a fresh token: every GET /token with Basic credentials is issued from the document as it reads at that moment. The curl check above relies on it. A signed-in SPA cannot use it.
The gate also blocks the way back in
A rule matches requests, and the requests a blocked user needs in order to stop being blocked are requests like any other. Only /ping, /health/db and CORS preflight are never guarded. Every other request can be blocked, so without the exclusions:
/tokenis blocked, so a user without consents cannot sign in at all, and the renewal after the acceptance can never take effect;/auth/*is blocked, so registration, email verification and the OAuth callback all fail;- the acceptance
PATCHitself, if you forget its exemption, is refused, and the user can never make the one request that would free them.
The application appears broken, and nothing in the logs says "misconfigured rule". For this reason not path-prefix('/auth') and not path-prefix('/token') are at the front of the condition, where they are hard to miss when you read it again.
/users/me is the deliberate exception: blocking it is what trips the gate. It costs nothing, since the client can still tell who the user is: the id is the sub claim of the token it already holds.
A rule that matches everything hides yours
Guards evaluates rules in order. The first rule whose condition matches performs its action, and evaluation stops. A rule left over from an experiment, such as path-prefix('/') blocking everything, sits ahead of yours and makes it unreachable. The symptom is 451 on every request, /token and /auth included, so nobody can sign in to go and look.
This happened to me while writing the setup file. The rule was already in the plugin's stored configuration, left by an earlier test, and installing Guards activated it again. The setup preserved it. That is the correct behavior in general, since a service may carry rules the setup knows nothing about. Here it produced the wrong outcome.
Before deciding your rule does not work, list the rules and check that nothing precedes it.
_id is required, and it is not in the body
The schema puts _id in required, and registration through /auth/register sends a whole document, so it passes. A direct PUT /users/{id} fails: the id is in the path, and the request is refused with
Request content violates schema 'userConsentsSchema': required key [_id] not found
The flow this article builds is unaffected. The error shows up in the next thing you do: seeding a user from a script, or creating one from a setup file. The message names a key that you can see in the URL. The fix is to put the id in the body as well.
The service administrator is never guarded
This is deliberate. A rule that blocks everything still leaves the Ulabase console working, so there is always a way back. For the same reason, test a new rule on a non-production service first: the one identity that can always fix it never sees the problem.
What You Get
A user who has not accepted is served only the requests that let them accept. This holds for your React app, a mobile client, curl, and the integration a customer wrote against your API last year. The user finds out immediately, since the first question any client asks is who they are.
The server wrote the versions and the timestamps in your database, so you can rely on them the day someone asks. The history is an append-only array.
When the terms change, you bump TOS_VERSION and PP_VERSION in the setup file and run ulabase setup again. You can also edit the same two versions in the console, in the rule and in the permission, taking care that all four occurrences agree. Every user meets the form again on their next request. Nothing is redeployed, on the frontend or anywhere else.
Start with a free service at ulabase.com and clone the React starter or the Angular one. Both carry the finished version of Part 2, and Part 1 as ulabase.setup.consents.ts. The Guards documentation covers the parts this tutorial moved past quickly.
For ulabase itself, see The ulabase command line.
Ulabase is a MongoDB Technology Partner. The consents pattern is documented in full under Guards → Example: Gating on Consents.
Build your app on Ulabase
Your backend is ready in minutes, and you spend your time on your app. The Free plan needs no credit card.