Skip to Content

Sign-in

Give a product its own users and its own sign-in pages on Floor Auth, and check who's calling in the backend.

This page gives SAC its own users and sign-in, then shows how the backend sees the person calling it. You'll define roles, turn on the sign-in methods SAC wants, sign people in from SAC's own pages with @usefloor/floor, give people access, and guard routes by role. You need a backend and a dashboard (see The dashboard's client).

Each project has its own users. A SAC user is SAC's alone: another product's users, and Floor's operators, are apart. The product draws its own sign-in pages in its own design; Floor Auth keeps the accounts, passwords, codes and sessions, and signs the tokens the backend checks.

1. Define the project's roles

floor roles set sac "admin=Runs the site and its lanes" "guard=Works the gates" "resident=Lives there"
floor roles list sac

roles set replaces the whole list; removing a role removes it from everyone who holds it. A user holds one role in the project, or none.

2. Turn on the ways people sign in

Every method is off until the project turns it on, in the console under the project's Auth › Sign-in methods:

MethodPeople sign in with
Email and passwordan email and a password; "Forgot password" emails a reset link. Optionally the email is confirmed first
Username and passworda name unique in the project, no email: good for people who share a device, like a shop's tablet. The password is reset from the console
Email codea 6-digit code, a link to tap, or both, sent to their email
Phone codea 6-digit code sent to their phone by WhatsApp

Auth › Sign-ups and sessions says who may make an account (only invited people, anyone, or anyone at given email domains), the role a new account gets, how long people stay signed in, and whether signing in on a new device signs them out elsewhere. Auth › Messages holds the wording of the emails and WhatsApp messages, in English and Urdu, sent in the product's name from its own address or number.

3. Get the key and the redirect URLs

Auth › Keys and URLs shows what the app needs:

  • The Auth URL, https://usefloor.dev/auth/v1/sac. A product's own hostname answers the same paths too (https://sac.example.com/auth/v1/sac/…), so a dashboard deployed on Floor signs in on its own origin.
  • The publishable key, pk_sac_…. It is safe in a browser or a phone app: it names the project and opens nothing by itself. Rolling it stops the old one at once.
  • Redirect URLs: where links in emails (confirm, reset, invite, magic link) may send people back to. A URL ending in * allows anything under it. Anything else is refused. They must be https, except http://localhost and 127.0.0.1 for development, or an app's own scheme (myapp://).

4. Sign in from the product's own pages

@usefloor/floor is on npm:

bun add @usefloor/floor

Make one auth for the app:

import { createAuth } from '@usefloor/floor'
import { configure } from './floor.gen'

export const auth = createAuth({ url: location.origin, project: 'sac', key: 'pk_sac_…' })

// Every call to the backend carries a fresh access token.
configure({ token: () => auth.accessToken() })

Draw only the methods that are on, then sign in by whichever the person picks:

const { methods, signup } = await auth.settings()

await auth.signInWithPassword({ email, password })          // or { username, password }

await auth.sendCode({ email })                               // or { phone: '+923001234567' }
await auth.verifyCode({ email, code })

await auth.signUp({ email, password, name })                 // when sign-ups are open
await auth.resetPassword({ email })                          // "Forgot password"

Links from emails come back to a redirect URL with #type=…&token=… in the fragment. On that page:

const { link, session } = await auth.handleLink()
if (link?.type === 'reset') await auth.setPassword({ token: link.token, password })
if (link?.type === 'invite') await auth.acceptInvite({ token: link.token, password })
// A magic link or a confirm link has signed them in already: `session`.
  • The session is kept in localStorage (pass storage for something else, such as a phone app's store) and followed across tabs. auth.accessToken() refreshes it a minute before it runs out.
  • Refresh tokens rotate. Each refresh returns a new one, and using an old one again ends the session.
  • auth.onChange(session => …) hears every sign-in, refresh and sign-out; auth.user() and auth.updateUser({ name, password, currentPassword }) read and change the signed-in person.
  • Signing out: auth.signOut() ends this session; auth.signOut({ scope: 'all' }) ends every one of theirs.
  • Refusals are FloorErrors: a wrong password is a 401, too many tries a 429, a method that's off a 403.

5. Give people access

In the console, Auth › Users lists the project's users: invite someone, change their role, disable them, end their sessions, or send them a password reset.

A product's own admin page does the same from its backend:

let a = cx.grant(Access::new("imran@example.com", "guard").name("Imran Ali").org("gulberg-residency")).await?;
if let Some(url) = a.invite_url {
    // Send it to them: it opens the product's own page with #type=invite, where they set a password.
}
cx.grant(Access::remove("imran@example.com")).await?;   // no role; their sessions end
cx.disable_person("imran@example.com").await?;          // can't sign in at all

See cx.grant. Organizations group the users from one customer: a user's org is a slug the product chooses (a residency, a company). A token carries it, and a backend keeps each customer's rows apart with it (cx.org(), below).

5. Decide who may call each route

Every route says who may call it, and the backend checks the token before the handler runs:

AttributeLets in
#[get(public)]anyone
#[get(signed_in)]any valid Floor token for this project: a person's or a service client's
#[get(role = "admin")], #[get(roles = "admin, guard")]those roles
#[get(can = "gates:open")]the roles permissions.rs allows for it
#[post(device)]the project's devices (Devices and MQTT)

permissions.rs names what each role may do:

floor::permissions! {
    visits: { read: [admin, guard], write: [admin, guard] },
    gates: { open: [admin, guard] },
    vehicles: { write: [admin] },
}

No token, or one Floor doesn't vouch for, is a 401. A valid token without the permission is a 403. A token for another project, including another environment of the same product, is refused. See Realtime and permissions.

6. Read the caller in a handler

// api/me.rs  →  GET /api/me
use floor::prelude::*;

#[derive(Serialize, Type)]
pub struct Me {
    id: String,
    name: Option<String>,
    role: Option<String>,
    can_open_gates: bool,
}

#[get(signed_in)]
pub async fn get(cx: Cx) -> Result<Json<Me>> {
    let u = cx.user()?;
    Ok(Json(Me {
        id: u.sub.clone(),
        name: u.name.clone(),
        role: u.roles.first().cloned(),
        can_open_gates: cx.can("gates:open"),
    }))
}
cx.Gives
user()the caller: sub (the user's id, stable; use it as a foreign key), kind (user, service or device), roles, org, email, name, expires_at. A 401 when nobody is signed in
org()the caller's organization slug; a 403 when they aren't in one
can("gates:open")whether the caller's roles allow it
require("gates:open")a 403 unless they do

Scope every query to the caller's organization, so one customer never sees another's visits:

let visits: Vec<Visit> = sqlx::query_as("select … from visits where organization = $1 order by id desc limit 50")
    .bind(cx.org()?)
    .fetch_all(cx.db())
    .await?;

Service clients

A service client is a program that calls with its own identity: a reporting job, another product's backend, or your backend calling Floor's own HTTP API.

floor clients create sac sac-reports --name "SAC nightly reports" --kind service   # prints the secret once

It trades its id and secret for an access token:

curl -X POST https://usefloor.dev/oauth/token -u sac-reports:$SECRET -d grant_type=client_credentials
  • The token lasts 15 minutes, has sub: "client:sac-reports" and token_use: "service", and is for its project only.
  • It has no roles. It passes signed_in routes, not role or can ones. Check cx.user()?.kind == "service" where it matters.
  • Its secret. Store it as a project secret, never in the repository. floor clients rotate-secret sac sac-reports replaces it, and the old one stops working at once.
  • From TypeScript, serviceToken({ url, clientId, clientSecret }) from @usefloor/floor fetches, caches and renews the token.

Checking tokens outside a Floor backend

A Floor backend checks tokens for you. A server that isn't one can check them itself with verifyToken, against Floor's published keys (cached for an hour):

import { verifyToken } from '@usefloor/floor'

const claims = await verifyToken(token, { issuer: 'https://usefloor.dev', project: 'sac' })
// claims.sub, claims.roles, claims.org, claims.email, claims.token_use

It checks the signature, issuer, expiry and project, and accepts only people's access tokens unless you pass uses: ['access', 'service'].

Security notes

  • Passwords are stored as Argon2id hashes. Five wrong passwords lock the account for 15 minutes, and each address can be sent at most three codes or resets an hour.
  • Codes are 6 digits, last 10 minutes and allow 5 tries. Links work once.
  • Disabling a user, taking their role away, or "End sessions" ends their sessions and revokes every refresh token. Access tokens already issued expire within the project's access-token time (an hour unless it's changed).
  • The product still decides what each role may do with its data; Floor tells it who is calling and in which role.

On this page