Build
End-user auth
Every app has its own users. They sign up with email and password, or with a 6 digit code sent by email. A session is a short lived JWT access token plus a refresh token that rotates on every use.
Sessions
All auth routes live under /v1/apps/{app}/auth and need the app's publishable key (or its secret key). Signup, login, verify, and refresh all return the same session shape:
{
"user": {"id": "...", "email": "ada@example.com", "data": {"name": "Ada"}},
"access_token": "...",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "..."
}Email and password
Sign up. data is optional profile JSON you choose.
SESSION=$(curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/signup \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"correct horse battery 1","data":{"name":"Ada"}}')
ACCESS_TOKEN=$(echo "$SESSION" | jq -er .access_token)
REFRESH_TOKEN=$(echo "$SESSION" | jq -er .refresh_token)
USER_ID=$(echo "$SESSION" | jq -er .user.id)
echo "$USER_ID"Log in later with the same body minus data:
SESSION=$(curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/login \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"correct horse battery 1"}')
ACCESS_TOKEN=$(echo "$SESSION" | jq -er .access_token)
REFRESH_TOKEN=$(echo "$SESSION" | jq -er .refresh_token)The CLI can do both for testing: berth auth signup --app "$APP" --email ada@example.com --password '...' and berth auth login with the same flags.
Email code
No password at all: ask for a code, then trade it for a session. Asking creates the user if the email is new. Codes are valid for 10 minutes, one per minute per email, five attempts.
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/code \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com"}'curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/verify \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","code":"123456"}'Password reset
Ask for a reset code with only the email. The reply is 202 {"sent": true} whether or not the address has an account, so it never reveals who signed up, and it never creates a user. POST /auth/recover does the same.
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/reset \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com"}'Then send the code with the new password to the same route. It signs the user in and signs out every other session. A wrong or expired code is 401.
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/reset \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","code":"123456","password":"a brand new password 3"}'Verify an email address
Every user has email_verified (true or false). Signing in with a code, Apple, or Google verifies the address. For a password signup, the signed-in user asks for a verification code, then sends it back. These codes are separate from sign in codes.
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/verify-email \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{}'curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/verify-email \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"code":"123456"}'The reply is {"user", "verified": true}. The email_verified claim in access tokens changes on the next refresh.
The signed-in user
Send the publishable key in apikey and the user token in Authorization. The token alone also works.
curl -sS https://api.atberth.com/v1/apps/$APP/auth/me \
-H "apikey: $PUBLISHABLE_KEY" \
-H "Authorization: Bearer $ACCESS_TOKEN"Update the profile or the password:
curl -sS -X PATCH https://api.atberth.com/v1/apps/$APP/auth/me \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"data":{"name":"Ada Lovelace"}}'Changing the password takes the current one as well, so a borrowed phone or a leaked access token can't take over the account. A wrong current_password is 403 wrong_password and counts toward the same lockout as a wrong sign in. Users who have only ever signed in with a code, Apple or Google have no password yet and can set one without it.
curl -sS -X PATCH https://api.atberth.com/v1/apps/$APP/auth/me \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"current_password":"old password 1","password":"new password 2"}'JWT claims
Access tokens are HS256 JWTs that expire after an hour. Your server can read the claims, but should check a token by calling /auth/me, since Berth holds the signing secret.
| Claim | Value |
|---|---|
sub | the user id |
email | the user's email |
email_verified | whether the email was verified when the token was issued |
aud | the app slug |
iss | berth |
sid | the session id, shared by the refresh chain |
exp | expiry, Unix seconds |
Look at the claims of the token you have:
echo "$ACCESS_TOKEN" | cut -d. -f2 | tr '_-' '/+' | jq -R '@base64d | fromjson'Refresh and rotation
When the access token is about to expire, trade the refresh token for a new session. Each refresh token works once: the response carries a new one.
OLD_REFRESH_TOKEN=$REFRESH_TOKEN
SESSION=$(curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/refresh \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d "{\"refresh_token\":\"$REFRESH_TOKEN\"}")
ACCESS_TOKEN=$(echo "$SESSION" | jq -er .access_token)
REFRESH_TOKEN=$(echo "$SESSION" | jq -er .refresh_token)If an old refresh token is used again more than 10 seconds after it was swapped, Berth treats it as stolen and revokes the whole chain, including the newest tokens. Within those 10 seconds a second refresh of the same token still works, so a retry or two tabs refreshing at once don't sign the user out. This answers 401:
sleep 11
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/refresh \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d "{\"refresh_token\":\"$OLD_REFRESH_TOKEN\"}"After that the user signs in again. Store the refresh token in the Keychain or Keystore, and write the new one back every time you refresh.
SESSION=$(curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/login \
-H "Authorization: Bearer $PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"correct horse battery 1"}')
ACCESS_TOKEN=$(echo "$SESSION" | jq -er .access_token)
REFRESH_TOKEN=$(echo "$SESSION" | jq -er .refresh_token)Devices and sessions
Each sign in is one session. Refreshing keeps it. List the signed-in user's sessions to build a "signed-in devices" screen. current marks the one making the call, and created_at is when that device signed in.
curl -sS https://api.atberth.com/v1/apps/$APP/auth/sessions \
-H "Authorization: Bearer $ACCESS_TOKEN" | jq '.sessions[] | {id, user_agent, created_at, current}'Sign out one other device. Its refresh token and access tokens stop working at once.
OTHER=$(curl -sS https://api.atberth.com/v1/apps/$APP/auth/sessions \
-H "Authorization: Bearer $ACCESS_TOKEN" | jq -er 'first(.sessions[] | select(.current | not) | .id)')
curl -sS -X DELETE https://api.atberth.com/v1/apps/$APP/auth/sessions/$OTHER \
-H "Authorization: Bearer $ACCESS_TOKEN"Sign out
Ends this session. Send {"all": true} to end every session of the user.
curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/logout \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"all":false}'Managing users from your server
With the secret key you can list, create, ban, and delete users. Deleting a user also deletes the rows they own.
berth auth users list --app "$APP"USER_ID=$(curl -sS -X POST https://api.atberth.com/v1/apps/$APP/auth/users \
-H "Authorization: Bearer $SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"email":"grace@example.com","password":"another long password 2"}' | jq -er .user.id)
berth auth users show --app "$APP" "$USER_ID"curl -sS -X PATCH https://api.atberth.com/v1/apps/$APP/auth/users/$USER_ID \
-H "Authorization: Bearer $SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"banned":true}'
berth auth users ban --app "$APP" "$USER_ID" --unbanberth auth users delete --app "$APP" "$USER_ID" --yesInsights: who uses your app
Every app has an Insights tab in the console, with no code to add. It shows sign-ups, daily, weekly and monthly active users, stickiness, an activation funnel, retention by sign-up week, when people are here, how they sign in, what platform and app they use, and your server error rate and median latency. Every number is compared with the period before. Any small set of values in your users' data (a plan, a goal, a country) gets its own breakdown.
A user counts as active on a day when they sign in or their session refreshes. The same report is available as JSON: GET /v1/apps/$APP/insights?days=30 with a secret key or account key. days is 7 to 90, and days are UTC.
Password policy, rate limits, and lockout
Any key can read the app's password rules, so a signup form can show them:
curl -sS https://api.atberth.com/v1/apps/$APP/auth/settings \
-H "Authorization: Bearer $PUBLISHABLE_KEY" | jq .passwordBy default a password is 8 to 200 characters with a letter and a number. Signup, reset, and password changes all enforce it, and a weak one is 400 weak_password.
Signup, login, code, reset, and refresh are rate limited separately. Each allows per_email requests per email (per refresh token for refresh) and per_ip requests per IP address in every window_seconds. Going over is 429 rate_limited with a Retry-After header.
After lockout_attempts wrong passwords in a row, that email is locked for lockout_seconds, even for the right password (also 429 with Retry-After). Each further lock doubles, up to a day. A right password resets the count.
Change any of it with the secret key. Fields you leave out keep their value, and null resets a group to the defaults.
curl -sS -X PATCH https://api.atberth.com/v1/apps/$APP \
-H "Authorization: Bearer $SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"auth":{"email":{"min_password_length":10,"password_require_symbol":false},
"limits":{"per_email":10,"per_ip":300,"window_seconds":900,
"lockout_attempts":10,"lockout_seconds":600}}}' | jq .app.auth| Setting | Default | Range |
|---|---|---|
email.min_password_length | 8 | 8 to 128 |
email.password_require_number | true | |
email.password_require_symbol | false | any character that is not a letter, digit, or space |
email.require_verification | false | when true, password users must verify their email before they can sign in |
email.brand_color | null | a hex color like #4f46e5 for the button and accents in your sign-in, reset and verify emails |
email.logo_url | null | an https URL to a square PNG or JPG shown at the top of those emails (64 px or larger) |
limits.per_email | 10 | 1 to 10,000 |
limits.per_ip | 300 | 1 to 100,000 |
limits.window_seconds | 900 | 10 to 86,400 |
limits.lockout_attempts | 10 | 3 to 100 |
limits.lockout_seconds | 600 | 10 to 86,400 |
Codes go out as your app: the sender name and the heading are the app's name, with its color and logo when you set them. Every email has a plain-text version, works in dark mode, says when the code expires, and says when it was requested, so a person who didn't ask for it knows to ignore it.
To hear about sign ups, sign ins, failed sign ins, and password changes, add a webhook for auth events.
Calling from a phone or browser
Ship the base URL and the publishable key. Nothing else. Then sign in and send the user token on each request.
JavaScript (fetch)
const BASE = "https://api.atberth.com/v1/apps/notes_app";
const KEY = "bpk_..."; // publishable key only
async function login(email, password) {
const res = await fetch(`${BASE}/auth/login`, {
method: "POST",
headers: { "apikey": KEY, "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!res.ok) throw new Error((await res.json()).message);
return res.json(); // { user, access_token, refresh_token, ... }
}
async function myNotes(session) {
const res = await fetch(`${BASE}/tables/notes/rows?order=created_at.desc`, {
headers: { "apikey": KEY, "Authorization": `Bearer ${session.access_token}` },
});
return (await res.json()).rows;
}Swift
struct Session: Decodable {
let access_token: String
let refresh_token: String
let expires_in: Int
}
let base = URL(string: "https://api.atberth.com/v1/apps/notes_app")!
let publishableKey = "bpk_..."
func login(email: String, password: String) async throws -> Session {
var req = URLRequest(url: base.appending(path: "auth/login"))
req.httpMethod = "POST"
req.setValue(publishableKey, forHTTPHeaderField: "apikey")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try JSONEncoder().encode(["email": email, "password": password])
let (data, response) = try await URLSession.shared.data(for: req)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.userAuthenticationRequired) }
return try JSONDecoder().decode(Session.self, from: data)
}
func notes(_ session: Session) async throws -> Data {
var req = URLRequest(url: base.appending(path: "tables/notes/rows"))
req.setValue(publishableKey, forHTTPHeaderField: "apikey")
req.setValue("Bearer \(session.access_token)", forHTTPHeaderField: "Authorization")
return try await URLSession.shared.data(for: req).0
}Kotlin (OkHttp)
val base = "https://api.atberth.com/v1/apps/notes_app"
val publishableKey = "bpk_..."
val client = OkHttpClient()
val json = "application/json".toMediaType()
fun login(email: String, password: String): JSONObject {
val body = JSONObject().put("email", email).put("password", password)
val req = Request.Builder()
.url("$base/auth/login")
.header("apikey", publishableKey)
.post(body.toString().toRequestBody(json))
.build()
client.newCall(req).execute().use { res ->
check(res.isSuccessful) { "login failed: ${res.code}" }
return JSONObject(res.body!!.string())
}
}
fun notes(accessToken: String): String {
val req = Request.Builder()
.url("$base/tables/notes/rows")
.header("apikey", publishableKey)
.header("Authorization", "Bearer $accessToken")
.build()
client.newCall(req).execute().use { return it.body!!.string() }
}Keep the refresh token in the iOS Keychain or Android Keystore backed storage, never in plain preferences.