# Quick start

This guide walks you through setting up Permissions from scratch. By the end, you will have:

- A set of permission definitions
- A Role model that stores permissions
- A User model with role assignments
- Authorization checks in a controller using Bouncer

## Overview

You need an AdonisJS 7 app with Lucid and the auth package. Your project must point at the AdonisJS Plus registry. See [Installation and setup](/docs/get-started/installation#premium-packages).

## Install and configure

Permissions uses [AdonisJS Bouncer](https://docs.adonisjs.com/guides/auth/authorization) under the hood to authorize actions. If you have not already installed Bouncer, run the following command first.

```sh
node ace add @adonisjs/bouncer
```

This command installs the package, creates the `app/abilities/main.ts` file, generates the Bouncer middleware at `app/middleware/initialize_bouncer_middleware.ts`, and registers it in your HTTP kernel.

Next, install Permissions. The command installs the package and runs its configure step.

```sh
node ace add @adonisplus/permissions
```

The configure step makes these changes:

1. Creates `start/permissions.ts`, where you define your permissions.
2. Creates `app/middleware/authorize_middleware.ts` and registers it in `start/kernel.ts` as the named middleware `authorize`.
3. Adds the `indexPermissions()` hook to `adonisrc.ts`. The hook writes `.adonisjs/client/permissions.d.ts`, which your frontend imports as `@generated/permissions`.
4. Creates a `Guard` component in `inertia/utils/permissions.tsx` (React) or `inertia/utils/permissions.vue` (Vue), when `inertia/pages` holds `.tsx` or `.vue` files.

## Define permissions

Permissions represent the actions a user can perform in your application. You define them in a single file so that every part of your codebase references the same set of keys.

The configure command already created the `start/permissions.ts` file for you. Open it and declare your permissions using the `definePermissions` function. Each permission follows the `resource.action` pattern.

```ts [start/permissions.ts]
import { definePermissions } from '@adonisplus/permissions'

export const permissions = definePermissions({
  product: {
    create: 'Create new products',
    update: 'Update existing products',
    delete: 'Delete products permanently',
  },
  billing: {
    refund: 'Issue refunds to customers',
  },
})

export type PermissionKey = ReturnType<typeof permissions.keys>[number]
```

This produces four permission keys: `product.create`, `product.update`, `product.delete`, and `billing.refund`. All keys are type-safe and autocompleted by your editor.

Keep the `PermissionKey` export. The `authorize` middleware and your frontend types import it.

## Create the database tables

You need two database tables to store roles and their assignments:

- **roles**: Stores role names and the permissions assigned to each role as a JSON column.
- **user_roles**: A pivot table that links users to their roles.

::steps

### Create the migrations

Run the following commands to generate the two migration files.

```sh
node ace make:migration roles
```

```sh
node ace make:migration user_roles
```

### Define the roles table

Open the generated roles migration file and define the table schema. The `permissions` column stores a JSON array of permission keys assigned to the role.

```ts [database/migrations/xxxx_create_roles.ts]
import { BaseSchema } from '@adonisjs/lucid/schema'

export default class extends BaseSchema {
  protected tableName = 'roles'

  async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments('id')
      table.string('name').unique().notNullable()
      table.text('permissions').defaultTo('[]')
      table.timestamp('created_at')
      table.timestamp('updated_at')
    })
  }

  async down() {
    this.schema.dropTable(this.tableName)
  }
}

```

### Define the user_roles pivot table

Open the generated user_roles migration file and define the pivot table schema. The unique constraint on `user_id` and `role_id` prevents duplicate role assignments.

```ts [database/migrations/xxxx_create_user_roles.ts]
import { BaseSchema } from '@adonisjs/lucid/schema'

export default class extends BaseSchema {
  protected tableName = 'user_roles'

  async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments('id')
      table.integer('user_id').notNullable().unsigned()
      table.integer('role_id').notNullable().unsigned()
      table.unique(['user_id', 'role_id'])
    })
  }

  async down() {
    this.schema.dropTable(this.tableName)
  }
}

```

### Run the migrations

```sh
node ace migration:run
```

::

## Set up models

Permissions provides two mixins that add role and permission management to your Lucid models.

### Apply `withPermissions` to the Role model

The `withPermissions` mixin teaches the Role model how to read and write the `permissions` JSON column. It adds methods like `givePermissions`, `syncPermissions`, and `revokePermissions` to role instances.

```ts [app/models/role.ts]
import { RoleSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withPermissions } from '@adonisplus/permissions'

export default class Role extends compose(
  RoleSchema,
  withPermissions() // [!code ++]
) {}

```

### Apply `withRoles` to the User model

The `withRoles` mixin connects users to roles through the pivot table. It adds methods like `assignRole`, `syncRoles`, and `hasRole` to user instances. You must tell the mixin which model represents roles and which table stores the assignments.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withRoles } from '@adonisplus/permissions'
import Role from '#models/role'

export default class User extends compose(
  UserSchema,
  // [!code ++:4]
  withRoles({
    roleModel: () => Role,
    pivotTable: 'user_roles',
  })
) {}

```

## Seed roles

Create the roles in a seeder, give them permissions, and assign one to a user. Use `permissions.getKey()` to reference permission keys with full type safety. `givePermissions` adds keys to a role. `syncPermissions` replaces the role's keys with the list you pass. `permissions.active()` returns every active key. The admin role keeps the keys that exist when the seeder runs. Sync it again after you add a permission.

```sh
node ace make:seeder role
```

```ts [database/seeders/role_seeder.ts]
import { BaseSeeder } from '@adonisjs/lucid/seeders'
import Role from '#models/role'
import User from '#models/user'
import { permissions } from '#start/permissions'

export default class extends BaseSeeder {
  async run() {
    const editor = await Role.create({ name: 'editor' })
    await editor.givePermissions([
      permissions.getKey('product.create'),
      permissions.getKey('product.update'),
    ])

    const admin = await Role.create({ name: 'admin' })
    await admin.syncPermissions(permissions.active())

    const user = await User.findOrFail(1)
    await user.assignRole(editor)
  }
}

```

```sh
node ace db:seed
```

A user can hold several roles. Their permissions are the union of the permissions of every role they hold.

## Register abilities with Bouncer

Permissions integrates with Bouncer by converting your permission definitions into Bouncer abilities. This lets you use the same `bouncer.authorize` API for both hand-written abilities and role-based permissions.

Open your Bouncer middleware and spread the generated abilities into the Bouncer constructor alongside your existing abilities.

```ts [app/middleware/initialize_bouncer_middleware.ts]
import * as abilities from '#abilities/main'
import { policies } from '#generated/policies'
import { permissions } from '#start/permissions' // [!code ++]

import { Bouncer } from '@adonisjs/bouncer'
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'

// [!code ++:4]
const allAbilities = {
  ...abilities,
  ...permissions.abilities(),
}

export default class InitializeBouncerMiddleware {
  async handle(ctx: HttpContext, next: NextFn) {
    ctx.bouncer = new Bouncer(
      () => ctx.auth.user || null,
      abilities, // [!code --]
      allAbilities, // [!code ++]
      policies
    ).setContainerResolver(ctx.containerResolver)

    if ('view' in ctx) {
      ctx.view.share(ctx.bouncer.edgeHelpers)
    }

    return next()
  }
}

declare module '@adonisjs/core/http' {
  export interface HttpContext {
    bouncer: Bouncer<
      Exclude<HttpContext['auth']['user'], undefined>,
      typeof abilities, // [!code --]
      typeof allAbilities, // [!code ++]
      typeof policies
    >
  }
}

```

The `permissions.abilities()` call is placed outside the middleware class so it runs once at import time, not on every request.

## Authorize in a controller

You can now protect controller actions using `bouncer.authorize`. Pass the permission key as a string, and Bouncer checks whether the logged-in user holds a role with that permission. If the check fails, Bouncer responds with a 403. With the seeded roles, an editor can create products and gets a 403 on delete. An admin can do both.

```ts [app/controllers/products_controller.ts]

import type { HttpContext } from '@adonisjs/core/http'

export default class ProductsController {
  async store({ bouncer }: HttpContext) {
    await bouncer.authorize('product.create')

    // User has permission, proceed
  }

  async destroy({ bouncer }: HttpContext) {
    await bouncer.authorize('product.delete')

    // User has permission, proceed
  }
}

```

You can also check a permission on the route, with the `authorize` middleware. See [Authorizing routes](/docs/packages/permissions/access#authorizing-routes).

## Next steps

::card-group
:::card{title="Defining permissions" to="/docs/packages/permissions/defining-permissions"}
Prefixes, aliases and inactive permissions.
:::

:::card{title="Managing roles" to="/docs/packages/permissions/managing-roles"}
Assign, sync and revoke roles.
:::

:::card{title="Managing permissions" to="/docs/packages/permissions/managing-permissions"}
Give permissions to a user without a role.
:::

:::card{title="Checking access" to="/docs/packages/permissions/access"}
Check permissions in code, and scope them to a token.
:::

:::card{title="Bouncer integration" to="/docs/packages/permissions/bouncer-integration"}
Authorize controllers and routes, and mix in your own abilities.
:::

:::card{title="Team permissions" to="/docs/packages/permissions/team-permissions"}
Give a user different roles in different teams.
:::
::
