# Checking access

This guide covers the `Access` class for checking permissions at runtime. You will learn how to:

- Create an Access instance from a user or raw permission keys
- Check whether a permission is allowed or denied
- Scope permissions for API tokens

## Overview

The `Access` class represents the resolved set of permissions for a specific user in a specific context. It takes raw permission strings (from the database), resolves aliases, removes inactive and unknown keys, and provides `allows` and `denies` methods for checking access.

You do not create `Access` instances directly. Instead, use the `createAccess` or `createAccessFor` methods on your `Permissions` instance.

## Creating an Access instance

### From a user

The most common approach is `createAccessFor`, which loads the user's permissions (from roles and direct assignments) and resolves them in one step.

```ts
import { permissions } from '#start/permissions'

const access = await permissions.createAccessFor(user)
access.allows('product.create') // true or false
```

The user must implement a `getPermissions()` method that returns a `Promise<string[]>`. Both the `withRoles` and `withPermissions` mixins provide this method.

> [!WARNING]
> `createAccessFor` keeps the `Access` on the model instance and returns it on every later call. After you change a user's roles or permissions, fetch the user again (`await User.findOrFail(user.id)`) before you check access.

### From raw keys

For lower-level control, create an empty `Access` instance and populate it manually.

```ts
const rawAccess = permissions.createAccess()
rawAccess.use(['product.create', 'product.update', 'product.remove'])
```

The `use` method resolves aliases and filters out inactive and unknown keys before adding them to the resolved set.

## Checking permissions

```ts
access.allows('product.create') // true
access.denies('billing.refund') // true
```

Both methods accept a permission key and return a boolean. Keys are type-safe and will be autocompleted by your editor.

## Listing permissions

Use the `permissions` method to get all resolved permission keys.

```ts
access.permissions()
// ['product.create', 'product.update', 'product.delete']
```

## Token scoping

When issuing API tokens, you may want to limit the token's capabilities to a subset of the user's permissions. The `scopeTo` method intersects the resolved permissions with the provided abilities, keeping only permissions present in both.

```ts
const scopedAccess = await permissions.createAccessFor(user)

// User has: product.create, product.update, product.delete, billing.refund
// Token allows: product.create, product.update

scopedAccess.scopeTo(['product.create', 'product.update'])

scopedAccess.allows('product.create') // true
scopedAccess.allows('product.delete') // false (not in token scope)
scopedAccess.allows('billing.refund') // false (not in token scope)
```

A token with `*` keeps the full set of the user's active permissions. It does not grant a permission that the user lacks. A scoped `Access` stays narrowed on that model instance for the rest of the request.

`scopeTo` resolves the aliases in the token's list and drops inactive and unknown keys.

## Authorizing routes

The `authorize` middleware checks a permission before the route's controller runs. Pass one key, or an array of keys to let in users who hold any of them. A guest, or a user without the permission, gets a 403.

```ts [start/routes.ts]
import router from '@adonisjs/core/services/router'
import { middleware } from '#start/kernel'
import { controllers } from '#generated/controllers'

router
  .delete('/products/:id', [controllers.Products, 'destroy'])
  .use(middleware.authorize('product.delete'))

router
  .put('/products/:id', [controllers.Products, 'update'])
  .use(middleware.authorize(['product.update', 'product.delete']))
```

To change the error, override `createAccessDeniedResponse` in `app/middleware/authorize_middleware.ts`.

```ts [app/middleware/custom_authorize_middleware.ts]
import AuthorizeMiddleware from '#middleware/authorize_middleware'
import { AuthorizationResponse } from '@adonisjs/bouncer'

export default class CustomAuthorizeMiddleware extends AuthorizeMiddleware {
  protected createAccessDeniedResponse() {
    return AuthorizationResponse.deny('You cannot do this', 403)
  }
}

```

### With access tokens

When your app signs users in with access tokens, scope the `Access` by the token in `app/middleware/authorize_middleware.ts`. Add the check after `createAccessFor(user)` in the generated middleware.

```ts [app/middleware/authorize_middleware.ts]
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import { AuthorizationResponse, errors } from '@adonisjs/bouncer'
import { permissions, type PermissionKey } from '#start/permissions'

export default class AuthorizeMiddleware {
    protected createAccessDeniedResponse() {
    return AuthorizationResponse.deny('Access denied', 403)
  }

    async handle(ctx: HttpContext, next: NextFn, ability: PermissionKey | PermissionKey[]) {
    const user = ctx.auth.user
    if (!user) {
      throw new errors.E_AUTHORIZATION_FAILURE(this.createAccessDeniedResponse())
    }

        const access = await permissions.createAccessFor(user)
    if (user.currentAccessToken) { // [!code ++]
      access.scopeTo(user.currentAccessToken.abilities) // [!code ++]
    } // [!code ++]
    const allowed = Array.isArray(ability)
      ? ability.some((a) => access.allows(a))
      : access.allows(ability)

    if (!allowed) {
      throw new errors.E_AUTHORIZATION_FAILURE(this.createAccessDeniedResponse())
    }
    return next()
  }
}

```

The `Access` is stored on the user. Bouncer and every later check of the request see the token's set. Your User model declares `currentAccessToken?: AccessToken`, with `AccessToken` imported from `@adonisjs/auth/access_tokens`, as the API starter kit does.

Give each token the abilities it needs.

```ts [app/controllers/tokens_controller.ts]
const token = await User.accessTokens.create(user, [permissions.getKey('product.create')])
```

## Reference

::::field-group

:::field{name="use" type="(rawKeys: string[]) => void"}
Resolves aliases, drops inactive and unknown keys, and adds the rest. You can call it more than once.
:::

:::field{name="allows" type="(key: PermissionKey) => boolean"}
Returns `true` when the key is in the set.
:::

:::field{name="denies" type="(key: PermissionKey) => boolean"}
Returns `true` when the key is not in the set.
:::

:::field{name="scopeTo" type="(abilities: string[]) => void"}
Keeps only the keys that are also in `abilities`. A list with `*` leaves the set unchanged.
:::

:::field{name="permissions" type="() => PermissionKey[]"}
Returns the keys in the set.
:::

::::
