Roles

Give your users roles in the Dashboard, such as admin or editor, and use them in your app. Block-Auth sends the user's roles with every login.

Create and assign roles

In the Dashboard, create the roles and assign them to your users. See Dashboard roles.

Each role has a name, which you choose and can rename, and a slug, which Block-Auth generates when you create the role (for example acme-x7k2p9) and never changes. Use the slug in your code: copy it from the Roles tab in the Dashboard, under the role's name.

Show or hide UI

Once the user has logged in with the widget, read their roles in the frontend. They come from your backend's answer (/code and /me in the backend routes), so you don't need anything else.

New from Block-Auth
Copyimport { useBlockAuthUser } from '@block-auth.io/react'

export function AdminLink() {
Copy  const { hasRoleBySlug, isLoadingUser } = useBlockAuthUser()

Copy  if (isLoadingUser || !hasRoleBySlug('acme-x7k2p9')) return null
  return <a href="/admin">Admin panel</a>
}

Replace acme-x7k2p9 with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name.

Protect your backend

How you add the backend login routes

Applies from here on. You pick it once in the SDK Quickstart.

Your backend gets the roles when it redeems the login code (/api/auth/token) and keeps them in the user's session. Check them there before doing anything that needs a role. With the Block-Auth package, read the user with currentUser, which also ends the session at signedExpiredAt (in .NET the roles are role claims):

New from Block-Auth
Copyimport { expressSessionStore } from '@block-auth.io/node/express'

function requireRole(slug) {
  return async (req, res, next) => {
    const user = await routes.currentUser({ session: expressSessionStore(req) })
    if (!user?.roles.some((role) => role.slug === slug)) {
      return res.status(403).json({ error: 'Forbidden' })
    }
    next()
  }
}

app.get('/api/admin/stats', requireRole('acme-x7k2p9'), getStats)

Replace acme-x7k2p9 with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name.

Roles are read at login. If you change a user's roles in the Dashboard, your backend sees them on the user's next login.

Reference

useBlockAuthUser() in React and Vue, and the BlockAuthService signals in Angular, return:

ValueWhat it is
rolesThe user's roles, as { name, slug }.
roleNames / roleSlugsOnly the names, or only the slugs.
hasRoleBySlug(slug)true if the user has that role.
hasAnyRoleBySlug(slugs)true if the user has at least one of them.
hasRole(name) / hasAnyRole(names)The same, by name. Not case-sensitive.
isLoadingUsertrue while the user is loading. Wait for it before deciding.
userThe logged-in user (address, did, roles), or null.