No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
MVC-L: controllers, models, templates

OpenCart Module Access Permissions: How user_group and the Controller Check Access

How user_group Permissions Work in OpenCart 3.0 and 4.1: access and modify, the hasPermission() Method, Module Routes, and Causes of the "No Access" Error.

10 min read OC 3.0 OC 4.1

The module's access rights in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → are set by the user group (user_group). For each group, the JSON stores two lists of routes: access allows opening a page, and modify allows changing something on it. The core performs the access check before the controllerCode that receives a request and prepares data. More in the glossary → runs. However, the module developer must check modify themselves, by calling $this->user->hasPermission() in every method that writes data.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

Where are the permissions stored and how do they get into $this->user?

In the oc_user table, each administrator has a user_group_id field. In the oc_user_group table, the permission field contains JSON that looks like this: {"access":["catalog/product",…],"modify":["catalog/product",…]}. There are no separate permissions for a specific user. Permissions always belong to a group, so to give a manager fewer capabilities, you create a separate group.

The $this->user object exists only in the admin (for the difference between the two applications, see the article about admin and catalog). It is an instance of the Cart\User class (3.0) or Opencart\System\Library\Cart\User (4.1), which the core places in the registry (more in the material how objects get into the controller through the Registry). On every request, the constructor takes user_id from the session, checks that the user is active, and reads the permissions of their group:

system/library/cart/user.php · OpenCart 4.1.0.4 · lines 68–76

$user_group_query = $this->db->query("SELECT `permission` FROM `" . DB_PREFIX . "user_group` WHERE `user_group_id` = '" . (int)$user_query->row['user_group_id'] . "'");

$permissions = json_decode($user_group_query->row['permission'], true);

if (is_array($permissions)) {
	foreach ($permissions as $key => $value) {
		$this->permission[$key] = $value;
	}
}

In 3.0, this code is almost the same. The practical conclusion is that permissions are re-read from the database on every request. After you change a group's permissions, the user does not need to log out and log back in; refreshing the page is enough. If the user is disabled (status = 0), the constructor calls logout(), and the next request redirects them to the login form.

How does hasPermission() work, and why does the exact route string matter?

The entire check comes down to a single in_array:

system/library/cart/user.php · OpenCart 3.0.5.1 · lines 75–81

public function hasPermission($key, $value) {
	if (isset($this->permission[$key])) {
		return in_array($value, $this->permission[$key]);
	} else {
		return false;
	}
}

The first argument is the type of permission ('access' or 'modify'), and the second is the controller route without the method. There are no masks, hierarchies, or "an admin who can do everything" here. The "Administrator" group has full access only because its JSON lists all routes. If you manually copied a new file into admin/controller, the administrator will not see its page until someone checks the box for it.

The comparison is exact, with no masks or hierarchy. in_array() is called without strict, but for route strings any difference in characters produces false. The table below shows typical module route formats:

WhatOpenCart 3.0OpenCart 4.1
Controller fileadmin/controller/extension/module/my_module.phpextension/my_ext/admin/controller/module/my_module.php
String in permissionextension/module/my_moduleextension/my_ext/module/my_module
Method route in the URLextension/module/my_module/saveextension/my_ext/module/my_module.save

The method is never included in the permission string. hasPermission('modify', 'extension/module/my_module/save') will always return false. How the core parses route= into a controller and a method is explained in the article about route= routing in 3.0 and 4.1.

Who checks access: the core or your controller?

The check of access is performed by the core. In the admin, startup actions (pre-actions) run before the main controller, including startup/login and startup/permission. The first action checks that the user is logged in and that the user_token in the request matches the session one (details in the material user_token: links, AJAX, and security). The second action takes route, normalizes it, and calls hasPermission('access', …). If false is returned, error/permission runs instead of your controller, and the user sees the "No Permission" page.

flowchart TD
  A["Request admin/index.php?route=..."] --> B["startup/login: session and user_token"]
  B -->|"not logged in"| L["common/login"]
  B --> C["startup/permission: hasPermission access"]
  C -->|"false"| E["error/permission"]
  C -->|"true"| D["Method of your controller"]
  D --> F{"Does the method change data?"}
  F -->|"yes"| G["hasPermission modify in validate/save"]
  F -->|"no"| H["Render page"]
  G -->|"false"| W["error_permission in response"]
  G -->|"true"| S["Write to DB"]

Route normalization differs between these versions, and this is where some of the "mysterious" denials come from.

  • OpenCart 3.0: the first two segments of the path are taken (catalog/product/edit becomes catalog/product). The third segment is added only when the first two belong to one of the extension types (extension/module, extension/payment, etc.). Because of this, a controller in a non-standard folder, for example extension/mytool/report, will be checked as extension/mytool, and there is no such permission in the list. Place your module's controllers in the standard type folders.
  • OpenCart 4.1: the part of the route after the method separator is cut off, and the full controller path is checked, including the extension code.

Both versions have their own lists of ignored routes (login, logout, header, footer, error pages) that do not require permission. Your module does not get into these lists.

How do you correctly check modify in your own module?

The core does not know which of your methods only display data and which change it. Therefore, modify must be checked in the controller itself. Use the core controllers as a reference. Here is how it is done on the user groups page:

admin/controller/user/user_permission.php · OpenCart 3.0.5.1 · lines 380–390

protected function validateForm() {
	if (!$this->user->hasPermission('modify', 'user/user_permission')) {
		$this->error['warning'] = $this->language->get('error_permission');
	}

	if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 64)) {
		$this->error['name'] = $this->language->get('error_name');
	}

	return !$this->error;
}

In 4.1, forms are saved via AJAX, so the error is returned in JSON:

admin/controller/user/user_permission.php · OpenCart 4.1.0.4 · lines 338–340

if (!$this->user->hasPermission('modify', 'user/user_permission')) {
	$json['error']['warning'] = $this->language->get('error_permission');
}

Template for your own module

OpenCart 3.0 (own example):

protected function validate() {
	if (!$this->user->hasPermission('modify', 'extension/module/my_module')) {
		$this->error['warning'] = $this->language->get('error_permission');
	}

	return !$this->error;
}

OpenCart 4.1 (own example):

public function save(): void {
	$this->load->language('extension/my_ext/module/my_module');

	$json = [];

	if (!$this->user->hasPermission('modify', 'extension/my_ext/module/my_module')) {
		$json['error']['warning'] = $this->language->get('error_permission');
	}

	if (!$json) {
		// запис налаштувань
		$json['success'] = $this->language->get('text_success');
	}

	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
}

The error_permission key must exist in your language fileA PHP file with interface texts, separate for each language. More in the glossary →. How to organize it is described in the article about language files and module translation. The general structure of JSON responses is covered in the material about controllers: data, template, and child controllers.

Where does the list of checkboxes come from, and what happens when a module is installed?

The group form does not read any permission registry. It simply scans the file system. In 3.0, the controller recursively walks admin/controller, converts file paths into routes, and filters out service files:

admin/controller/user/user_permission.php · OpenCart 3.0.5.1 · lines 347–355

foreach ($files as $file) {
	$controller = substr($file, strlen(DIR_APPLICATION . 'controller/'));

	$permission = substr($controller, 0, strrpos($controller, '.'));

	if (!in_array($permission, $ignore)) {
		$data['permissions'][] = $permission;
	}
}

In 4.1, a separate pass over the extension/ directory is added, because extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → live outside admin/controller:

admin/controller/user/user_permission.php · OpenCart 4.1.0.4 · lines 298–305

// Extension permissions
$results = oc_glob(DIR_EXTENSION . '*/admin/controller/{,*/,*/*/,*/*/*/}*.php');

foreach ($results as $result) {
	$path = substr($result, strlen(DIR_EXTENSION));

	$data['extensions'][] = 'extension/' . str_replace('admin/controller/', '', substr($path, 0, strrpos($path, '.')));
}

This shows how the extension/my_ext/module/my_module string is formed: admin/controller/ is cut off, and the extension/ prefix is added. The map of these directories is shown in the article about OpenCart file structure.

When, in "Extensions → Extensions", you select "Modules" in the list of types and click "Install", the core adds the module's route to the access and modify of the current user's group. Other groups receive nothing, so permissions for managers must be granted manually. When uninstalling in 3.0, the module's routes are removed from access and modify of all groups. In 4.1, permissions are not revoked, and the rows remain in the groups' JSON.

Extensions → Modules: the «Install» button adds module permissions only to the current user's group
Extensions → Modules: the «Install» button adds module permissions only to the current user's group · OpenCart 4.1.0.4

If your module has several controllers (for example, a separate report page or an AJAX endpoint in another file), only the main route is added automatically. You will have to either tick the rest manually in the group or add them programmatically in the module's install() method via the user/user_group model (working with models is described in the article about database queries via $this->db).

How do you grant permissions to a manager in the admin and verify the result?

  1. Open "System → Users → User Groups".
  2. Create a new group with the "Add New" button, for example "Content Manager", or open an existing one with the "Edit" button.
  3. In the "Access Permission" block, tick the routes the person should see. In the "Modify Permission" block, tick those where they can save changes. In 4.1, extension routes are placed in separate lists.
  4. Click "Save".
  5. In "System → Users → Users", assign this group to the required account.
  6. Open the admin in another browser under this user and go through the module's pages, making sure to try saving changes.
System → Users → User Groups: the «Access» and «Modify» lists with controller routes
System → Users → User Groups: the «Access» and «Modify» lists with controller routes · OpenCart 4.1.0.4

For diagnostics, it is useful to look at what is actually stored in the database:

SELECT user_group_id, name, permission
FROM oc_user_group
WHERE user_group_id = 1;

Look in the JSON for the exact route string. If it is missing but the page opens, the route is being ignored or normalized differently than you think. Edit the JSON by hand in phpMyAdminA web interface to the database. Make a dump before any changes. More in the glossary → only if you have a backup. One extra comma will make json_decode invalid, and the group will lose all its permissions, including access to the groups page.

Common permission mistakes in modules

  • A method in the permission string. hasPermission('modify', 'extension/module/x/save') will never work. Pass only the controller path.
  • A 3.0-style string in a module for 4.1. When porting, developers often forget the extension code: extension/module/x instead of extension/my_ext/module/x.
  • Checking only in the template. Hiding the "Save" button without a server-side check protects nothing, because the request can be sent manually.
  • A non-standard folder in 3.0. Because the route is trimmed to two segments, a controller in a nested folder is checked against a different string than the one you see in the checkbox list.
  • The module was copied as files instead of installed. Permissions were not added, and the administrator sees error/permission. Reinstall the module or tick the route in the group.
  • One shared administrator account for everyone. Then permissions do not work as a separation mechanism at all. Broader recommendations are collected in the article about OpenCart admin security.

You can read more about the structure of controllers, models, and templates in the section MVC-L: controllers, models, templates.

Summary

  • Permissions belong to the group, not the user. They are stored as JSON with lists of access and modify in oc_user_group.permission and are re-read from the database on every request.
  • hasPermission() works like a plain in_array: the route string must match character for character and must not contain a method.
  • access is checked by the core at the startup/permission stage. The modify check is your responsibility, in every method that changes data.
  • In 4.1, the module route contains the extension code, and the group form shows extensions in a separate list.
  • Installing a module grants permissions only to the group of the person who installed it. Other groups must be given permissions manually.

Next step: go through all public methods of your module and make sure that every method that writes to the database starts with a modify check. Then test the module under an account with a restricted group.

FAQ

Can I give a user permission for only one controller action, such as editing without deleting?
Not with standard tools. Permissions are set at the controller level, not the method level. If you need that separation, move deletion into a separate controller with its own route, or add an extra check to your code.
Why are there new pages after updating OpenCart that the administrator cannot access?
New core controllers are not added automatically to the JSON of existing groups. Open the Administrator group, tick the new routes in both lists, and save.
Is $this->user available in the storefront?
No, the admin user object and its permissions are used only in the admin application. The storefront uses a separate customer object with different logic.
How do I check permissions in an admin Twig template?
You can't directly: the template has no access to $this->user. Calculate a flag in the controller using hasPermission() and pass it into $data, and still check the permission on the server when saving.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.