Cakephp: AuthComponent Evaluation Order and how to redirect to an action - cakephp

good day everyone, regarding auth component I am doing some tests to understand better the tool, in a probe of concept i want that an authenticated admin user be authorized to access any action, but if the authorized user has the "supervisor" role only be able to the actions index, view and edit in the "RequestsController.php", I am trying this approach:
1) allow everything for admin role and deny everything for anyone else in AppController.php.
2) Allow explicitly "supervisor" in "RequestsController.php" and deny any other role.
The doubt is that after some tests what happens is that if I authorize the admin user just in AppController.php the redirects only allows me to go to /webroot/, but If I allow the admin role in RequestsController.php. I can see requests without problem
IsAuthorize method in AppController
public function isAuthorized($user)
{
//privileges 1 means admin
if ($user['privileges']==1){
debug($user);
return true;
} else {
debug($user);
return false;
}
}
IsAuthorize method in Requests Controller
public function isAuthorized($user)
{
//privileges 9 means supervisor
if ($user['privileges']==9){
debug($user);
$action = $this->request->getParam('action');
if (in_array($action, ['index', 'view', 'edit'])) {
debug($user);
return true;
}
return false;
} else {
debug($user);
return false;
}
}
As I am not clear in the order that the isAuthorized function is handled, or why the redirect to the Request (even if it is "AppController.php" or "RequestsController.php") So this makes me think that I'll have to explicity authorize the admin role in all controllers

When using ControllerAuthorize, AuthComponent will call isAuthorized() method only on active controller. So, in your example, when requesting any action from RequestsController, only RequestsController::isAuthorized() will be called, disallowing access to users which has priviledge other than 9.
If you want to allow admin users to access as well, you should change your RequestsController::isAuthorized() as follows:
public function isAuthorized($user)
{
//privileges 9 means supervisor
if ($user['privileges']==9){
debug($user);
$action = $this->request->getParam('action');
if (in_array($action, ['index', 'view', 'edit'])) {
debug($user);
return true;
}
return false;
} else {
debug($user);
return parent::isAuthorized($user); //changed this line
}
}
Additional info: CakePHP 3.x AuthComponent - Authorization

Related

How to disable authorization middleware in cakePHP4?

By default, the authorization plugin is apply to a global scope. For some controllers that I did not want to apply any authorization. I have to use the skipAuthorization config manually for each action. For authentication plugin, I can just only load the authentication component for each controller that requires authentication. However, the authorization middleware seems will always work even if I did not load the authorization component in the controller. So, why is that? And is there a way I can disable the authorization process for the entire controller?
You probably mean Authentication and not Authorization. In any case, from the Docs:
// in src/Controller/AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('Authentication.Authentication');
}
By default the component will require an authenticated user for all
actions. You can disable this behavior in specific controllers using
allowUnauthenticated():
// in a controller beforeFilter or initialize // Make view and index not require a logged in user.
$this->Authentication->allowUnauthenticated(['view', 'index']);
More information: The Authentication plugin in the Cake Book.
I think you are not doing it in the right way. For authorization, you have to write a request policy. Whenever you bake controller just add --prefix Admin or whatever you want to.
cake bake controller Users --prefix Admin
Put all admin controllers in one place.
Add routes in your routes file
$builder->prefix('Admin',['_namePrefix' => 'admin:'], function (RouteBuilder $builder) {
$builder->connect('/', ['controller' => 'Users', 'action' => 'Index']);
$builder->fallbacks(DashedRoute::class);
});
`
Request Policy. Create a role table and add column role_id in the Users table and the rest you will understand with code below.
<?php
namespace App\Policy;
use Authorization\IdentityInterface;
use Authorization\Policy\RequestPolicyInterface;
use Cake\Http\ServerRequest;
class RequestPolicy implements RequestPolicyInterface
{
/**
* Method to check if the request can be accessed
*
* #param IdentityInterface|null Identity
* #param ServerRequest $request Server Request
* #return bool
*/
public function canAccess($identity, ServerRequest $request)
{
$role = 0;
if(!empty($identity)){
$data = $identity->getOriginalData();
$role = $data['role_id'];
}
if(!empty($request->getParam('prefix'))){
switch($request->getParam('prefix')){
case 'User' : return (bool)($role === 3);
case 'Admin': return (bool)($role === 1) || (bool)($role === 2);
}
}else{
return true;
}
return false;
}
}
`
and then implements AuthorizationServiceProviderInterface to the Application
use App\Policy\RequestPolicy;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\AuthorizationService;
use Authorization\Policy\MapResolver;
use Cake\Http\ServerRequest;
use Psr\Http\Message\ServerRequestInterface;
class Application extends BaseApplication implements AuthorizationServiceProviderInterface{
public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
{
$mapResolver = new MapResolver();
$mapResolver->map(ServerRequest::class, RequestPolicy::class);
return new AuthorizationService($mapResolver);
}
}

How to restrict ordinary user accessing all views

I want to restrict users with role="ordinary" accessing other Controller views
example... I have add views under JobsController so
if current login user has a user role="ordinary" basically he or she cant proceed to that and it will prompt, you are restricted accessing that page.
and if current user login has a user role="admin" he or she can proceed
I have this code below under AppController.php
public function isAuthorized($user)
{
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'ordinary') {
$allowedActions = ['index', 'logout', 'add'];
if(in_array($this->request->action, $allowedActions)) {
return true;
}
}
return false;
}
You can just put like this
<?php
if($this->request->session()->read('Auth.User.role') == 'admin'){
/// display the views
/// if current login user has admin role
}
else{
echo"You are not allowed to access this area";
}
?>
role must be present in users table field.
Hope it help your problem

admin panel with multiple user in cakephp

We are making application with having admin panel and under it multiple employees.
employee only see data and edit and update it.
I have studied ACL Component but i doesn't understand it properly, Can we get another
Link for it.
So I have store role admin , employee.
On user controller when users login it checks whether it is admin or employee
But it is not working can you suggest whats the problem in code.
public function beforeFilter()
{
parent::beforeFilter();
$userDetail=$this->Auth->request->data['User'];
$role = $this->User->findByEmail($userDetail['username']);
if($role['User']['role'] == "admin") {
$this->Auth->allow('*');
}else {
$this->Auth->allow('add','edit');
}
Try this-
public function beforeFilter()
{
parent::beforeFilter();
$role = $this->Auth->user('role');
if($role == "admin") {
$this->Auth->allow('*');
}else {
$this->Auth->allow('add','edit');
}
}

CakePHP Admin Login

I have two types of users and right now i dont want to use ACL. With Auth Component i want to achieve the following
login() -> allows users to login and access the general part of the site
admin_login -> allows the admin to access the admin_{actions} part of the website.
When i do a Admin Login -> i want to check if group_id = 1 in the Users Module and only allow them to login to the admin section of the website.
function admin_login(){
$this->layout = 'admin_login';
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username and password, try again'));
}
}
}
How to check if the group_id = 1 when the user logs in ?
I would do something like this:
function admin_login(){
$this->layout = 'admin_login';
if($this->request->is('post')) {
if($this->Auth->login()) {
// If here because user is logged in
// Check to see if group_id is 1
if($this->Auth->user('group_id') == 1){
//$this->redirect($this->Auth->redirect());
$this->redirect('/admin/dashboards'); //Example
}else{
// In case a user tries to login thru admin_login
// You should log them in anyway and send them to where they belond
$this->redirect('/users/account');
}
} else {
$this->Session->setFlash(__('Invalid username and password, try again'));
}
}
}

How can you test whether a user is active in Cakephp 2.0 auth component?

I'm having trouble hashing out how to test whether a user is active using the new Auth component. I have 3 states a user can be in: 0 unactivated (default), 1 activated, 2 deactivated. I'm trying to implement this in the login function so I can return whether they haven't registered or have been banned.
Login:
public function login() {
if ($this->request->is('post')) {
if($this->Auth->login()) {
$results = $this->User->find('all', array(
'conditions' => array('User.email' => $this->Auth->user('email')),
'fields' => array('User.is_active')
));
if ($results['User']['is_active'] == 0) {
// User has not confirmed account
$this->Session->setFlash('Your account has not been activated. Please check your email.');
$this->Auth->logout();
$this->redirect(array('action'=>'login'));
}
// not working atm
else if ($results['User']['is_active'] == 2) {
// User has been deactivated
$this->Session->setFlash('Your account has been deactivated. Contact site admin if you believe this is in error.');
$this->Auth->logout();
$this->redirect(array('action'=>'login'));
}
else if ($results['User']['is_active'] == 1) {
// User is active
$this->redirect($this->Auth->redirect());
}
} else {
$this->Session->setFlash(__('Your email/password combination was incorrect'));
}
}
}
Can't see where I've gone wrong. Users with admin privileges and activated users are still getting the unactivated account error.
Update
Decided to drop the User.is_active field and handle it all in roles. I'm handling it in the AppController and it is almost working now. In the isAuthorized function, it now throws errors if the user is banned or unactivated, but I need it to log them out as well.
public function isAuthorized($user) {
// This isAuthorized determines what logged in users are able to see on ALL controllers. Use controller
// by controller isAuthorized to limit what they can view on each one. Basically, you do not want to allow
// actions on all controllers for users. Only admins can access every controller.
if (isset($user['role']) && $user['role'] === 'admin') {
return true; //Admin can access every action
}
elseif (isset($user['role']) && $user['role'] === 'unactivated') { // Account has not been activated
$this->Session->setFlash("You haven't activated your account yet. Please check your email.");
return false;
}
elseif (isset($user['role']) && $user['role'] === 'banned') { // Your account has been banned
$this->Session->setFlash("You're account has been banned. If you feel this was an error, please contact the site administrator.");
return false;
}
return false; // The rest don't
}
If they log in, the User model info can be accessed with $this->Auth->user(). So you should be able to do something like this:
if ($this->Auth->login()) {
if ($this->Auth->user('is_active') == 0) {
// User has not confirmed account
} else if ($this->Auth->user('is_active') == 1) {
// User is active
// and so on
You can use debug($this->Auth->user()); after the login() to see why the users keep showing as unactivated.
Now, in year 2021, for CakePHP 4.x this is the correct approach:
if ( $result->isValid() ) {
if ( $this->getRequest()->getAttribute('identity')->is_active ) {
// The user is active and can log in
} else {
// The user is not active - reject the log in
}
}

Resources