What are role providers? - php

How do I use zfc rbac role providers?
I understand guards prevent users from accessing routes but it seems like I need the role providers as well. Are these database permissions? In the example below is 'article' a controller and the part after the '.' the permission granted on that controller? How can I test these once in place? Many thanks.
return [
'zfc_rbac' => [
'role_provider' => [
'ZfcRbac\Role\InMemoryRoleProvider' => [
'admin' => [
'permissions' => [
'article.delete',
'article.edit',
'article.archive',
'article.read'
]
],
'member' => [
'permissions' => [
'article.edit',
'article.archive',
'article.read'
]
],
'guest' => [
'permissions' => ['article.read']
]
]
]
]
];

Here you can read about role providers
In ZF-Rbac one identity can have different roles with different permissions/privileges. To collect the roles for the authorizationService you need role providers. They will include a RoleProvicerInterface (link) with the getRoles method which is supposed to return the roles that the authorization service has to work with.
Each Identity has an IdentityInterface (link) which has also a getRoles method. This will return an array of roleNames which will be mapped to the roles from the RolesProvider to find out about permissions/privileges.
You can then find out what the current user (identity) is allowed to do.

Related

Modifying the included auth controller for Laravel 5.3

I am using the basic login and registration scaffold that comes with Laravel 5.3. I've also created a logging function so that I can log some of the basic user actions for my platform, such as updating or deleting records.
I'd like to add the logging to the user login process so that I can log when they've logged in and a failed attempt. Because I'm using the basic included scaffolding, I'm not sure where to do this?
If you want to hook into login process and just log something. Consider hooking into the authentication events provided by Laravel's Authentication events
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'Illuminate\Auth\Events\Registered' => [
'App\Listeners\LogRegisteredUser',
],
'Illuminate\Auth\Events\Attempting' => [
'App\Listeners\LogAuthenticationAttempt',
],
'Illuminate\Auth\Events\Authenticated' => [
'App\Listeners\LogAuthenticated',
],
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
],
'Illuminate\Auth\Events\Failed' => [
'App\Listeners\LogFailedLogin',
],
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\LogSuccessfulLogout',
],
'Illuminate\Auth\Events\Lockout' => [
'App\Listeners\LogLockout',
],
];

Silex Defining Access Rules

I follow the Silex documention section http://silex.sensiolabs.org/doc/providers/security.html#defining-access-rules
And here is my confirguration
'security.role_hierarchy' => [
'ROLE_ADMIN' => [
'ROLE_USER',
],
'ROLE_SUPER_ADMIN' => [
'ROLE_USER',
'ROLE_ADMIN',
'ROLE_ALLOWED_TO_SWITCH'
]
],
'security.access_rules' => [
[ '^.*$', 'IS_AUTHENTICATED_ANONYMOUSLY' ],
[ '^/account', 'ROLE_USER' ],
[ '^/admin', 'ROLE_ADMIN' ]
]
So what I need is quite simple, an anonymous user can access everywhere (except the /account/* and /admin/* paths), a user with "ROLE_USER" can access averywhere and /account/* paths, but not /admin/* paths, and a user with "ROLE_ADMIN" can access everywhere.
I make a very basic controller to test if a user is redirected if he's not a "ROLE_ADMIN":
$app->get('/admin', function () use ($app) {
return 1;
})->bind('admin');
But not at all. He can acces to /admin, with a printed "1" on the page...
According to the doc:
With the above configuration, users must have the ROLE_ADMIN to access the /admin section of the website [...] (if that's not the case, the user will be automatically redirected).
Definitely the order of the rules is important, only one will be matched. Silex will look at each starting at the top, and stop as soon as it finds one security.access_rules entry that matches the URL, in other words, Silex will decide which security.access_rules to use based on the URI and the first rule that matches is used. So you need move the first rule to end to resolve this:
'security.access_rules' => [
[ '^/account', 'ROLE_USER' ],
[ '^/admin', 'ROLE_ADMIN' ],
[ '^.*$', 'IS_AUTHENTICATED_ANONYMOUSLY' ],
]

Yii2 RBAC check permissions without each actions in controller

How i can check permissions in one place?
I don't want to check each function individually.
My RBAC controller.
I would like check permission for logged in user for all actions in the controller. Now I have to use Yii::$app->user->can('...') individually for each actions in the controller
$admin = $auth->createRole('Admin');
$moderator = $auth->createRole('Moderator');
$createPost=$auth->createPermission('createPost');
$updatePost=$auth->createPermission('updatePost');
$deletePost=$auth->createPermission('deletePost');
$createCategory=$auth->createPermission('createCategory');
$updateCategory=$auth->createPermission('updateCategory');
$deleteCategory=$auth->createPermission('deleteCategory');
$auth->add($admin);
$auth->add($moderator);
$auth->add($createPost);
$auth->add($updatePost);
$auth->add($deletePost);
$auth->add($createCategory);
$auth->add($updateCategory);
$auth->add($deleteCategory);
Here I assign role with permissions, but i never use these permissions because write manually in behavior->(like your example)
What is goal, create permissons in RBAC, if this not working? If I would like add premium user. I could only add action in controller e.g. actionPremium and set in behavior actions for premium user.
e.g
action=>['premium']
roles=>['premiumUser']
and one more question.
How in behavior customize message error?
$auth->addChild($admin,$moderator);
$auth->addChild($admin,$createCategory);
$auth->addChild($admin,$updateCategory);
$auth->addChild($admin,$deleteCategory);
$auth->addChild($moderator, $createPost);
$auth->addChild($moderator, $updatePost);
$auth->addChild($moderator, $deletePost);
$auth->assign($admin,1);
$auth->assign($moderator,2);
You can assign the permission allowed in controller for all action in behaviors
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index','view'], // these action are accessible
//only the yourRole1 and yourRole2
'allow' => true,
'roles' => ['yourRole1', 'yourRole2'],
],
[ // all the action are accessible to superadmin, admin and manager
'allow' => true,
'roles' => ['superAdmin', 'admin', 'manager'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
The role you assigned in behaviors are for action .. allowd or deny .. the if a role had an allowed action in behaviors then he can execute otherwise he get permission denied 403 .. (not authorized) ..
You can also check the role in procedural code with
if ( Yii::$app->User->can('admin') ){
.....
yourdCode
....
}

Multiple Login table in yii2 IdentityInterface error while login

I have 2 different tables user and organiser and i am trying to create 2 different login for both users.
I am able to sign them up easily and get the record in database but after saving the record i get the error on following code line
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) { //yii\web\IdentityInterface error
return $this->goHome();
}
}
Following is my configuration module
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendOrganiser', // unique for frontend
],
],
'users' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\Users',
'enableAutoLogin' => false,
'enableSession' => true,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
],
],
'session' => [
'name' => 'PHPFRONTSESSID',
'savePath' => sys_get_temp_dir(),
],
]
So what is wrong am i doing here? Do i need to create any other Interface or something or provide different interface for different module?
And i had to do this because organiser table uses password_hash technique to log in the users where my user table is from another project and they uses md5 technique, so i had to create separate module for both users.
Argument 1 passed to yii\web\User::login() must be an instance of yii\web\IdentityInterface, instance of common\models\Users given, called in C:\xampp\htdocs\project\frontend\controllers\SiteController.php on line 202 and defined
The exact error statement is as above.
I think your user model don't implement the Identity interface correctly.
Try check you data model also (in your DB) this must contain all the field managed bay the interface.
And be sure you User implement the Identity Interface correctly.
and mapping the interface method with your model correctly..
See the interface doc for this http://www.yiiframework.com/doc-2.0/yii-web-identityinterface.html

How to use authentication for multiple tables in Laravel 5

Sometimes, we'd like to separate users and admins in different 2 tables.
I think it is a good practice.
I am looking if that is possible in Laravel 5.
Before reading the following, you are supposed to have basic knowledge on ServiceProvider, Facade and IoC in Laravel 5. Here we go.
According to the doc of Laravel, you could find the Facade 'Auth' is refering to the Illuminate\Auth\AuthManager, which has a magic __call(). You could see the major function is not in AuthManager, but in Illuminate\Auth\Guard
Guard has a Provider. This provider has a $model property, according to which the EloquentUserProvider would create this model by "new $model". These are all we need to know. Here goes the code.
1.We need to create a AdminAuthServiceProvider.
public function register(){
Auth::extend('adminEloquent', function($app){
// you can use Config::get() to retrieve the model class name from config file
$myProvider = new EloquentUserProvider($app['hash'], '\App\AdminModel')
return new Guard($myProvider, $app['session.store']);
})
$app->singleton('auth.driver_admin', function($app){
return Auth::driver('adminEloquent');
});
}
2.Facade:
class AdminAuth extends Facade {
protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
}
3. add the alias to Kernel:
'aliases' => [
//has to be beneath the 'Auth' alias
'AdminAuth' => '\App\Facades\AdminAuth'
]
Hope this could be helpful.
I have created a laravel package where you can handle multiple authentication.
Step 1 : Composer require
Firstly, composer require the multiauth package
composer require sarav/laravel-multiauth dev-master
Step 2 : Replacing default auth service provider
Replace
Illuminate\Auth\AuthServiceProvider::class
with
Sarav\Multiauth\MultiauthServiceProvider
in your config/app.php file
Step 3 : Modify auth.php
Modify your config/auth.php file to something like this
'multi' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users'
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
'table' => 'admins'
]
],
Thats it! Now you can try multiple authentication by passing the user as first parameter. For example
\Auth::loginUsingId("user", 1); // Login user with id 1
\Auth::loginUsingId("admin", 1); // Login admin with id 1
// Attempts to login user with email id johndoe#gmail.com
\Auth::attempt("user", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
// Attempts to login admin with email id johndoe#gmail.com
\Auth::attempt("admin", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
For more detailed documentation
http://sarav.co/blog/multiple-authentication-in-laravel/
http://sarav.co/blog/multiple-authentication-in-laravel-continued/

Categories