Part 5: Users and permissions
So far everyone can do everything. In this part we will:
- let users sign in, with the
rind-authcrate; - close the catalogue: everyone reads, only the staff writes;
- add the loans, in a second domain, where each member sees only their own.
How rind sees users
rind itself does not know your users. It asks one question per request:
who is this? The answer is an Identity: an id, the flags
is_staff and is_superuser, and the user’s groups. Everything else —
the rules, the modes — reads this identity.
Something must answer the question. You can write it yourself (the
Authentication chapter shows how), or use
rind-auth, which does what Django’s auth app and
djangorestframework-simplejwt do: a user model, password hashing,
POST /token to sign in, JSON Web Tokens, password reset.
Adding rind-auth
rind-auth is a crate of its own, beside rind. While rind is not
published, add it by path, next to rind, in the workspace’s
Cargo.toml:
# Cargo.toml
[workspace.dependencies]
rind = { path = "/path/to/rind/crates/rind" }
rind-auth = { path = "/path/to/rind/crates/rind-auth" }
and in app/Cargo.toml:
[dependencies]
rind-auth.workspace = true
Then, in app():
#![allow(unused)]
fn main() {
// app/src/lib.rs
pub fn app() -> rind::Application {
rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
.models(rind_auth::models::migrations())
.models(catalog_models::migrations())
.models(lending_models::migrations())
.api(catalog_api::api())
.api(lending_api::api())
.with(
rind_auth::Auth::<rind_auth::models::User>::from_env()
.expect("RIND_JWT_SECRET")
.groups(rind_auth::models::groups()),
)
}
}
(lending does not exist yet: we create it below. Add those two lines
when you get there.)
.models(rind_auth::models::migrations())adds the crate’s own user and group tables,auth_userandauth_group, as Django’sdjango.contrib.authdoes. An application can use its own user model instead: see Signing in..with(..)installs a plugin: something that adds routes, checks or behaviour to the application. This one adds the sign-in routes, and answers “who is this?” for every request.from_env()reads the secret that signs the tokens fromRIND_JWT_SECRET. Add it to.env:
RIND_JWT_SECRET=change-me-to-a-long-random-string
Creating users
rind has no createsuperuser command yet, so we write a command of our
own: the equivalent of a Django management command. Commands are added
in main.rs:
// app/src/main.rs
use rind::prelude::*;
use rind_auth::models::User;
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app())
.command(
"create-user",
"creates a user: create-user NAME PASSWORD [--staff]",
create_user,
)
.main()
}
async fn create_user(_app: &rind::Application, args: &[String]) -> rind::cli::Result {
let [name, password, flags @ ..] = args else {
return Err("usage: create-user NAME PASSWORD [--staff]".into());
};
let staff = flags.iter().any(|flag| flag == "--staff");
let db = rind::db::Db::connect(&std::env::var("DATABASE_URL")?)?;
let user = db
.insert(
&Insert::<User>::new()
.value(User::username(), name.clone())
.value(User::is_staff(), staff),
)
.await?;
rind_auth::set_password::<User>(&db, user.id, password, rind_auth::password::ITERATIONS).await?;
println!("created user {} (id {})", user.username, user.id);
Ok(())
}
Insert::<User>::new().value(..) builds an INSERT with typed paths,
and db.insert(..) runs it and returns the new row. set_password
stores the password hashed the way Django hashes it.
rind migrate
rind create-user alice wonderland1
rind create-user bob builder123 --staff
applied auth 0001_initial
…
created user alice (id 1)
created user bob (id 2)
Alice is a member; Bob is a librarian (is_staff).
Signing in
POST /token takes a user name and a password, and answers two tokens:
curl -X POST -H 'Content-Type: application/json' \
-d '{"username": "alice", "password": "wonderland1"}' localhost:8080/token
{"access":"eyJ0eXAiOiJKV1Qi…","refresh":"eyJ0eXAiOiJKV1Qi…"}
The client sends the access token with each request, in the
Authorization header. It is valid for five minutes; POST /token/refresh with the refresh token gives a new one. This is
simplejwt’s protocol, so existing clients work as they are.
To keep the commands short, put the tokens in shell variables:
ALICE=$(curl -s -X POST -H 'Content-Type: application/json' \
-d '{"username": "alice", "password": "wonderland1"}' localhost:8080/token | jq -r .access)
BOB=$(curl -s -X POST -H 'Content-Type: application/json' \
-d '{"username": "bob", "password": "builder123"}' localhost:8080/token | jq -r .access)
A wrong password:
{"detail":"No active account found with the given credentials"}
Rules: who may do what
Now close the catalogue. In both books/views.rs and authors/views.rs,
replace #[rule(anyone)] with:
#![allow(unused)]
fn main() {
#[rule(staff)]
#[rule(anyone, actions(list, retrieve))]
}
A rule says who it is for, and which actions it allows (all of them
when it lists none). The rules are read in order, and the first one that
accepts the request decides. Here: the staff may do everything; anyone
else may only list and retrieve. This is DRF’s
IsAdminUser-or-ReadOnly, without writing a permission class.
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 1}' localhost:8080/books
{"detail":"Authentication credentials were not provided or are invalid."}
The answer is 401: nobody signed in, and signing in might help. With
Alice’s token, it is 403, because signing in did not help:
curl -X POST -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 1}' localhost:8080/books
{"detail":"You do not have permission to perform this action."}
And with Bob’s, the book is created:
{"id":4,"title":"Children of Dune","year":1976,"author":1}
An action name that does not exist in a rule (a typo such as
actions(lsit)) is a compile error, not a rule that silently allows
nothing.
A second domain: the loans
Loans are another subject than the catalogue, so they get a domain of their own:
rind add domain lending
rind add model lending Loan 'borrowed_on:NaiveDate' 'returned_on:Option<NaiveDate>'
The loans point to the books and to the users, so lending-models
depends on catalog-models and on rind-auth. It also uses dates, from
the chrono crate. Add to crates/lending/lending-models/Cargo.toml:
rind-auth.workspace = true
chrono.workspace = true
catalog-models = { path = "../../catalog/catalog-models" }
and chrono to the workspace’s dependencies, in the root Cargo.toml
(rind also re-exports it as rind::db::chrono, which saves the
dependency; the generated code of rind add resource uses chrono
directly, so we add it):
chrono = { version = "0.4", default-features = false, features = ["std", "clock", "serde"] }
The model:
#![allow(unused)]
fn main() {
// crates/lending/lending-models/src/lib.rs
use catalog_models::Book;
use chrono::NaiveDate;
use rind::prelude::*;
use rind_auth::models::User;
/// A book lent to a member of the library.
#[derive(Debug, Clone, Model)]
#[model(table = "lending_loan")]
pub struct Loan {
pub id: i64,
#[fk(Book, on_delete = cascade, reverse = loans)]
pub book_id: i64,
#[fk(User, on_delete = cascade, reverse = loans)]
pub borrower_id: i64,
#[column(default = "CURRENT_DATE")]
pub borrowed_on: NaiveDate,
/// Empty while the book is still out.
pub returned_on: Option<NaiveDate>,
}
impl Loan {
/// The loans of one user.
pub fn of(user: &rind::api::Identity) -> Query<Loan> {
Query::new().filter(Loan::borrower_id().eq(user.id))
}
}
}
Two new things:
default = "CURRENT_DATE"is a default given by the database, written in SQL.Loan::of(user)is a scope: a plain function that returns a query. It is where a Django developer would write a custom manager method,Loan.objects.of(user). You can test it without HTTP, and use it anywhere.
Domains are ordered: a domain may point to the domains before it, never
after. lending comes after catalog and auth in app(), which is
where the tool put it. Then:
rind make
rind migrate
lending 0001_initial
create lending_loan
key lending_loan.book_id
key lending_loan.borrower_id
The loans resource
rind add resource lending Loan --rule authenticated
Add catalog-models = { path = "../../catalog/catalog-models" } to the
dependencies of crates/lending/lending-api/Cargo.toml, then write the
serializer and the input:
#![allow(unused)]
fn main() {
// crates/lending/lending-api/src/loans/serializers.rs
use catalog_models::Book;
use chrono::NaiveDate;
use lending_models::Loan;
use rind::{Input, Serializer};
/// A loan as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Loan)]
pub struct LoanOut {
#[field(mandatory)]
pub id: Option<i64>,
#[field(name = "book")]
pub book_id: Option<i64>,
#[field(name = "borrower")]
pub borrower_id: Option<i64>,
pub borrowed_on: Option<NaiveDate>,
pub returned_on: Option<Option<NaiveDate>>,
}
/// What a member writes to borrow a book: only the book. The borrower is
/// who is signed in, and the date is today.
#[derive(Debug, Input)]
#[input(model = Loan)]
pub struct LoanIn {
#[input(name = "book", fk = Book)]
pub book_id: Option<i64>,
}
}
returned_on is an Option<Option<…>>: the outer Option is “was the
field asked for”, the inner one is the SQL NULL.
The input has only book. A member does not choose the borrower: it is
whoever is signed in. That is set by the resource, below.
Modes: which rows each user sees
Alice must see her loans, not Bob’s. In DRF you would write
get_queryset() and filter on request.user. In rind, a rule can give a
mode: a value that decides which rows the request works on, and which
fields it hides.
#![allow(unused)]
fn main() {
// crates/lending/lending-api/src/loans/views.rs
use lending_models::Loan;
use rind::api::resource::{self, Writes};
use rind::api::{ApiError, Ctx, QueryParams};
use rind::prelude::*;
use rind::{Resource, actions};
use super::filters::LoanFilters;
use super::serializers::{LoanIn, LoanOut};
/// What a user sees of the loans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoanMode {
/// The librarians: every loan.
All,
/// A member: their own loans.
Own,
}
/// Members borrow books and give them back; librarians see every loan.
#[derive(Resource)]
#[resource(
model = Loan,
path = "loans",
out = LoanOut,
filters = LoanFilters,
input = LoanIn,
mode = LoanMode,
hooks,
actions
)]
#[rule(staff, mode = LoanMode::All)]
#[rule(authenticated, actions(list, retrieve, create, give_back), mode = LoanMode::Own)]
#[mode(LoanMode::All, query = Query::new())]
#[mode(LoanMode::Own, query = Loan::of(user), hide(borrower))]
#[ordering(by(id, borrowed_on), default("-borrowed_on"))]
pub struct LoanResource;
}
Read the rules and the modes together:
- the staff may do everything, in mode
All: every loan; - a signed-in user may list, retrieve, create and
give_back(an action we write in part 6), in modeOwn: the rows ofLoan::of(user), and the fieldborroweris hidden, since it is always themselves.
There is no delete in #[resource], so nobody deletes a loan.
Everything happens inside the mode’s rows: the list, the count, the
filters, and each object. A loan that is not yours does not exist for
you: GET /loans/3 answers 404, not 403, so that nobody learns which
ids exist.
A hook: completing a write
hooks in #[resource] says that the resource implements Writes: code
that runs inside the write’s transaction. It is where Django’s
perform_create, or an overridden save(), goes. Ours checks that the
book is on the shelf, and sets the borrower:
#![allow(unused)]
fn main() {
impl Writes for LoanResource {
/// A book can only be borrowed when it is on the shelf. A new loan is
/// the signed-in user's.
async fn creating(
ctx: &Ctx,
input: &LoanIn,
insert: Insert<Loan>,
) -> Result<Insert<Loan>, ApiError> {
let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
let out = Query::<Loan>::new()
.filter(Loan::book_id().eq(input.book_id.unwrap_or_default()))
.filter(Loan::returned_on().is_null());
if ctx.db.count(&out).await? > 0 {
return Err(ApiError::Validation(
[("book".to_owned(), vec!["This book is already lent.".to_owned()])].into(),
));
}
Ok(insert.value(Loan::borrower_id(), user.id))
}
}
}
ctxis the context of the request:ctx.useris the identity,ctx.dbthe database (here, the write’s transaction).creatingreceives the input, already validated, and theINSERTthat rind is about to run. It returns that insert, possibly completed.ApiError::Validationanswers a 400 with messages per field, like a DRFValidationError({"book": [...]}).
The give_back action is named in a rule, so the code does not compile
until it exists. Add an empty block for now, and fill it in part 6:
#![allow(unused)]
fn main() {
#[actions]
impl LoanResource {}
}
Coming from Django: there are no signals. Code that must run when a loan is created is in the hook, where you can see it, or in a function the hook calls.
Trying it
curl -X POST -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"book": 1}' localhost:8080/loans
{"id":1,"book":1,"borrowed_on":"2026-11-27","returned_on":null}
borrower is not there: the mode hides it. Alice borrows book 3 too.
Then Bob tries to borrow book 1:
curl -X POST -H "Authorization: Bearer $BOB" -H 'Content-Type: application/json' \
-d '{"book": 1}' localhost:8080/loans
{"book":["This book is already lent."]}
Bob borrows book 2 instead. Now compare the lists. Alice’s:
curl -H "Authorization: Bearer $ALICE" localhost:8080/loans
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 2, "pages": 1},
"results": [
{"id": 1, "book": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 2, "book": 3, "borrowed_on": "2026-11-27", "returned_on": null}
]
}
Bob’s, as a librarian, has every loan, with their borrowers:
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 3, "pages": 1},
"results": [
{"id": 1, "book": 1, "borrower": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 2, "book": 3, "borrower": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 3, "book": 2, "borrower": 2, "borrowed_on": "2026-11-27", "returned_on": null}
]
}
And Bob’s loan, seen by Alice:
curl -H "Authorization: Bearer $ALICE" localhost:8080/loans/3
{"detail":"Not found."}
Next: Part 6: Actions and tests.