Giter Club home page Giter Club logo

cakephp-3-acl-example's Introduction

cakephp-3-acl-example

A very simple CakePHP 3 ACL plugin usage example. This example is based on Simple Acl controlled Application for CakePHP 2. The differences are described in this document. The files in this repository contain the changes and implementations of functions discuessed below.

Getting started

  • Assuming you are using composer, get a copy of the latest cakephp release by running composer create-project --prefer-dist cakephp/app acl-example. This will create an empty CakePHP project in the acl-example directory. Answer YES when asked if folder permissions should be set.
  • Navigate to the CakePHP project directory (acl-example in this case) cd acl-example
  • Install the CakePHP ACL plugin by running composer require cakephp/acl
  • Include the ACL plugin in app/config/bootstrap.php
Plugin::load('Acl', ['bootstrap' => true]);

###Example schema An example schema taken from the CakePHP 2 ACL tutorial:

CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL UNIQUE,
    password CHAR(60) NOT NULL,
    group_id INT(11) NOT NULL,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE groups (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE posts (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    user_id INT(11) NOT NULL,
    title VARCHAR(255) NOT NULL,
    body TEXT,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE widgets (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    part_no VARCHAR(12),
    quantity INT(11)
);

After the schema is created, proceed to "bake" the application.

bin/cake bake all groups
bin/cake bake all users
bin/cake bake all posts
bin/cake bake all widgets

Preparing to Add Auth

Add UsersController::login function

public function login() {
	if ($this->request->is('post')) {
		$user = $this->Auth->identify();
		if ($user) {
			$this->Auth->setUser($user);
			return $this->redirect($this->Auth->redirectUrl());
		}
		$this->Flash->error(__('Your username or password was incorrect.'));
	}
}

Add UsersController::logout function

public function logout() {
	$this->Flash->success(__('Good-Bye'));
	$this->redirect($this->Auth->logout());
}

Add src/Templates/Users/login.ctp

<?= $this->Form->create() ?>
<fieldset>
	<legend><?= __('Login') ?></legend>
	<?= $this->Form->input('username') ?>
	<?= $this->Form->input('password') ?>
	<?= $this->Form->submit(__('Login')) ?>
</fieldset>
<?= $this->Form->end() ?>

Modify UsersTable::beforeSave to hash the password before saving

use Cake\Auth\DefaultPasswordHasher;
...
public function beforeSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, 
	\ArrayObject $options)
{
	$hasher = new DefaultPasswordHasher;
	$entity->password = $hasher->hash($entity->password);
	return true;
}

Include and configure the AuthComponent and the AclComponent in the AppController

public $components = [
	'Acl' => [
		'className' => 'Acl.Acl'
	]
];
...
$this->loadComponent('Auth', [
	'authorize' => [
		'Acl.Actions' => ['actionPath' => 'controllers/']
	],
	'loginAction' => [
		'plugin' => false,
		'controller' => 'Users',
		'action' => 'login'
	],
	'loginRedirect' => [
		'plugin' => false,
		'controller' => 'Posts',
		'action' => 'index'
	],
	'logoutRedirect' => [
		'plugin' => false,
		'controller' => 'Users',
		'action' => 'login'
	],
	'unauthorizedRedirect' => [
		'controller' => 'Users',
		'action' => 'login',
		'prefix' => false
	],
	'authError' => 'You are not authorized to access that location.',
	'flash' => [
		'element' => 'error'
	]
]);

Add Temporary Auth Overrides

Temporarily allow access to UsersController and GroupsController so groups and users can be added. Add the following implementation of beforeFilter to src/Controllers/UsersController.php and src/Controllers/GroupsController.php:

public function initialize()
{
	parent::initialize();
	
	$this->Auth->allow();
}

Initialize the Db Acl tables

  • Create the ACL related tables by running bin/cake Migrations.migrations migrate -p Acl

Model Setup

Acting as a requester

  • Add the requester behavior to GroupsTable and UsersTable
  • Add $this->addBehavior('Acl.Acl', ['type' => 'requester']); to the initialize function in the files src/Model/Table/UsersTable.php and src/Model/Table/GroupsTable.php

Implement parentNode function in Group entity

Add the following implementation of parentNode to the file src/Model/Entity/Group.php:

public function parentNode()
{
	return null;
}

Implement parentNode function in User entity

Add the following implementation of parentNode to the file src/Model/Entity/User.php:

public function parentNode()
{
	if (!$this->id) {
		return null;
	}
	if (isset($this->group_id)) {
		$groupId = $this->group_id;
	} else {
		$Users = TableRegistry::get('Users');
		$user = $Users->find('all', ['fields' => ['group_id']])->where(['id' => $this->id])->first();
		$groupId = $user->group_id;
	}
	if (!$groupId) {
		return null;
	}
	return ['Groups' => ['id' => $groupId]];
}

Creating ACOs

The ACL Extras plugin referred to in the CakePHP 2 ACL tutorial is now integrated into the CakePHP ACL plugin for CakePHP 3.

  • Run bin/cake acl_extras aco_sync to automatically create ACOs.
  • ACOs and AROs can be managed manually using the ACL shell. Run bin/cake acl for more information.

Creating Users and Groups

Create Groups

  • Navigate to /groups/add and add the groups
    • For this example, we will create Administrator, Manager, and User

Create Users

  • Navigate to /users/add and add the users
    • For this example, we will create one user in each group
      • test-administrator is an Administrator
      • test-manager is a Manager
      • test-user is a User

Remove Temporary Auth Overrides

Remove the temporary auth overrides by removing the beforeFilter function or the call to $this->Auth->allow(); in src/Controllers/UsersController.php and src/Controllers/GroupsController.php.

Configuring Permissions

Configuring permissions using the ACL shell

First, find the IDs of each group you want to grant permissions on. There are several ways of doing this. Since we will be at the console anyway, the quickest way is probably to run bin/cake acl view aro to view the ARO tree. In this example, we will assume the Administrator, Manager, and User groups have IDs 1, 2, and 3 respectively.

  • Grant members of the Administrator group permission to everything
    • Run bin/cake acl grant Groups.1 controllers
  • Grant members of the Manager group permission to all actions in Posts and Widgets
    • Run bin/cake acl deny Groups.2 controllers
    • Run bin/cake acl grant Groups.2 controllers/Posts
    • Run bin/cake acl grant Groups.2 controllers/Widgets
  • Grant members of the User group permission to view Posts and Widgets
    • Run bin/cake acl deny Groups.3 controllers
    • Run bin/cake acl grant Groups.3 controllers/Posts/index
    • Run bin/cake acl grant Groups.3 controllers/Posts/view
    • Run bin/cake acl grant Groups.3 controllers/Widgets/index
    • Run bin/cake acl grant Groups.3 controllers/Widgets/view
  • Allow all groups to logout
    • Run bin/cake acl grant Groups.2 controllers/Users/logout
    • Run bin/cake acl grant Groups.3 controllers/Users/logout

cakephp-3-acl-example's People

Contributors

mattmemmesheimer avatar paanblogger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cakephp-3-acl-example's Issues

AclNode::node() - Couldn't find Aros node identified by

We encountered this issue while building the ACL's for our system in AclNodesTable.php line 146 $ref[$name][$this->primaryKey()] now we were able to get it working by modifying the line to $ref[$name]['group_id'] as it was pointing to the Users->id and not the users->group_id, and we followed all the steps in setting up the ACO and ARO but what we fear is that if we are to update that our local changes will be overwritten.

Error aro not found, no tree returned

Hi,
I'm trying to use ACL in my app. I've followed all the step of the tutorial. Aro table is empty. when I try to see my arrow tree in console with command ./cake acl view aro i get error aro not found.
How can i fix it please?
I really followed all step includind generate acos. Please help me

can't login

Thanks for the tutorial
I followed it to a tee. Twice.

Well each time I can't login once I've finished.
It says that the password or user name is wrong. - the error from the login method.
It is doing the sql queries.
Do you know what is causing this? - I'm using WAMP.

UnauthorizedRedirect error

I'm testing this example and i see that in the part that you set the loadcomponent(auth....) with the paremeters, is missing one thing.
'unauthorizedRedirect' => [
'controller' => 'Cameras',
'action' => 'index',
'prefix' => false
],
'authError' => 'forbidden access',
'flash' => [
'element' => 'error'
]
In the code you are calling de 'Cameras' controller, but that file is missing. And i tried to implement the unauthorized redirect in several ways but i'm not figuring out how to display the error message. I created a contrller and a view but the message 'forbidden access' is not showing up.

Can you help me understand why?

Couldn't find Aros node (Groups)

Hey Guys, followed the Tutorial to setup ACL in an already existing Project. Now I Have the following error when i run:
bin/cake acl grant Groups.1 controllers

Exception: AclNode::node() - Couldn't find Aros node identified by "Array
(
    [Aros0.model] => Groups
    [Aros0.foreign_key] => 1
)
" in [/makakken/vendor/cakephp/acl/src/Model/Table/AclNodesTable.php, line 183]
2017-08-03 07:38:39 Error: [Cake\Core\Exception\Exception] AclNode::node() - Couldn't find Aros node identified by "Array
(
    [Aros0.model] => Groups
    [Aros0.foreign_key] => 1
)

Can Anyone please give ma hint how to solve the Problem? Yes there is a group with ID 1, it's Administrators , yes there is also a User having the group_id = 1

Running on Dev-Server of PHP 7.1.7

Missing Component: AclComponent could not be found.

Hi!

Thank you for this very useful tutorial.

Im having a litle error:

Missing Component: AclComponent could not be found.

Error: Create the class AclComponent below in file: src\Controller\Component\AclComponent.php

And it seems that the file isnt in the location mentioned above, i installed the plugin via composer from my app directory.

Thanks in advance.

Password Hashing Step

In order to be able to update other user information without changing (or at least re-entering) a users password, I would suggest using the following in App\Model\Entity\User.php

protected function _setPassword($password)
{
     return (new DefaultPasswordHasher)->hash($password);
}

And change the "baked" line below in App\Model\Table\UsersTable.php:

->notEmpty('password');

to this:

->notEmpty('password', 'You must provide a password', 'create');

I would also note that someone should add 'value' => '' anytime they use the Form helper to generate a field for updating the password.

Hope this is helpful.

Jwt with cakephp3 acl

Been able to successfully implement your plugin for role based authentication in my app. If you could guide me on how to authenticate api requests using the same. And If it is also possible to check if has permissions in the same api call. Thanks for providing us with this cute plugin.

AuthComponent is misconfigured

The AuthComponent is misconfigured. The unauthorizedRedirect and unauthorizedRedirect keys are configured to the non-existent CamerasController

AclNode::node() - Couldn't find Aros node identified by

Mi problema es: AclNode::node() - Couldn't find Aros node identified by "Array ( [Aros0.model] => Users [Aros0.foreign_key] => 45 ) "
en mi aplicación la tabla "users" se llama usuarios_externos, lo unico que cambio fue :
public function parentNode()
{
if (!$this->id) {
return null;
}
if (isset($this->group_id)) {
$groupId = $this->group_id;
} else {
$Users = TableRegistry::get('UsuariosExternos');
$user = $Users->find('all', ['fields' => ['group_id']])->where(['id' => $this->id])->first();
$groupId = $user->group_id;
}
if (!$groupId) {
return null;
}
return ['Groups' => ['id' => $groupId]];
}

Les agradezco la ayuda.. THX

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.