Skip to Content

Realtime and permissions

Declare who may do what once in permissions.rs, check it on routes and in code, and publish typed realtime channels.

Two small files at the crate's root describe a backend to the outside: permissions.rs says which roles may do what, and channels.rs names the realtime channels it publishes on. Both reach the dashboard's TypeScript client too, so a typo in a permission or a channel's message type is a type error there.

Roles come from Floor

A user's roles are their roles in the project, set in Floor: the project defines them, and each user holds some. Floor puts them in the user's access token, and the backend reads them from there.

floor roles set sac admin guard "resident=Lives on site"
floor invite --email guard@example.com --name "Gate 3 guard" --org acme-towers --role sac:guard

See Sign-in for users, organizations and service clients.

permissions.rs

Name each action once, as resource: { action: [roles] }:

// permissions.rs
floor::permissions! {
    visits: { read: [admin, guard], remark: [admin, guard], reopen: [admin] },
    gates: { open: [admin, guard] },
    vehicles: { read: [admin, guard], write: [admin] },
}

That defines visits:read, visits:remark, visits:reopen, gates:open, vehicles:read and vehicles:write, and which roles have each. A role not listed doesn't have it.

On a route: can

#[get(can = "visits:read")]
pub async fn get(cx: Cx, Query(page): Query<Page>) -> Result<Json<Visits>> {
    // only admins and guards get here
}
  • No token is a 401. A token without the permission is a 403, you may not visits:read, before the handler runs.
  • A can that permissions.rs doesn't define stops the backend at start, with the route and the missing permission, and fails its tests. A misspelt permission can't ship.
  • role = "admin" and roles = "admin, guard" check roles directly, without permissions.rs. Prefer can: it keeps the decision in one file the dashboard shares.

WebSockets take the same options: #[ws(can = "visits:read")].

In code: cx.can and cx.require

When the decision depends on the data, check in the handler:

// api/visits/[id]/remarks.rs  →  POST /api/visits/{id}/remarks
#[post(can = "visits:remark")]
pub async fn post(cx: Cx, Path(id): Path<i64>, Json(r): Json<Remark>) -> Result<NoContent> {
    let visit = load(&cx, id).await?;
    // Guards remark on open visits; a closed one takes an admin.
    if visit.status == "done" && !cx.can("visits:reopen") {
        return Err(Error::forbidden("this visit is closed"));
    }
    // …
    Ok(NoContent)
}
  • cx.can("gates:open") is true when the caller's roles allow it, false otherwise (and when nobody is signed in).
  • cx.require("gates:open")? is a 403 unless they do.

Organizations

Permissions say what a role may do; they don't say whose data. A project's users come from many organizations, one per customer, so filter by the caller's organization in every query:

.bind(cx.org()?)   // 403 when the caller isn't in an organization

channels.rs

A channel is a name and the type of message it carries:

// channels.rs
floor::channel!(pub Lanes = "lanes", crate::model::LaneCard);
floor::channel!(pub PoleAlerts = "alerts", crate::model::PoleAlert);
// src/model.rs
#[derive(Debug, Clone, Serialize, Type)]
pub struct LaneCard {
    pub lane: i64,
    pub plate: String,
    pub action: String,
    pub visit: i64,
}

The message type needs Serialize and floor::Type. Publish from any handler:

use crate::channels::Lanes;

let listeners = cx.publish(Lanes, &LaneCard { lane: e.lane_id, plate: e.plate, action: action.into(), visit }).await?;
  • The channel is app:<name> on the project's realtime hub: Lanes publishes on app:lanes.
  • publish returns how many listeners got the message. Nobody listening isn't an error.
  • cx.publish_to("lanes", &value) publishes without a declared channel, for a one-off. A declared channel is better: the dashboard gets its type.

Who hears a channel

Any signed-in user of the project can listen on any of its app: channels, through Floor's realtime hub. Permissions and organizations don't filter them. So publish only what every user of the project may see.

Putting the organization in the name keeps each customer's dashboard to its own messages:

cx.publish_to(&format!("lanes.{org}"), &card).await?;

That sorts messages; it doesn't protect them, because a user who knows another channel's name can listen to it. Channel names are 1 to 64 characters of a-z, 0-9, ., _ and -.

For data only some roles may see, or that depends on the caller, use a WebSocket with can: it's checked per caller.

In the dashboard

The generated client carries both files:

import { can, channels, listen } from './floor.gen'

if (can(user, 'gates:open')) showOpenButton()                       // 'gates:close' is a type error
listen(floor.realtime, channels.lanes, (card) => showCard(card.plate)) // card: LaneCard

can decides as the backend does, from the same table. listen takes @usefloor/floor's floor.realtime or anything with the same subscribe. See The dashboard client.

In tests

let guard = t.sign_in(&["guard"]);
assert_eq!(t.get("/api/visits", Some(&guard)).await.status, 200);
let resident = t.sign_in(&["resident"]);
assert_eq!(t.get("/api/visits", Some(&resident)).await.status, 403);

let published = t.published();               // (channel, message)
assert_eq!(published[0].0, "app:lanes");
assert_eq!(published[0].1["action"], "open");

See Testing.

On this page