Giter VIP home page Giter VIP logo

cakephp-tinyauth's Introduction

CakePHP TinyAuth Plugin

CI Latest Stable Version Coverage Status Minimum PHP Version License Total Downloads Coding Standards

A CakePHP plugin to handle authentication and user authorization the easy way.

This branch is for CakePHP 5.0+. For details see version map.

Features

Authentication

What are public actions, which ones need login?

  • Powerful wildcard (*) operator.
  • Quick Setup for 5 minute integration.

Authorization

Once you are logged in, what actions can you see with your role(s)?

  • Single-role: 1 user has 1 role (users and roles table for example)
  • Multi-role: 1 user can have 1...n roles (users, roles and a "roles_users" pivot table for example)
  • Quick Setup for 5 minute integration.

Useful helpers

  • AuthUser Component and Helper for stateful and stateless "auth data" access.
  • Authentication Component and Helper for isPublic() check on current other other actions.
  • Auth DebugKit panel for detailed insights into current URL and auth status.

What's the idea?

Default CakePHP authentication and authorization depends on code changes in at least each controller, maybe more classes. This plugin hooks in with a single line of change and manages all that using config files and there is no need to touch all those controllers, including plugin controllers.

It is also possible to manage the config files without the need to code. And it can with adapters also be moved completely to the DB and managed by CRUD backend.

Ask yourself: Do you need the overhead and complexity involved with the full blown (RBAC DB) ACL? See also my post acl-access-control-lists-revised/. If not, then this plugin could very well be your answer and a super quick solution to your auth problem :)

But even if you don't leverage the authentication or authorization, the available AuthUserComponent and AuthUserHelper can be very useful when dealing with role based decisions in your controller or view level. They also work stand-alone.

Demo

See https://sandbox.dereuromark.de/auth-sandbox

auth_allow.ini

Define the public actions (accessible by anyone) per controller:

Users = index,view
Admin/Maintenance = pingCheck
PluginName.SomeController = *
MyPlugin.Api/V1 = *

auth_acl.ini

Define what actions may be accessed by what logged-in user role:

[Users]
index = *
add,edit = user,super-user

[Admin/Users]
* = admin

[Translate.Admin/Languages]
* = *

AuthUser component and helper

$currentId = $this->AuthUser->id();

$isMe = $this->AuthUser->isMe($userEntity->id);

if ($this->AuthUser->hasRole('mod')) {
}

if ($this->AuthUser->hasAccess(['action' => 'secretArea'])) {
}

// Helper only
echo $this->AuthUser->link('Admin Backend', ['prefix' => 'Admin', 'action' => 'index']);
echo $this->AuthUser->postLink('Delete', ['action' => 'delete', $id], ['confirm' => 'Sure?']);

Installation

Including the plugin is pretty much as with every other CakePHP plugin:

composer require dereuromark/cakephp-tinyauth

Then, to load the plugin either run the following command:

bin/cake plugin load TinyAuth

or manually add the following line to your app's src/Application.php file's bootstrap() function:

$this->addPlugin('TinyAuth');

That's it. It should be up and running.

Docs

For setup and usage see Docs.

Also note the original blog post and how it all started.

cakephp-tinyauth's People

Contributors

adamhyski avatar alecho avatar alysson-azevedo avatar amr-dallin avatar angelxmoreno avatar bar avatar bravo-kernel avatar challgren avatar chrisspony avatar codaxis avatar dereuromark avatar dismounted avatar dsgraham avatar ervinszabo avatar gi-jones avatar ldsign avatar lordsimal avatar lorro avatar marianodonal avatar menshutin avatar mikk0s avatar mtancoigne avatar nadymain avatar opeadeyomoye avatar osazos avatar saeideng avatar steefaan avatar xyng avatar zeroasterisk 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  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

cakephp-tinyauth's Issues

Multiple Role tables

Hello,
Really nice plugin, very useful for the kind of application I'm developing.

Would it be possible to have multiple authorization tables, like, say, a user has both Roles and Rights.
I remember the Cake 2 version had it.

Missing TinyAuth role id field (Auth.User.user_role) in user session (CakePHP 4)

Error

i receive an error

Missing TinyAuth role id field (Auth.User.user_role) in the user session

This error comes from this line here

Investigation

Because of this line here

What actually happens is converting $identity->getOriginalData() into array got problem

Example of the problem

$user = $identity ? (array) $identity->getOriginalData() : [];
$userObject = $identity->getOriginalData();
dump($userObject->user_role); //return 1
dump($user['user_role']); //return Undefined index: user_role

below solution solve the issue

//at function canAccess(...)
$user = $identity ? $this->toArrayV2($identity->getOriginalData()) : [];

public function toArrayV2($object)
{
    return json_decode(json_encode($object), true);
}

Others

versions

"cakephp/authentication": "^2.0",
"cakephp/authorization": "^2.0",
"cakephp/cakephp": "^4.0",
"dereuromark/cakephp-tinyauth": "3.0.0",

BC & performance issues

hi
i think there are 2 problems

1)BC
removing public validate

public function validate($userRoles, Request $request) {
// Give any logged in user access to ALL actions when `allowUser` is
// enabled except when the `adminPrefix` is being used.
if (!empty($this->_config['allowUser'])) {
if (empty($request->params['prefix'])) {
return true;
}
if ($request->params['prefix'] !== $this->_config['adminPrefix']) {
return true;
}
}
// Allow access to all prefixed actions for users belonging to
// the specified role that matches the prefix.
if (!empty($this->_config['authorizeByPrefix']) && !empty($request->params['prefix'])) {
if (in_array($request->params['prefix'], $this->_config['prefixes'])) {
$roles = $this->_getAvailableRoles();
$role = isset($roles[$request->params['prefix']]) ? $roles[$request->params['prefix']] : null;
if ($role && in_array($role, $userRoles)) {
return true;
}
}
}
// Allow logged in super admins access to all resources
if (!empty($this->_config['superAdminRole'])) {
foreach ($userRoles as $userRole) {
if ($userRole === $this->_config['superAdminRole']) {
return true;
}
}
}
if ($this->_acl === null) {
$this->_acl = $this->_getAcl($this->_config['filePath']);
}
// Allow access if user has a role with wildcard access to the resource
$iniKey = $this->_constructIniKey($request);
if (isset($this->_acl[$iniKey]['actions']['*'])) {
$matchArray = $this->_acl[$iniKey]['actions']['*'];
foreach ($userRoles as $userRole) {
if (in_array((string)$userRole, $matchArray)) {
return true;
}
}
}
// Allow access if user has been granted access to the specific resource
if (isset($this->_acl[$iniKey]['actions'])) {
if (array_key_exists($request->action, $this->_acl[$iniKey]['actions']) && !empty($this->_acl[$iniKey]['actions'][$request->action])) {
$matchArray = $this->_acl[$iniKey]['actions'][$request->action];
foreach ($userRoles as $userRole) {
if (in_array((string)$userRole, $matchArray)) {
return true;
}
}
}
}
return false;
}

2)performance
when we used AuthUserHelper::hasAccess() and related _check() method
and $this->_getUserRoles($user); within _check()
so https://github.com/dereuromark/cakephp-tinyauth/blob/master/src/Auth/AclTrait.php#L385-L390 lines executed every time for every calling AuthUserHelper::hasAccess()
i think that makes low performance, for example for creating menu items

before this ,I used
$userRoles=$table->find()....
validate($userRoles , $request) in custom helper
but now I can not doing that :)

Authorization adapter "TinyAuth.Tiny" was not found

After installing TinyAuth in CakePHP 3.0 with Composer, and enabling it in AppController when I try to log in I get the following error:

Authorization adapter "TinyAuth.Tiny" was not found

This is my code from AppController:

 'authorize' => [
                    'TinyAuth.Tiny' => [
                        'roleColumn' => 'role_id',
                        'rolesTable' => 'Roles',
                        'multiRole' => true,
                        'pivotTable' => 'roles_users',
                        'superAdminRole' => null,
                        'authorizeByPrefix' => false,
                        'prefixes' => [],
                        'allowUser' => false,
                        'adminPrefix' => null,
                        'autoClearCache' => true
                    ]

This is how I load it in bootstrap.php:

Plugin::load('TinyAuth', ['bootstrap' => true]);

Calling the hasRole method in a ModelTable.php file

Hi Mark,

I'm having some problems with the following use case.
In a beforeSave method I would like to check if the logged in user has a specific role. If that's the case I set a specific property in the entity.

if ($customer->isNew() && $this->hasRole(ROLE_AGENT)) {           
    $customer->agent_id = $this->user('id');
 }

First I let this Table use the AuthUserTrait which allows me to use the $this->user method which works fine.
Though when I call the hasRole method I get the error that _getUserRoles is an unknown method so I also used the AclTrait. But then I get the error that the Table Class is not associated with _config. So I guess the approach I'm following isn't really the correct one :)

Is there an easy way to have access to this hasRole method in a ModelTable class?

Thanks!

Denied authorization redirect loop issue

I'm using TinyAuth with following configs in AppController.

    'authorize' => [
                'TinyAuth.Tiny' => [
                    'multiRole' => false,
                    'autoClearCache' => Configure::read('debug'),
                    'authorizeByPrefix' => true,
                    'prefixes' => ['admin'],
                ],
            ],

If I hit /users it works fine after logged in as a non-admin user. With the same user, if I hit /admin/users it says like this:

This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS

And here's the contents of acl.ini

[Users]
* = user

[admin/Users]
* = admin

How can I stop the above error?

Public functions calls

I have in my controller functions not related to views. If I do not include them in the acl.ini it is firing the flash auth message when my javascript calls this functions for ajax updates. Is there a way to exclude these functions from the acl.ini? Should these be private functions _someFunction()?

Kinda new at this...

Check access for the URL

I am trying to check access for the given URL so I have tried to use AuthUserHelper like this:

AppView
$this->loadHelper('TinyAdmin.AuthUser');

Template
$this->AuthUser->hasAccess(['controller' => 'users', 'action' => 'index'])

It returns following error
Missing TinyAuth role id field (Auth.User.role_id) in user session

I am using multi role, see component settings

$this->loadComponent('TinyAuth.Auth', [
    'authError' => false,
    'authenticate' => [
        'Form' => [
            'finder' => 'active',
            'fields' => ['username' => 'email']
        ]
    ],
    'authorize' => [
        'TinyAuth.Tiny' => [
            'multiRole' => true
        ]
    ],
    'loginRedirect' => [
        'controller' => 'Users',
        'action' => 'index',
    ]
]);

Any ideas?

hasAccess not considering auth_allow.ini

I am trying to create a dynamic menu only showing the links, which the user actually has access to.
Using $this->AuthUser->hasAccess() to do it seems to work for everything actually requiring authorization. But it does not take the setup of auth_allow.ini into acccount, and returns false for anything defined therein.

Is there a good way around this?

Table 'ppc.roles' doesn't exist

I'm trying to implemente a role file base (not database), following the example in the document:

define('ROLE_USER', 1);
define('ROLE_ADMIN', 2);
define('ROLE_SUPERADMIN', 9);

return [
    'Roles' => [
        'user' => ROLE_USER,
        'admin' => ROLE_ADMIN,
        'superadmin' => ROLE_SUPERADMIN
    ]
];

Still getting

 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ppc.roles' doesn't exist 

Do I necessarily needs the roles stored in database?

Proposition : split the config file

The idea behind the proposition is to have the ability to split the config file (acl.ini) in multiple files: I'd like to be able to create an acl.admin.ini with all admin-related rights, an acl.users.ini with users rights, etc... and when the files are merged, the rights are merged too, so I can have this :

; File acl.whatever.ini
[Controller1]
action1, action2= someRole

; File acl.whatever2.ini
[Controller1]
action1= someOtherRole

; Merged array:
[Controller1]
action1= someRole, someOtherRole
action2= someRole

I did something once with Yaml files, but it should be possible with inis too.

What do you think ?

how can define user id Column for user table?

hi
i need use other column instead of id in user table in multiRole
in multiRole , userColumn and roleColumn is for pivot Table
and this plugin use id of user table for query in
->where([$this->_config['userColumn'] => $user['id']])
i can open PR for this new option
are you other idea for resolve it?

Plugin

Hello!

Create one module "Admin" in "plugins/Admin" tinyauth not work on my module admin.

Support for named routes

Hi Mark,

Apparently the link method in the AuthUserHelper doesn't support the use of named routes to check if a user should see the link or not? Is that correct?

 <?= $this->AuthUser->link('Change Password', ['_name' => 'admin:account:password']); ?>    

doesn't show the link

 <?= $this->AuthUser->link('Change Password', ['action' => 'changePassword']); ?>    

does

Should I change all my named routes to array variants or is there a way to overcome this issue?

Thanks!

Missing TinyAuth role id field (Auth.User.role_id) in user session

Hi,

Thanks for this wonderful plugin.

I have successfully implemented Tiny Auth and Authorization with the multiRole facility but whenever I tried to access AuthUser component or Helper it gives

Missing TinyAuth role id field (Auth.User.role_id) in user session

I work around this issue by commenting following code from AclTrait.php file _getUserRoles function.
if (!$this->getConfig('multiRole')) { if (!array_key_exists($this->getConfig('roleColumn'), $user)) { throw new Exception(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $this->getConfig('roleColumn'))); } if (!isset($user[$this->getConfig('roleColumn')])) { return []; } return $this->_mapped([$user[$this->getConfig('roleColumn')]]); }

What am I doing wrong?

Regards,

Messaging for auth failures?

Is it possible to differentiate the messaging for an auth required vs. access denied message?

  • 'That page requires you to be logged in'
  • 'You do not have permission to access that page'

One comes when you are not logged in, the other is sent when you are logged in but do not a sufficient level to access.

User authentication, account athorization

I want to suggest to have an option to authenticate by users table, and authorize by accounts table.

Why?
Some applications may have one single user-login for multiple accounts. [email protected] may have to different accounts with different role(s).

How?
The developer needs to build a authFinder in the users-table to contain the accounts-table. The application needs rules/logic to make sure only one account is contained. The function _getUserRoles($user) in AclTrait.php is modified to get roles from accounts table is option 'accountsTable' => 'SomeTable'. If accountsTable === null, authorization works like today.

Want to discuss the interest of this?

acl.ini not recognised

After installing the plugin, acl.ini does not appear to be recognised, with none of the role authorisations working. However, auth_allow.ini works fine, with the views listed in that being accessible to everyone.

For example, in acl.ini, I have the UsersController as such:

[Users]
index = admin`
edit, view = user, engineer, admin
* = admin

However, when I log in as any type of user (admin or othewise), I'm able to access everything as if I'm an admin. In my AppController, the authorisation section is as follows:

'authorize' => [
                'TinyAuth.Tiny' => [
                    'filePath' => ROOT . DS . 'config' . DS,
                    'file' => 'acl.ini',
                    'multiRole' => false,
                    'usersTable' => 'users',
                    'allowUser' => false,
                    'authorizeByPrefix' => false,
                    'prefixes' => [],
                    'superAdminRole' => null,
                    'rolesTable'=>'roles',
                    'roleColumn' => 'role_id',
                    'idColumn' => 'id',
                    'aliasColumn' => 'alias',
                    'autoClearCache' => true,
                    'adminPrefix' => null
                ]
            ]

The roles are defined using a database format, with a roles table "roles", while the users table "users" has foreign key 'role_id' linked to the 'id' in table "roles".

ACL not working, it broken for version 1.6.4

I am working with version 1.6.4. Suddenly I found that, acl not working according to config/acl.ini. It works before when I used version 1.5. My AppController and config/app.php as same as before according to tinyauth documentation.

Mixing with Code has issue with Auth->deny()

Hello.

Documentation specifies that you can mix with code but i have a problem with the following situation:

//previous to TinyAuth...
//in Users Controller beforeFilter I would do something like this
$this->Auth->allow(); //allow all actions
$this->Auth->deny(['update']); //deny just the one action

//with TinyAuth...
//inside the INI file
Users = *
//in Users Controller beforeFilter
$this->Auth->deny(['update']); //deny just the one action

This does not appear to work, unauthenticated users can reach the 'update' action.

Error: Missing TinyAuth role id field (Auth.User.role_id) in user session

Could you please advise. Having a cakephp 3.5 issue? Can't seem to find what I am missing.

Error: Missing TinyAuth role id field (Auth.User.role_id) in user session

Appcontroller

$this->loadComponent('TinyAuth.Auth', [
                'loginAction' => [
                    'controller' => 'Users',
                    'action' => 'login',
                    'prefix' => false
                ],
                'loginRedirect' => [
                    'controller' => 'Auctions',
                    'action' => 'index',
                    'prefix' => false
                ],
                'logoutRedirect' => [
                    'controller' => 'Auctions',
                    'action' => 'index',
                    'prefix' => false
                ],
                'flash' => [
                    'element' => 'autherror'
                ],
                'authError' => 'Did you really think you are allowed to see that?',
                'unauthorizedRedirect '=> false,
                'authenticate' => [
                    'Form' => [
                        'fields' => [
                            'username' => 'username',
                            'password' => 'password'
                        ],
                        'contain' => ['Roles'],
                        'scope' => ['Users.active' => 1]
                    ]
                ],
                'authorize' => [
                    'TinyAuth.Tiny' => [
                        'roleColumn' => 'role_id', // Name of column in user table holding role id (only used for single-role per user/BT)
                        'rolesTable' => 'Roles',  // Name of Configure key holding all available roles OR class name of roles database table
                        'roleAlias ' => 'alias ',  // Name of the column for the alias
                        'multiRole' => true, // True will enable multi-role/HABTM authorization (requires a valid join table)
                        'pivotTable' => 'RolesUsers',
                        'superAdminRole' => null, // Id of the super admin role. Users with this role will have access to ALL resources
                        'authorizeByPrefix' => false, // If prefixed routes should be auto-handled by their matching role name
                        'prefixes' => [], // A list of authorizeByPrefix handled prefixes
                        'allowUser' => false, // True will give authenticated users access to all resources except those using the adminPrefix
                        'adminPrefix' => null, // Name of the prefix used for admin pages. Defaults to admin
                        'autoClearCache' => true // True will generate a new ACL cache file every time
                    ]
                ]
            ]
        );

appview

public function initialize()
    {
        parent::initialize();
        $this->loadHelper('TinyAuth.AuthUser');
        $this->loadHelper('User');
        $this->loadHelper('Ip');
    }

userstable

public function initialize(array $config)
    {
        $this->table('users');
        $this->displayField('username');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->addBehavior('Search.Searchable');
        $this->hasMany('Addresses', [
            'foreignKey' => 'user_id'
        ]);
        $this->belongsToMany('Roles', [
            'foreignKey' => 'user_id',
            'targetForeignKey' => 'role_id',
            'joinTable' => 'roles_users'
        ]);
        $this->belongsTo('Limits', [
            'foreignKey' => 'limit_id',
            'joinType' => 'INNER'
        ]);
    }

rolestable

public function initialize(array $config)
    {
        $this->table('roles');
        $this->displayField('name');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->addBehavior('Search.Searchable');
        $this->belongsToMany('Users', [
            'foreignKey' => 'role_id',
            'targetForeignKey' => 'user_id',
            'joinTable' => 'roles_users'
        ]);
    }

rolesuserstable

public function initialize(array $config)
    {
        $this->table('roles_users');
        $this->displayField('role_id');
        $this->primaryKey(['role_id', 'user_id']);
        $this->addBehavior('Timestamp');
        $this->belongsTo('Roles', [
            'foreignKey' => 'role_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);
    }

Coding Style

Maybe silly question.
It seems that code uses tabs for indent, but PSR-2 is saying

Code MUST use 4 spaces for indenting, not tabs.

Is this about personal preferences?

Thanks for great plugin!

Error: The "Auth" alias has already been loaded with the following config

After upgrading I am trying to enable Auth to test the auth_allow.ini feature but... enabling it using $this->loadComponent('TinyAuth.Auth'); as documented seems to interfere with my current Auth setup. Any ideas what's going on here?

    /**
     * Setup authentication.
     *
     * Please note that the Form authentication is only used when users request
     * a new token. All other authentication is handled by JwtAuth.
     *
     * Required option values:
     * - `queryDataSource`: set user fields (like Tiny required `id`) from db using `sub` claim
     *
     * @return void
     */
    protected function _setupAuth()
    {
        $this->_controller->loadComponent('Auth', [
            'storage' => 'Memory', // do not use session
            'checkAuthIn' => 'Controller.initialize', // make user data available in beforeFilter()
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password']
                ],
                'ADmad/JwtAuth.Jwt' => [
                    'finder' => 'obfuscated',
                    'userModel' => 'Users',
                    'fields' => [
                        'username' => 'id'
                    ],
                    'parameter' => 'token',
                    'queryDatasource' => true // must be true, see docblock
                ]
            ],
            'authorize' => [
                'TinyAuth.Tiny' => [
                    'multiRole' => true,
                    'rolesTable' => 'UserRoles',
                    'roleColumn' => Configure::readOrFail('TinyAuth.roleColumn'),
                    'allowUser' => false,
                    'authorizeByPrefix' => false,
                    'superAdminRole' => null,
                    'autoClearCache' => Configure::readOrFail('TinyAuth.clearCache')
                ]
            ],
            'unauthorizedRedirect' => false,
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login',
                'prefix' => false // make sub-namespaces use main logic (DRY)
            ]
        ]);
    }

V2.0 preparation

  • Remove deprecations
  • Rename acl.ini to auth_acl.ini to be consistent with auth_allow.ini

//EDIT: Or would anyone prefer this to be more concrete:

  • tinyauth_allow.ini
  • tinyauth_acl.ini

Missing TinyAuth role id field (Auth.User.role_id) in user session

I get this error when trying to use: $this->AuthUser->hasRole('admin'); in a view.
I would like to use DB roles with multi role option, but I'm not sure I fully understand how TinyAuth works and I did something wrong :/

This is my setup:

$this->loadComponent('TinyAuth.Auth', [ 'authorize' => [ 'TinyAuth.Tiny' => [ 'multiRole' => true, 'autoClearCache' => true ] ], 'authenticate' => [ 'Form' => [ 'fields' => [ 'username' => 'username', 'password' => 'password' ] ] ], 'loginRedirect' => [ 'controller' => 'Homepage', 'action' => 'index' ], 'logoutRedirect' => [ 'controller' => 'Homepage', 'action' => 'index' ] ]);

`; ----------------------------------------------------------
; UsersController
; ----------------------------------------------------------
[Users]

  • = admin

[Visits]

  • = admin, caller

[Workers]

  • = admin, caller

[Groups]

  • = admin, caller
    `

CREATE TABLE roles(idint(11) NOT NULL,namevarchar(255) NOT NULL DEFAULT '',descriptionvarchar(255) NOT NULL DEFAULT '',aliasvarchar(255) NOT NULL DEFAULT '',createddatetime NOT NULL,modified datetime NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE roles_users(idint(11) unsigned NOT NULL AUTO_INCREMENT,user_idint(11) unsigned NOT NULL,role_id int(11) unsigned NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE users(idint(11) NOT NULL AUTO_INCREMENT,usernamevarchar(255) NOT NULL,passwordvarchar(255) NOT NULL,activetinyint(1) NOT NULL DEFAULT '0',tokenvarchar(255) DEFAULT NULL,real_namevarchar(255) DEFAULT NULL,createddatetime NOT NULL,modified datetime NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Simple method to Edit own user account or profile

Is the a simple way to allow a user to edit their own user account?

Given a case where not a "normal" user is only allowed to view accounts, but not to create, edit, or delete:

[Users]
 index = *
 view = *
 add = user-manager, reporting, systems-admin
 edit = user-manager, reporting, systems-admin
 delete = user-manager, reporting, systems-admin

Is there a recommended way to allow them to edit their own account, say maybe in beforeFilter?

Router Scope Issue

I have a controller with the following namespace:

namespace App\Controller\Api\Datatables;

The controller is Listings and my function is Filter

I have the follwing route setup:

Router::scope('/datatables', ['prefix' => 'api/datatables'], function (RouteBuilder $routes) {
    $routes->extensions(['json', 'xml', 'ajax']);   
    $routes->fallbacks(DashedRoute::class);
});

This allows me to call the following url:

/datatables/listings/filter.json

I want to allow the filter function:

datatables/Listings = filter

When I call my URL I am re-directed to login. If I login the url works, so the allow_auth works.

I have also tried the following:

api/datatables/Listings = filter
api/Datatables/Listings = filter
Api/Datatables/Listings = filter
api/datatables/Listings = filter
datatables/Listings = filter
Datatables/Listings = filter
api/Listings = filter

No matter what the path is not allowed. If I move the controller to the default location then in allow_auth:

Listings = filter

the filter function is accessible without authorisation. This suggests that there is a problem with the plugin when user a router scope.

No roles when allowing anonymous

If I understand correctly, when allowing anonymous access (using auth_allow.ini):

  1. Auth is bypassed
  2. the user is therefore not authenticated
  3. the user does therefore not have any roles available

However understandable this does seem to make it impossible to support the following scenario:

  • single API endpoint /books
  • the endpoint produces different JSON result based on role:
    • result is limited for anonymous
    • users see a bit more data
    • admins see everything

The problem here is

  • when I allow anonymous access... no user ever authenticates (no roles available)
  • when I enable * acl... anonymous users can no longer access the resource

โ“ Do you think a solution for the scenario above is even possible?

Allow loginRedirect action for all authenticated users

With Auth component you can or use default loginRedirect, when you use 'authorize' => 'TinyAuth.Tiny' you might end up with too many redirect untill you specify loginRedirect action in the acl.ini.

Would it be good idea to allow this action for all authenticated users?

Permission for App Controller Actions

How can add permission for app controller actions. i have tried to add through auth_allow.ini as follows

app/testAction = *

but it doesn't allows user to access link raises unauthorized error.

Cake4 - Documentation suggestions

https://github.com/dereuromark/cakephp-tinyauth/blob/cake4/README.md

Just personal preference, but I tend to put installation instructions at the top of the readme, after a brief introduction about what problem the plugin solves. It took me a bit of searching to find the installation instructions at the bottom of the readme.

https://github.com/dereuromark/cakephp-tinyauth/blob/cake4/docs/AuthPanel.md

I think it would be handy to include a link to the relevant section of the DebugKit documentation on how to add panels. As saying to add it to configuration but not showing where or how is confusing and a bit frustrating.

Once I implemented the TinyAuth.Auth component I still didn't see a DebugKit panel show up. I configured the panel using Configure::write('DebutKit.panels', ['TinyAuth.Auth' => true]);

https://github.com/dereuromark/cakephp-tinyauth/blob/cake4/docs/README.md

I would move the DebugKit panel documentation after the Authentication, Authorization and Configuration sections. As I've enabled the panel first, but because I haven't yet enabled the other parts, it doesn't show up in DebugKit Toolbar. Could be my bad implementation.

https://github.com/dereuromark/cakephp-tinyauth/blob/cake4/docs/Authentication.md

I'd want to know how to enable it before trying to configure it. So I would personally move the enable section to the top of the readme here.

There is no documentation which shows how to configure the components options. My application is using email_address as the username field. So when I loaded the component I wasn't able to login. I guessed that it follows the same configuration options as the core AuthComponent which worked, so I'd add a link stating that into the docs.

I also couldn't seem to get the finder option to work. As I have a scoped find using is_active. If the component doesn't support custom finders this should be noted in the docs.

DB backend for ACL management?

Can we discuss the possibility of having an easy admin backend here to manage the roles via website?

My idea would be to hook into the _getAcl() method and also allow reading from the database.
We would need the following table:

auth_acl:

  • id
  • controller (incl prefix and plugin), e.g. Posts.admin/Posts
  • actions, e.g. *
  • roles, e.g. user,admin

This would then be cached somehow so the _getAcl() would retrieve a list just like it expects from the INI file. We could even write this INI file upon each DB change.

The backend could have pre-parsed dropdown options of all plugins and their controllers and actions as well as available roles and some basic sanity validation.

Any more feedback here?
I think this would make the plugin suitable for many more use cases.

Cannot load TinyAuth bootstrap.php

Dear Dereuromark.

I did use composer to install plugin and in my bootstrap.php I do load your TinyAuth plugin with bootstrap = true, but seam wrong folder.

Error as bellow, in fact, your plugin folder is: TinyAuth instead of cakephp-tinyauth

wrong folder

Cannot get user role using $this->loadComponent('TinyAuth.AuthUser');

Hello,
I'm using multiple-roles-per-user model and i stucked on the getting the role of the logged user.

I am able to define roles and log-in with allowed roles. But when i tried to get role using the following code:
AppController
$this->loadComponent('TinyAuth.AuthUser');

I always got the following exception:

TinyAuth.AuthUserComponent could not be found.

Make sure your plugin was loaded from config/bootstrap.php and Composer is able to autoload its classes, see Loading a plugin and Plugins - autoloading plugin classes

So i cannot use this in any controller to get role:

*DashboardsController extends AppController *

$this->Auth->hasRole('admin') //true / false

Or any other method to get role.

when i removed the

$this->loadComponent('TinyAuth.AuthUser');

From the appController i was able to get user info, but not the user role from the related table.

In this case i left only the following config:

 $this->loadComponent('TinyAuth.Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'authorize' => [
                'TinyAuth.Tiny' => [
                    'autoClearCache' => true,
                    'multiRole' => true,
                    'roleColumn' => 'role_id',
                    'rolesTable' => 'Roles',
                    'pivotTable' => 'roles_users',
                    //'roleColumn' => 'role',
                    /*
                    'usersTable' => 'users',
                    'rolesTable' => 'users',
                    'roleColumn' => 'role',
                    'aliasColumn' => 'role',
                    */
                ]
            ],
            'loginRedirect' => [
                'controller' => 'Dashboards',
                'action' => 'index'
            ],
            'unauthorizedRedirect' => [
                'controller' => 'Users',
                'action' => 'restricted'
            ],
        ]);

How this could be solved? Documentation seems to be outdated in this case.

Many thanks for any advice.

Auth Help

When in a controller or view how to I check for the current users role?

AuthComponent not fully executing

While checking why my auth_allow.ini was not being processed I noticed the AuthComponent does not run anything after this line.

Might very well be caused by my setup but the AuthComponent startup and beforeRender methods are never executed. Looks like jwt-auth somehow preceeds it (throwing a 401 error).

    protected function _setupAuth()
    {
        $this->_controller->loadComponent('TinyAuth.Auth', [
            'storage' => 'Memory', // do not use session
            'checkAuthIn' => 'Controller.initialize', // make user data available in beforeFilter()
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password']
                ],
                'ADmad/JwtAuth.Jwt' => [
                    'finder' => 'obfuscated',
                    'userModel' => 'Users',
                    'fields' => [
                        'username' => 'id'
                    ],
                    'parameter' => 'token',
                    'queryDatasource' => true // must be true, see docblock
                ]
            ],
            'authorize' => [
                'TinyAuth.Tiny' => [
                    'multiRole' => true,
                    'rolesTable' => 'UserRoles',
                    'roleColumn' => Configure::readOrFail('TinyAuth.roleColumn'),
                    'allowUser' => false,
                    'authorizeByPrefix' => false,
                    'superAdminRole' => null,
                    'autoClearCache' => Configure::readOrFail('TinyAuth.clearCache')
                ]
            ],
            'unauthorizedRedirect' => false,
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login',
                'prefix' => false // make sub-namespaces use main logic (DRY)
            ]
        ]);
    }

Issue because of debug mode off in app.php

Hello,

I am using this plugin in cakephp 3.0.
Issue is there when we change in acl.ini file by add or remove permission. On result there will be not impact but when we enable debug mode on and again test then It will work. So how can I resolve this issue.

Stateful and Stateless Auth in a single application

Hi,

I'm struggling to configure TinyAuth to handle both form based stateful authentication (for a user and a web browser) and API stateless authentication (to power a JSON API)

I can get the form based auth working fine, and have confirmed it will call each of Authentication classes in the order defined.

However, when simulating an API request (I'm using POSTMAN rest client here) with Accept/Content-Type headers set, the authentication classes are ignored completely.

Before going any further - is what I am trying to do even possible? Can TinyAuth handle both stateless and stateful for a single application at the same time?

I should also note I am using RequestHandlerComponent to handle my JSON dataviews.

TinyAuth

after set, on running the project i got this error message: Authorization adapter "TinyAuth.Tiny" was not found. I need help on this.

Deny support using `!`?

Is this something people see as useful to have for Authentication?

tinyauth_allow.ini

Users = index, view ; Public access to index and view action
Extras.Offers = *, !delete ; All expect delete action are public

If not we can close this again

Adding PHP, YAML, ... adapters?

Do people currently prefer the INI files and adapter?
Or shall we also add others? What are your preferred config files?
Feel free to comment and let us know what is missing terms of config file support.

Prepare 1.2 release

1.2 release notes will look like:


No constants anymore.
Please make sure you upgrade to the new configs:

  • usersTable (no constant anymore)
  • userColumn (new, defaults to user_id as it was hardcoded before)

usersTable, pivotTable and rolesTable now support plugin prefixing, e.g.:

// App
'rolesTable' => 'Roles',

// User plugin
'rolesTable' => 'User.Roles',

Anything missing?

We need to adjust the plugin syntax with tests prior to making this new release.

Issue with DB Roles.

Hi, thanks for your auth plugin. I wanted to query, once configured the table of users, roles and roles_users, how specific that a particular role number has access to a controller or function? Thank you.

using Auth::hasRole()

Hi!

I'm just migrating a project from cake2 to cake3 and i wonder why there has been a change to Auth::hasRole(). I used this to check if the current user has the given role like this:

Auth::hasRole( ROLE_OFFICE )

Now I have to use something like this:

Auth::hasRole( ROLE_OFFICE, $this->Auth->user('role_id') )

Am I doing something wrong? It seems that i could also check the rights with a simple "==".

Thanks!
Bernhard

Route access instead of action

Currently you can set what action is controlled in acl.ini, e.g. index, view, edit, ... but sometimes you action can be more sophisticated and you need more access control.

For example you have index action and you pass first parametr to filter your results, e.g.

/users/index/all
/users/index/active
/users/index/blocked

And you would like user role to have access only to the /users/index/active.

Acl ini could look like

[Users]
index/all, index/blocked = admin
index/active = user

Is that something what could be part of TinyAuth or is this out of the plugin concept?

I don't want to fall into ROW based access, but this is about extended action (route), not about the records itself.

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.