Skip to content

Blog (author scoping)

This tutorial builds examples/blog: an editorial admin with posts, categories, tags, comments, and two roles. Authors only see and edit their own posts; administrators moderate everything.

The blog starter writes the schema, resources, policies, actions, and seed. This guide explains every piece and shows the running app. It assumes you are comfortable with JavaScript or TypeScript and new to Dashild.

What you will learn:

  • How to model a post with an enum, a many-to-many relation, and a Bytes cover.
  • How scope turns one resource into “my posts” for an author and “all posts” for an admin.
  • How role-aware policies hide and refuse actions.
  • How declared actions update status and publishedAt together.
  • How comments inherit the post’s author scope.
  • How CSV import/export respects the active scope.

The finished app is in the repository if you want to compare.

Terminal window
pnpm create dashild@latest my-blog --template blog --database sqlite --yes
cd my-blog

The blog starter adds:

  • Category, Tag, Post, and Comment models, plus a Role enum and User.role.
  • One resource per model under src/dashild/resources/.
  • src/dashild/policies.ts, src/dashild/actions/index.ts, and the panel registration.
  • A replacement src/lib/session.ts that returns the user’s role. The starter lists it in overwrite, so it replaces the generated session file instead of being ignored.
  • A seed with an admin, two authors, posts, tags, and comments.

--database sqlite keeps the example self-contained (prisma/dev.db).

BETTER_AUTH_URL must match the URL you open. Change it if you use another port:

Terminal window
BETTER_AUTH_URL=http://localhost:3001 pnpm dev

Sign in to the blog panel

The panel uses the same Better Auth login; the demo users have different roles.

The blog adds a role and an editorial workflow to the Better Auth models:

prisma/schema.prisma
enum Role {
ADMIN
AUTHOR
}
enum PostStatus {
DRAFT
REVIEW
PUBLISHED
}
model Post {
id String @id @default(uuid())
title String
slug String @unique
excerpt String?
body String
status PostStatus @default(DRAFT)
publishedAt DateTime?
cover Bytes?
authorId String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
categoryId String?
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
tags Tag[]
comments Comment[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Comment {
id String @id @default(uuid())
authorName String
body String
approved Boolean @default(false)
postId String
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
}

What matters for the admin:

  • authorId is the ownership field. The policy scopes every query by it.
  • status is an enum rendered as a badge. publishedAt is separate: an action sets both together.
  • tags is a many-to-many relation. The form renders a multi-select and the relation manager uses attach/detach.
  • cover is Bytes?; the form renders a file picker and sends base64.
  • Comment.postId is required and cascades. A comment cannot exist without its post, and deleting a post deletes its comments.

User.role is a plain Prisma enum. session.ts reads it and returns roles: ["ADMIN"] or roles: ["AUTHOR"], which is the shape every policy receives.

Terminal window
pnpm prisma migrate dev --name init
pnpm prisma generate
pnpm db:seed

migrate dev writes the migration, but on Prisma 7 it does not regenerate the Dashild metadata. Run prisma generate before opening the panel or using make:resource.

The seed creates:

Email Role Password
ana@blog.test ADMIN dashild123
bruno@blog.test AUTHOR dashild123
carla@blog.test AUTHOR dashild123

It also creates two categories, four tags, three posts, and two comments. Bruno owns two posts; Carla owns one. The published post has one approved and one pending comment.

pnpm db:seed is re-runnable: it deletes comments, posts, tags, categories, and users in dependency order, then recreates them.

The panel registers five resources:

src/dashild/panel.ts
export const panel = definePanel({
title: "Admin",
path: "/admin",
locale: "en",
resources: [
postResource,
categoryResource,
tagResource,
commentResource,
staffResource,
],
auth: { getCurrentUser, signOut },
});

They appear in three groups:

  • Content: Posts, Categories, Tags.
  • Moderation: Comments.
  • Settings: Staff.

The blog dashboard

A resource is one file of data. The catch-all route renders lists, forms, details, and relation managers from these definitions.

src/dashild/resources/post.ts is the center of the app:

src/dashild/resources/post.ts
export const postResource = defineResource({
model: "Post",
navigation: { label: "Posts", slug: "posts", group: "Content", icon: "file-text" },
table: {
searchable: ["title", "excerpt"],
pageSize: 25,
columns: [
{ field: "title", label: "Title", sortable: true },
{
field: "status",
label: "Status",
format: "badge",
tone: { DRAFT: "muted", REVIEW: "accent", PUBLISHED: "green" },
},
{ field: "category", label: "Category", display: "name", sortable: true },
{ field: "author", label: "Author", display: "name", sortable: true },
{ field: "publishedAt", label: "Published", format: "datetime", sortable: true },
],
filters: [
{ field: "status", type: "enum", label: "Status" },
{ field: "category", type: "relation", label: "Category", display: "name" },
{ field: "author", type: "relation", label: "Author", display: "name" },
],
actions: [
{ name: "create", placement: "header" },
{ name: "view", placement: "row" },
{ name: "edit", placement: "row" },
{ name: "delete", placement: "row" },
{ name: "publish", label: "Publish", placement: "row", requires: "publish", variant: "secondary" },
{ name: "unpublish", label: "Unpublish", placement: "row", requires: "unpublish", confirm: true },
],
},
form: {
fields: [
{ field: "title", type: "text", rules: { required: true } },
{ field: "slug", type: "text", rules: { required: true } },
{ field: "excerpt", type: "textarea" },
{ field: "body", type: "textarea", rules: { required: true } },
{ field: "status", type: "select" },
{ field: "publishedAt", type: "datetime" },
{ field: "author", type: "relation", relation: "author", display: "name", rules: { required: true } },
{ field: "category", type: "relation", relation: "category", display: "name" },
{ field: "tags", type: "relation", relation: "tags", display: "name", multiple: true },
{ field: "cover", type: "bytes" },
],
},
policy: { scope: "author" },
});

The posts table

An admin sees every post. The status badge has a tone per enum value, and the filters are server-side.

Creating a post

The create form starts empty but already includes the author, category, tags, and cover fields.

Editing a post

The form includes the relation select for author and category, the multi-select for tags, and a file picker for the cover.

policy.scope: "author" is a marker, not the rule. The actual predicate is in policies.ts; the string only signals that the resource is scoped.

Open src/dashild/policies.ts:

src/dashild/policies.ts
const isAdmin = (ctx: { roles: string[] }) => hasRole(ctx, "ADMIN");
export const policies = definePolicies<CurrentUser>({
resources: {
Post: {
scope: (ctx) => (isAdmin(ctx) ? {} : { authorId: ctx.user.id }),
can: {
create: () => true,
update: () => true,
delete: isAdmin,
publish: () => true,
unpublish: () => true,
},
},
Comment: {
scope: (ctx) =>
isAdmin(ctx) ? {} : { post: { authorId: ctx.user.id } },
can: {
create: () => true,
update: () => true,
delete: isAdmin,
approve: () => true,
unapprove: () => true,
},
},
User: {
scope: () => ({}),
can: { create: () => false, update: isAdmin, delete: () => false },
},
},
});

scope returns a Prisma where that the server applies to reads, updates, deletes, and relation managers. For an admin it is {} (all rows); for an author it is { authorId: user.id }.

Bruno only sees his own posts

Signed in as Bruno (AUTHOR), the same resource returns two posts instead of three. The rows are filtered on the server, not hidden in the browser.

create and update are value-aware: an author can only attribute a post to themselves. The User.scope for non-admins is { id: user.id }, so the author select and the staff list only show their own account. Admins keep {} and can assign any author.

Comments are scoped through the relation: { post: { authorId: user.id } }. An author can moderate comments on their own posts but cannot reach a comment on someone else’s post, even with a guessed id. Only admins can create or edit comments in the panel, so approved cannot be forged there; authors still use the approve action for their own posts.

The can block is deny-by-default for declared actions: if publish or approve is missing, the action disappears from the UI and the server refuses it. Authors can delete neither posts nor comments in this example; only admins can.

The resource declares the action; the handler runs on the server:

src/dashild/actions/index.ts
Post: {
publish: (context) => setPostStatus(context, "PUBLISHED"),
unpublish: (context) => setPostStatus(context, "DRAFT"),
},
Comment: {
approve: (context) => setCommentApproved(context, true),
unapprove: (context) => setCommentApproved(context, false),
},

setPostStatus updates two fields so the data stays consistent:

src/dashild/actions/index.ts
await db.post.update({
where: { id: context.id },
data: {
status,
publishedAt: status === "PUBLISHED" ? new Date() : null,
},
});

Post row actions

“Publish” and “Unpublish” come from table.actions; unpublish confirms first.

Comment moderation

Comments show the approved flag, the post, and the author name.

Comment row actions

“Approve” and “Unapprove” are normal actions. The handler runs with the scoped client, so an author cannot approve a comment on another author’s post.

context.db is Prisma extended with the policy scope. It is typed unknown and can be undefined, so the example narrows it with dbFrom. context.id is optional; check it before a row action.

src/dashild/resources/staff.ts manages User:

src/dashild/resources/staff.ts
export const staffResource = defineResource({
model: "User",
navigation: { label: "Staff", slug: "staff", group: "Settings", icon: "users" },
table: {
searchable: ["name", "email"],
columns: [
{ field: "name", sortable: true },
{ field: "email", sortable: true },
{
field: "role",
format: "badge",
tone: { ADMIN: "accent", AUTHOR: "muted" },
},
],
filters: [{ field: "role", type: "enum", label: "Role" }],
},
form: {
fields: [
{ field: "name", type: "text", rules: { required: true } },
{ field: "role", type: "select" },
],
},
policy: { scope: "public" },
});

The staff table

The role badge is another enum column. The policy hides create/delete from everyone and allows updates only for admins.

There is a subtlety: session.ts returns roles from User.role, but the panel reads the role from the database on every request. If an admin changes a user’s role, that user gets the new permissions on their next request. The demo does not need to sign out and back in.

The list buttons are available on every resource and respect the active scope:

  • An admin exports all posts.
  • An author exports only their own posts.
  • The same predicates apply to import, so an author cannot create a post for someone else by sending an authorId.

Rules:

  • Export uses the current search, filters, sort, and page size, capped at 5,000 rows. Relation columns export ids, and Bytes columns (the cover) are excluded.
  • Import is create-only, capped at 1,000 rows and 2 MB. Headers must match form.fields; unknown columns are ignored.
  • Types: Int/Float are coerced, booleans accept true/1, and Decimal/BigInt stay strings.
  • Relations use the form field name (author, category) with the id as the value, not the display name. The basic CSV path does not import many-to-many tags; use the form or the relation manager for those.

Advanced import mapping and updates are reserved for Dashild Pro.

Terminal window
pnpm dev

Open http://localhost:3000/admin.

As ana@blog.test (ADMIN):

  1. See all three posts, filter by status or author.
  2. Publish the draft, then unpublish it. The status and publishedAt change together.
  3. Open Comments and approve the pending comment.
  4. Open Staff and change a user’s role.

Sign out and sign in as bruno@blog.test (AUTHOR):

  1. The posts list now shows only Bruno’s two posts.
  2. He can create and edit his posts and publish them.
  3. He sees comments only on his posts; Carla’s post is not reachable.
  4. He cannot delete a post or change a role.

Finally:

Terminal window
pnpm dashild doctor
pnpm build

Add a model the same way as any Dashild app:

Terminal window
pnpm prisma migrate dev --name add_series
pnpm prisma generate
pnpm dashild make:resource Series

Then edit the generated resource, add predicates to policies.ts, and run pnpm dashild doctor. make:action Series feature appends a handler stub without touching the resource.

For the full resource-by-resource workflow from an empty app, read the vet clinic tutorial. For policies and scope in depth, read the policies guide.

  • An author sees every post: the Post.scope branch is returning {}; check session.ts returns roles and that hasRole receives "ADMIN" only for admins.
  • Publish is missing: the publish predicate is absent from can, or the action name collides with a built-in.
  • Comments are empty for an author: the Comment.scope path expects post.authorId; a comment whose post has no author will not match.
  • make:resource cannot find the model: run pnpm prisma generate after migrate dev.
  • Cover upload fails: Bytes fields are excluded from CSV; use the form.