> For the complete documentation index, see [llms.txt](https://docs.akinon.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.akinon.com/technical-guides/instore/permission-models.md).

# Permission Models

## <mark style="color:red;">1. Summary</mark>

Instore has two independent permission layers:

|                                    | Store screens                                                 | Management screens                                               |
| ---------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------- |
| **Who uses them?**                 | Store staff                                                   | Omnitron users                                                   |
| **Where are they opened?**         | The Instore app                                               | The Instore management pages inside Omnitron                     |
| **Login**                          | Email/password or OAuth (e.g. Azure)                          | Omnitron session                                                 |
| **Identity**                       | Instore session (token + `store_sessionid` cookie)            | Omnitron token                                                   |
| **Where are permissions defined?** | **Permission groups** in Instore                              | **FEPermission** groups in Omnitron                              |
| **Example screens**                | Orders, packages, transfers, stock, customer search, checkout | Store management, staff, permission groups, application settings |

When you get a 403, the first question is: **Which layer is the request going to?** A 403 on the store management screen is caused by something in Omnitron. A 403 on the package list is caused by the Instore permission groups or by the active store.

## <mark style="color:red;">2. Store Screens: Instore Permission Groups</mark>

### <mark style="color:red;">2.1 How it works</mark>

* Each staff member (`Staff`) belongs to one or more **permission groups** (`InstorePermissionGroup`).
* Each permission group holds a set of **permissions** (`InstorePermission`). Each permission stands for a single operation (e.g. "OMS Package List", "Order Cancel").
* When a request arrives, `BaseInstorePermission` checks whether the permission of the called endpoint is in one of the user's groups. If it is, the request passes. If not, it returns 403.
* Staff with `is_superuser` in Instore skip this check.

Matching is done on the permission record's `path` field:

| Endpoint type                                              | `path` looked up            | Example                     |
| ---------------------------------------------------------- | --------------------------- | --------------------------- |
| ViewSet action (`oms/`, `omnitron/`, `extension/`, orders) | `{action}-{view_name}`      | `packages-oms:oms-packages` |
| Proxy endpoints (`customers/`, `users/...`, registration)  | `{view_name}` + HTTP method | `customers` + `GET`         |

The permission list comes from `application_permissions.json` in the repository and is written to the database by migrations. You can find which `path` a screen maps to in this file.

### <mark style="color:red;">2.2 The default group</mark>

Setup creates a group called **General Permission Group** and adds almost every permission to it. New staff, whether created from the panel or on their first OAuth login, are put in this group unless another group is given.

The sensitive operations below are **not** added to the default group. Staff who need them must be given a separate group:

| Permission                              | Operation                            |
| --------------------------------------- | ------------------------------------ |
| Users Profile Retrieve / Partial Update | View / update a customer profile     |
| Users Reset Password                    | Reset a customer's password          |
| Users Reset Password With Phone         | Reset a customer's password by phone |

> The password reset endpoints also require the `ALLOW_SENSITIVE_USER_UPDATES` application setting to be on. If it is off, they return 403 even when the permission is granted.

### 2.3 Which screen needs which permission?

Permission names are the names shown on the permission group screen in Instore.

| Screen / operation                       | Required permission                                                                                                                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Order list and detail**                | Order List, Order Retrieve                                                                                                                                                                              |
| Accept / cancel / deliver an order       | Order Accept, Order Cancel, Order Deliver                                                                                                                                                               |
| Update order item status                 | Omnitron Order UpdateOrderItemStatus                                                                                                                                                                    |
| Order external statuses                  | Order External Status List                                                                                                                                                                              |
| **Package list and detail**              | OMS Package List, OMS Package Retrieve                                                                                                                                                                  |
| Package commands (prepare, ship, etc.)   | OMS Package Command                                                                                                                                                                                     |
| Package extra information field          | Update Extra Information Field                                                                                                                                                                          |
| Cargo companies, suppliers               | OMS CargoCompany List, OMS CargoCompany DefinedSuppliers List                                                                                                                                           |
| Package denial reasons, delivery ranges  | OMS PackageDenialReason List, OMS DeliveryRange List                                                                                                                                                    |
| Shipping label                           | OMS ShippingLabel Retrieve                                                                                                                                                                              |
| **Transfer orders**                      | OMS TransferOrder List, OMS TransferOrder Retrieve, OMS TransferOrder Command                                                                                                                           |
| **Stock and stock location screens**     | OMS StockLocations List, OMS StockLocation Dashboard (+ Transfer / Source / Destination variants)                                                                                                       |
| Product stock, multiple product query    | OMS Products Stocks, OMS Multiple Products Query                                                                                                                                                        |
| Stock search                             | Stock Search List, Stock Search Detail                                                                                                                                                                  |
| Blacklist                                | Blacklist List, Blacklist Detail                                                                                                                                                                        |
| Channels, states                         | OMS Channel List, OMS State List                                                                                                                                                                        |
| **Customer search**                      | Commerce User Search - Customers Get                                                                                                                                                                    |
| Customer detail                          | Omnitron User Detail - Customers Detail Get                                                                                                                                                             |
| Customer registration                    | Commerce Register Post                                                                                                                                                                                  |
| **Checkout-with-token (one-time token)** | Omnitron Generate One Time Token Post                                                                                                                                                                   |
| User schema                              | Omnitron-Shop User Schema - Schema Types Get                                                                                                                                                            |
| **In-store ordering (on-call)**          | Omnitron OnCall Order List / Detail / Complete                                                                                                                                                          |
| Pay later                                | Omnitron Pay Later                                                                                                                                                                                      |
| **Cancellation requests**                | Omnitron Cancellation Requests, Omnitron Reject Cancellation, Omnitron Cancellation Plan, CancellationReasons list, Bulk Cancellation Requests                                                          |
| **Trade-in**                             | Omnitron Tradable Items, Tradable Item Detail, Tradable Item Questions, Trade In Calculate Questions, Tradable Item Order Number, Confirm / Reject Tradable Item, Update Order Item Status For Trade In |
| Product attributes                       | Omnitron Attribute List, Omnitron AttributeDetailed Retrieve                                                                                                                                            |
| Application list                         | Application List                                                                                                                                                                                        |
| Extension screens                        | Dynamic Extension                                                                                                                                                                                       |

### <mark style="color:red;">2.4 Store assignment and the active store</mark>

Permissions answer the question "which operations can I perform?". The **active store** answers "whose data can I see?".

* The stores a staff member works at are kept on their record (`retail_stores`).
* When the app opens, it calls `GET /api/v1/auth/me/?current_store_remote_id=<store code>`. This call saves the selected store under the `current_store_remote_id` session key. The store code is the store's `remote_id` field and matches the `erp_code` value in OMS.
* The active store is also added as headers to requests sent to the backend systems (store id, `remote_id`, staff id and email). The header names come from the `STORE_*_HEADER_NAME` application settings.
* Later OMS requests are based on this store:
  * The package list returns only the active store's packages when no filter is given.
  * Package detail and package commands return **403** if the package's `stock_location.erp_code` is not the active store's `remote_id` (this check is skipped when the `pre_package_click_and_collect` UI setting is on).
  * Transfer detail and commands return **403** if the active store is neither the transfer's `source.erp_code` nor its `destination.erp_code`.
  * Transfer commands are limited by the store's role:

    | Role                        | Allowed commands                                                                                                                                                                      |
    | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | Source (`source`)           | `READY_TO_SHIP_TRANSFER_ORDER`, `READY_TO_SHIP_TRANSFER_ORDER_ADVANCE`, `IN_TRANSIT_TRANSFER_ORDER`, `TRANSFER_OUT_OF_STOCK`, `SHIP_SELECTED_TRANSFER_ORDERS`, `RENEW_TRANSFER_ORDER` |
    | Destination (`destination`) | `TRANSFER_ORDER_TRANSFERRED`                                                                                                                                                          |

    The `commands` field in the transfer list is filtered by this rule. Sending a `transition` that is not in the filtered list returns **403**.

These 403s have nothing to do with permission groups. The user has every permission they need, but the record belongs to another store.

## <mark style="color:red;">3. Management Screens: Omnitron FE Permission</mark>

### <mark style="color:red;">3.1 How it works</mark>

The Instore management screens opened from Omnitron work with an Omnitron token. These ViewSets use `OmnitronAuthentication` and `OmnitronFEPermission`. On every request, Instore:

1. Sends the token to Omnitron's active user endpoint and identifies the user. The token is not cached; Omnitron is asked again on every request.
2. Lets the request through if the user is a **superuser** in Omnitron.
3. Otherwise, works out the required permission. It then reads the user's FEPermissions from Omnitron (`detailed_list`) and looks for the permission among the records whose `is_visible_for_user` is `true`.

The required permission has three parts:

```
{OMNITRON_APPLICATION_ID}|{ACTION}|{resource}
example: 12|UPDATE|omnistore_api:retail_stores
```

The resource comes from the router's `basename`, not from the URL. So every route of a resource (`staffs-list`, `staffs-detail`, `staffs-duplicate-email-staffs`) maps to the same record. The action comes from the request's HTTP method:

| HTTP method        | Action |
| ------------------ | ------ |
| GET, HEAD, OPTIONS | READ   |
| POST               | WRITE  |
| PUT, PATCH         | UPDATE |
| DELETE             | DELETE |

### <mark style="color:red;">3.2 Resources</mark>

Omnitron holds 4 records for each resource: `READ`, `WRITE`, `UPDATE` and `DELETE`. They are granted to users from the group screen in Omnitron.

| Name in Omnitron                             | Resource                             | Screen                      |
| -------------------------------------------- | ------------------------------------ | --------------------------- |
| Instore Retail Store                         | `omnistore_api:retail_stores`        | Store management            |
| Instore Staff                                | `omnistore_api:staffs`               | Staff management            |
| Instore Permission Group                     | `omnistore_api:permission-groups`    | Permission group management |
| Instore Permission                           | `omnistore_api:permissions`          | Permission list             |
| Instore Application Setting                  | `omnistore_api:application-settings` | Application settings        |
| Instore UI Setting                           | `omnistore_api:ui-settings`          | UI settings                 |
| Instore OAuth Provider                       | `omnistore_api:oauth`                | OAuth providers             |
| Instore Audit Log                            | `omnistore_api:audit-logs`           | Audit logs                  |
| Instore Address                              | `omnistore_api:address`              | Addresses                   |
| Instore Country / City / Township / District | `omnistore_api:country` …            | Address definitions         |
| Instore Set Omnitron Id                      | `omnistore_api:set-omnitron-id`      | Omnitron ID matching        |

### <mark style="color:red;">3.3 Store management in detail</mark>

| Operation                | Endpoint                                        | Required permission             |
| ------------------------ | ----------------------------------------------- | ------------------------------- |
| Store list, store detail | `GET retail_stores/`, `GET retail_stores/{id}/` | None (public)                   |
| Create a store           | `POST retail_stores/`                           | Instore Retail Store **WRITE**  |
| Update a store           | `PUT/PATCH retail_stores/{id}/`                 | Instore Retail Store **UPDATE** |
| Delete a store           | `DELETE retail_stores/{id}/`                    | Instore Retail Store **DELETE** |
| Change store password    | `POST retail_stores/change_password/`           | Instore Retail Store **WRITE**  |
| Fill Omnitron IDs        | `POST retail_stores/fill_omnitron_ids/`         | Instore Retail Store **WRITE**  |
| Store login (staff list) | `POST retail_stores/login/`                     | None                            |

Because the list and detail are public, the screen opens. Saving or deleting can still return `403`. In that case the user's Omnitron group is missing the matching action for **Instore Retail Store**. Changing the password is also a `POST`, so it needs the same **`WRITE`** permission as creating a store.

### <mark style="color:red;">3.4 Prerequisites</mark>

This check needs two setup steps:

* The **`OMNITRON_APPLICATION_ID`** application setting must be filled. If it is empty, the required permission cannot be worked out and everyone except superusers gets 403.
* The **FEPermission setup** must have run (`POST api/setup/fe_permissions/execute/` or the general setup flow). If it has not, there are no records in Omnitron to grant, and again everyone gets 403.

## <mark style="color:red;">4. Token Scope</mark>

When staff log in with `POST /api/v1/auth/login/`, they get two things: an Instore token and the `store_sessionid` session cookie. The active store is kept in this session as well.

Each identity only works in its own layer. A request with the wrong token usually returns `403`, not `401`. Instore does not recognise the token and treats the request as anonymous. Since these authentication classes do not define a `WWW-Authenticate` header, DRF rejects the anonymous request with `403` instead of `401`.

| Endpoint group                                                                                | Instore session           | Omnitron token             |
| --------------------------------------------------------------------------------------------- | ------------------------- | -------------------------- |
| Store screens (`oms/`, `omnitron/`, `extension/`, orders)                                     | ✅                         | —                          |
| Endpoints that go to commerce (`customers/`, `users/...`, one-time-token)                     | ✅ session cookie required | —                          |
| Management screens (`retail_stores`, `staffs`, `permission_groups`, `application_settings` …) | ❌ 403                     | ✅                          |
| Setup endpoints (`api/setup/...`)                                                             | ❌                         | ✅ Omnitron superusers only |

The endpoints that go to commerce are not DRF views but reverse proxies (`revproxy`), and they pass the request on to commerce as it is. On these endpoints the user is identified by the **session cookie** through Django's session middleware, not by the `Authorization` header. If the cookie is missing or the session has expired (2 weeks by default), they return `403` with the plain text `Authentication required`.

If the Omnitron token has expired, has been revoked, or Omnitron cannot be reached, the user is not recognised and the management endpoints also return `403`.

## <mark style="color:red;">5. The Checkout-With-Token Flow</mark>

Staff generate a one-time token to log a customer in on the commerce site and move on to checkout on their behalf.

```
Instore FE ──POST /api/v1/customers/{customer_id}/one-time-token/──▶ Instore
Instore ──(admin token + store headers)──▶ Commerce: passwordless-login
Commerce ──200 { redirect_url }──▶ Instore
Instore ──200 { redirect_url?secret_key=...&user={customer_id} }──▶ Instore FE
Instore FE ──redirect──▶ Commerce site (customer session opens)
```

**Step by step:**

1. **SMS verification (optional).** If the `VERIFY_LOGIN` setting is on, the flow has two steps. The first call sends a code to the customer's phone and returns `202` with `expire_date`. The second call sends the code with `?verify=true`. A wrong code returns `400`. The code is cached under a hash of the phone number and becomes invalid when it expires.
2. **Token generation.** Instore adds a random 16-character `secret_key` and `user` (the customer id) to the request body. It forwards the request to commerce's `UPSTREAM_PASSWORDLESS_LOGIN` endpoint (`api/v1/passwordless-login/` by default) together with the active store headers.
3. **Permission.** `UPSTREAM_ADMIN_TOKEN` is only sent to commerce if the staff member has the **Omnitron Generate One Time Token Post** permission. Without it, the request goes without the admin token, and the 401/403 that commerce returns is passed back to the staff member as it is.
4. **Admin token refresh.** If commerce rejects the admin token with 401/403, Instore refreshes `UPSTREAM_ADMIN_TOKEN` once and retries the request. If the refresh fails, commerce's first response is returned.
5. **Redirect.** If commerce returns `200`, Instore appends the `secret_key` and `user` parameters to `redirect_url`. The app then redirects to this address.

Everything **after** the redirect (validating the token, logging the customer in, moving to the basket and checkout) happens on the commerce side. If something fails after the redirect, look into the commerce backend. Instore's part ends once it has produced the correct `redirect_url`.

## <mark style="color:red;">6. I Got a 403: Where Does It Come From?</mark>

### <mark style="color:red;">6.1 Look at the response body</mark>

The shape of the response tells you most of what you need about the source:

| Response                                                                                          | Source                                                                    | What to do                                                                                                                                       |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `{"error": {"detail": "Authentication credentials were not provided."}, "status_code": 403}`      | Token not recognised                                                      | Check that you use the right token and that it has not expired (Section 4)                                                                       |
| `{"error": {"detail": "You do not have permission to perform this action."}, "status_code": 403}` | Instore permission check (permission group or FEPermission)               | Follow the checklist in Section 6.2                                                                                                              |
| `{"status": 403, "error": {"detail": "You do not have permission to perform this action"}}`       | Instore permission group (customer profile, password reset, registration) | Check the permission and the `ALLOW_SENSITIVE_USER_UPDATES` setting                                                                              |
| Plain text `Authentication required`                                                              | Session cookie missing or expired                                         | Log in again                                                                                                                                     |
| 403 with an **empty body**                                                                        | Active store check (package / transfer)                                   | Check that the record belongs to the active store (Section 2.4)                                                                                  |
| `{"error": {"detail": "<some other message>"}, "status_code": 403}`                               | A backend system (OMS, Omnitron or commerce)                              | A 4xx from a backend system is returned as `InstoreProxyError` with the same status code. The message comes from that system; look into it there |
| Commerce's own error format                                                                       | Commerce (customer search, token generation)                              | Check whether the staff member has the matching permission (Section 5, step 3)                                                                   |

### <mark style="color:red;">6.2 Checklist</mark>

**403 on a store screen:**

1. Is the staff member logged in to Instore, and is the session still valid? The Omnitron token does not work here.
2. Do the staff member's permission groups include this screen's permission? (Section 2.3)
3. Is it a sensitive operation (profile, password reset)? These are not in the default group.
4. If the body is empty: is the active store right? Does the `current_store_remote_id` sent to `auth/me` match the record's store?
5. If it is a transfer command: is the store the source or the destination of this transfer? Is the command allowed for that role?

**403 on a management screen:**

1. Is the request sent with an Omnitron token? The Instore token does not work here.
2. Is the user a superuser in Omnitron? If so, this is not a permission problem. Check that the token is valid.
3. Does the user's Omnitron group include the resource and the action? E.g. saving a store needs **Instore Retail Store UPDATE**. (Sections 3.2 and 3.3)
4. If everyone gets 403: is `OMNITRON_APPLICATION_ID` filled? Has the FEPermission setup been run? (Section 3.4)
5. Can Omnitron be reached? If it cannot, the user is not recognised and the request is rejected with 403.

For 403s on management screens, the Instore log lines starting with `[FE PERMISSION]` tell you the cause directly:

| Log line                                       | Meaning                                                                                                          |
| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `user <id> is not allowed to <namespace_path>` | The user lacks this resource and action. Add the `namespace_path` from the line to the user's group in Omnitron. |
| `has no Omnitron identity`                     | No Omnitron user could be taken from the token. Check the token.                                                 |
| `Cannot map ... to a namespace_path`           | The required permission could not be worked out. Most often `OMNITRON_APPLICATION_ID` is empty.                  |
| `Failed to retrieve permissions`               | Permissions could not be read from Omnitron (connection or Omnitron error).                                      |

## <mark style="color:red;">7. I Got a 500: Is It a Permission Problem?</mark>

**A** `500` **never means a missing permission.** A missing permission always comes back as `403` (or as a 401/403 from a backend system). If you get a 500, the cause is one of the following:

| Case                                                                  | How to recognise it                                                                                                                                                                                                                          |
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **A backend system returned 5xx** (OMS, Omnitron, commerce)           | The same request sent to that system directly also returns 5xx. Instore's logs show an `HTTPError` with a `<code> Server Error: ... for url:` line.                                                                                          |
| **A backend system could not be reached** (connection error, timeout) | The logs show `ConnectionError` or `ConnectTimeout`. Check the `UPSTREAM`, `UPSTREAM_OMS` and `UPSTREAM_OMNITRON` settings.                                                                                                                  |
| **The store in the session no longer exists**                         | The `current_store_remote_id` in the session cannot be found in Instore (the store was deleted, or its `remote_id` changed). The logs show `RetailStore.DoesNotExist`. Logging out, logging in again and selecting the store again fixes it. |
| **No active store selected**                                          | If OMS screens (packages, transfers) are opened before `auth/me` is called, the logs show `'NoneType' object has no attribute 'remote_id'`.                                                                                                  |
| **Missing UI setting**                                                | If the `pre_package_click_and_collect` UI setting is not defined, package detail and package commands fail and the logs show `'NoneType' object has no attribute 'value'`.                                                                   |

**For a quick split:**

* `403` → permission, token or active store. See Section 6.
* `401`/`403` with a body in commerce's format → commerce rejected the request. Most often the staff member lacks the matching permission and the request went without the admin token.
* `500` → not a permission problem. See the table in this section and check the backend systems.

## <mark style="color:red;">8. Common Scenarios</mark>

**The store management screen opens, but saving returns** `403`**.** The list and detail are public, so the screen opens. Saving is a `PUT`/`PATCH` request and needs **Instore Retail Store** `UPDATE` in Omnitron. A new store needs `WRITE`, and deleting needs `DELETE`. The permission is granted from the group screen in Omnitron, not from the Instore permission groups.

**After the checkout-with-token redirect, the customer is not logged in.** If Instore returned the `redirect_url` (200), the Instore side has finished successfully. Look at how commerce validates the `secret_key` and `user` parameters in the address. If token generation returns `401`/`403`, check that the staff member has the **Omnitron Generate One Time Token Post** permission.

**Customer search returns** `500`**.** This is not a permission problem. With a missing permission, commerce returns `401`/`403`. For a `500`, first check what commerce's `user_search` endpoint returns for the same query. If commerce is healthy, check that the store in the session still exists (Section 7).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.akinon.com/technical-guides/instore/permission-models.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
