CakePHP - CakeDC Plugin Permission Not Working - cakephp

I have been using the following plugin (https://github.com/CakeDC/users) for CakePHP, but I can't figure out how to get the permissions working for it. I have followed all instructions, but it seems authorize does not get used at all. Wondering if anyone has any tips on how to make it work. Here is my setup:
bootstrap.php
Configure::write('Users.config', ['users']);
Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
AppController.php initialize function
$this->loadComponent('CakeDC/Users.UsersAuth');
config/users.php
$config = [
'Auth' => [
'authError' => 'Did you really think you are allowed to see that?'
]
];
return $config;
config/permissions.php
return [
'Users.SimpleRbac.permissions' => [
[
'role' => '*',
'controller' => 'Pages',
'action' => ['display'],
'allowed' => true
], [
'role' => '*',
'controller' => 'Taxes',
'action' => ['*'],
'allowed' => true
], [
'role' => '*',
'prefix' => 'v1',
'controller' => '*',
'action' => '*',
'allowed' => true
]
]
];
return $config;
Frankly it seems a CakePHP configuration issue, but I am not able to find where that problem is coming from. I say that because even though debug shows the correct file loaded to authorize, it does not get called.

Please ensure you are returning the $config variable in the users.php file and you are initializing the plugin correctly as indicated here https://github.com/CakeDC/users/blob/master/Docs/Documentation/Configuration.md
Configure::write('Users.config', ['users']);
Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
I've created a test environment here with your provided Auth configuration and it works correctly https://ide.c9.io/steinkel/users-so-42523209
https://nimbus.everhelper.me/client/notes/share/790695/girguwv9x7rttdvu5c4x
Thanks,

Related

CakePHP 3 JWT-Auth gives 401 Unauthorized error

I'm using CakePHP 3.6 and JWT Auth to enable token-based authentication in my application and frontend is written in Angular 6.
My login controller is like
<?php
namespace App\Controller\Api;
use Cake\Event\Event;
use Cake\Http\Exception\UnauthorizedException;
use Cake\Utility\Security;
use Crud\Controller\Component\CrudComponent;
use Firebase\JWT\JWT;
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['add', 'token']);
}
public function token()
{
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username or password');
}
$this->set([
'success' => true,
'data' => [
'token_type' => 'Bearer',
'expires_in' => 604800,
'token' => JWT::encode([
'sub' => $user['id'],
// 'exp' => time() + 604800
],
Security::getSalt())
],
'_serialize' => ['success', 'data']
]);
}
}
AppController.php contents
namespace App\Controller\Api;
<?php
use Cake\Controller\Controller;
class AppController extends Controller
{
use \Crud\Controller\ControllerTrait;
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Crud.Crud', [
'actions' => [
'Crud.Index',
'Crud.View',
'Crud.Add',
'Crud.Edit',
'Crud.Delete'
],
'listeners' => [
'Crud.Api',
'Crud.ApiPagination'
]
]);
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'finder' => 'auth'
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'Users',
'finder' => 'auth',
'fields' => [
'username' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
]);
}
}
On sending request from the angular application to generate token works fine and following response is received.
But when using the token to send the request to other endpoints giving an error
401: Unauthorized access
The request/response header has token
What I tried?
I tried with disabling exp while generating an access token.
tried with disabling debug in CakePHP application.
It is working great when CakePHP server application is run locally.
in your .htaccess try this rule (if mod_rewrite is activated) :
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
With the Bitnami stack of LAMP (on EC2 AWS instance for example), the php-fdm module filter the header of every requests, and the "authorization" header is screwed up.
With this line, you can force to create a $_HTTP variable with the original Authorization header.
Regards
Check in cakephp code if you are receiving the AUTHORIZATION in headers.

Cakephp 3 Auth Component password field with MD5

I am using cakephp 3 and their auth component .. everything is working fine but i want to match my password while login using md5 instead of default hashing password logic cakephp 3 uses ... what should i do to implement this feature .. here below is my AppController.php file what i have done so far ..
AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'dashboard'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'authenticate' => [
'Form' => [
'userModel' => 'Users',
'fields' => [
'username' => 'user_email',
'password' => 'user_password'
]
]
],
'storage' => 'Session',
'unauthorizedRedirect' => false,
]);
}
as i mentioned above, everything is working fine, i am able to login successfully with default hashing method which cakephp 3 provides, but i just want to exclude this hashing method and need to check using md5 .. how can i do this ?
Can someone guide me or help me please ?
Thanks
Ok .. guys .. eventually i have found out the solution and here below is what i have come up with .. so if anybody stuck or want similar feature, they can follow this thing to accomplish this ..
Go here http://book.cakephp.org/3.0/en/controllers/components/authentication.html#creating-custom-password-hasher-classes there they are saying to create a new file which you need to follow and need to create.
Then in your Auth Component make sure you add below line
'Form' => [
'passwordHasher' => [
'className' => 'Legacy',
]
]
This is working for me, i hope it helps someone .. Thank you guys.

How to get CakePdf to work in CakePHP 3.x?

I have installed CakePdf plugin in app/plugins folder and followed all the documentation possbile, thus my settings are as following:
// config/bootstrap.php
Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.WkHtmlToPdf',
'binary' => '/wkhtmltopdf/bin/wkhtmltopdf',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'landscape',
'download' => true
]);
// config/routes.php
Router::extensions(['pdf']);
// controller/AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
'loginAction' => ['controller' => 'Users', 'action' => 'login'],
'loginRedirect' => ['controller' => 'Users', 'action' => 'index'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'login'],
'authorize' => 'Controller'
]);
}
Here is how a sample agendaPdf action looks like:
function agendaPdf(){
$agenda = 'sample agenda';
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'agenda_123'
]
]);
$this->set('agenda', $agenda);
}
I have PDF layouts done, as well as a PDF folder inside the templates folder for the model's actions, however, if I go to app/users/agendapdf.pdf, I am given the following messages:
The action agendapdf.pdf is not defined in UsersController
Error: Create UsersController::agendapdf.pdf() in file: src/Controller/UsersController.php.
I would really like to know what could have went wrong and how I can fix it to work.
CakePdf does not include any of the supported PDF engines, so i tried wkhtmltopdf( Refered Link).
Step by Step process:
1. Install wkhtmltopdf binary file in your local or server system (Ubuntu, Window, Mac) - Download link : [wkhtmltopdf][2]
2. Check the installed location of wkhtmltopdf binary file - (i am using ubuntu so installed location is /usr/local/bin)
3. configure the wkhtmltopdf with cakephp:
- in : config/bootstrap.php like below:
Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.WkHtmlToPdf',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'landscape',
'download' => true
]);
- Create a folder name "pdf" under your working template view folder:
* for ex: src/template/(working view folder)/pdf (src/template/budget/pdf)
- Create a file name "view.ctp" under newly created pdf folder under working directory:
* for ex: src/template/(working view folder)/pdf/view.ctp (src/template/budget/pdf/view.ctp)
- use below code in working controller - action(view - method)
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
]
]);
* for ex:
public function view($id = null)
{
$budget = $this->budget->get($id);
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
]
]);
$this->set('budget', $budget);
}
- Hit the controller and action to download as PDF.
* for ex: http://localhost:8765/projects/view/1.pdf
- if you are facing "wkhtmltopdf binary is not found or not executable" error. copy your wkhtmltopdf file from "/usr/local/bin" to "/usr/bin"
* cd /usr/local/bin
* sudo cp wkhtmltoimage /usr/bin/wkhtmltoimage
* sudo cp wkhtmltopdf /usr/bin/wkhtmltopdf

CakePHP - Add custom values to User Object

I have added 4 more columns to my CakePHP Users table and I am trying to figure out how I can include these columns in the $this->Auth->user() object.
I've added the column information to my Users Model and Entity but still no joy. Currently my user object looks like this;
[
'id' => (int) 1,
'username' => 'admin',
'name' => 'Web Admin',
'email' => 'webteam#',
'role' => 'admin',
'created' => object(Cake\I18n\Time) {
'time' => '2016-02-09T16:04:46+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2016-02-12T08:53:16+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
}
]
Where is this object created and is there a way I can add my custom values to it, without editing core CakePHP files?
Thanks for your help .
By default the built-in authenticators will fetch all fields in the tables schema.
You most probably just forgot to clear your cache (tmp/cache/models), which you should do whenever you make changes to your schemas.
In case one would want to specify what fields are being fetched, a custom finder would be needed.
See Cookbook > Controllers > Components > Authentication > Customizing Find Query
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'finder' => 'auth'
]
],
]);
In your UsersTable class
public function findAuth(\Cake\ORM\Query $query, array $options)
{
return $query
->select(['id', 'username', 'password', 'column_x', 'column_y']);
}
It should be noted that the fields required for authentication must always be included, ie like username and password!

Display/hide links cakephp 3.0

Sorry im new to cakephp 3.0. In my user table, there are two user types, admin and public. How do I display/hide links according to user types in default.ctp? Can anyone guide me thanks!!
This is my app controller
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
//...
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['controller' => 'Users', 'action' => 'add', 'index',
]);
}
}
The AppController you've posted has nothing to do with what I understand of your request so that's got me a little confused. Either way, you can access the session of the current logged in user through session variables.
For example - if your users table had the column 'type' in which the values 'public' or 'admin' were stored, it would look something like this:
<?php if ($this->session->read('Auth.User.type') == 'admin') { ?>
Link to admin functions
<?php } else { ?>
Boring public link
<?php } ?>
That's assuming you're working with logged in users. If you haven't got that far yet, read the CakePHP 3 tutorial on authentication and authorization.

Resources