Yii: How to set up roles in yii-user extensions? - yii

I installed the yii user extension and now i am wandering how i can add an extra role. I added a new column in the User db table and edited the UserModule like this:
public static function isEmployee() {
if(Yii::app()->user->isGuest)
return false;
else {
if (!isset(self::$_employee)) {
//check to see what kind of user we got and include admin for all
if(self::user()->type)
self::$_employee = true;
else
self::$_employee = false;
}
return self::$_employee;
}
}
and then when i try calling this in the rest of my site it dose not seem to work
'visible' => Yii::app()->user->isEmployee()
What i am doing wrong or what would be the best way to add an extra role that i can call on the site as above.

I don't know which extension exactly you installed - but you confused it with the user component. The user component is what you can access through Yii::app()->user. It's a CWebUser object by default. You can create your custom class WebUser extends CWebUser in the components/ directory. You would configure this as user component in your main.php config file.
'components' => array(
'user' => 'WebUser',
),
Then you move your isEmployee() method into that class. As you didn't provide any details on which extension you used, i can not really help you how to get that role check right. But i wonder if you shouldn't rather use a RBAC based solution. It allows you to create Roles and assign them to users. There are also several extensions that help you to manage roles and users.

Yii User is not meant for adding roles to users, it only handles user account management.
You may install an additional extension like rights, auth or srbac (see list) which provides a web-interface for this task.

Related

Role based Authorization for Razor Pages

In asp.net core it is very easy to define the razor pages authorization for pages and folders as follows:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact");
options.Conventions.AuthorizeFolder("/Private");
options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
});
My problem is that I want to use roles in my project but I can not find a way to define which roles are allowed to view the contents of the page.
I tried to use the Authorize attribute but it does not work with Razor Pages.
The AuthorizePage can take a second parameter which can be used in order to define the policy which will be used in order to determine if the current use can see the specified page or not. I used it as follows:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index", "RequireAdministratorRole");
});
The problem is that it still does noe work. It acts like I have not defined the policy. When I am logged I can see the page and when I am not logged it redirects me to the loggin form.
Is something else that I have to do in order to make it work?
I found what is wrong. In order to apply the changes after I remove the user from the role, I have to logout and login again so that the framework will refresh what the user allows to view.
This is really a problem because if a User has the admin role and for some reason we want to stop him from accessing sensitive data, we cannot stop him until he logs off.
Is there a way to refresh the user’s permissions when I remove a role from his account?
Restarting the application did not remove his permission. The only way to refresh his permissions is when he logs out.
This is due to the user's cookie still being valid. Here is more explanation to it here with a solution. Although it is in ASP.NET, the same concepts should apply for your Razor Pages project:
Refresh current user's role when changed in ASP.NET identity framework?
As to your latest question of
Is there a way to refresh the user’s permissions when I remove a role
from his account?
Yes you can refresh your logged in user using the SignInManager RefreshSignIn method.
As per the official documentation the method will
Signs in the specified user, whilst preserving the existing AuthenticationProperties of the current signed-in user like rememberMe, as an asynchronous operation.

Laravel protect routes from users that are not admin

I have certain routes that I need to protect from users that are not admin.
For example
http://myapp.com/clients
returns all the clients but is only for the administrator.
However
http://myapp.com/client/treutel_breitenberg
Should be available to them if they are logged in.
What is the best way to achieve this
You're going to need roles and a middleware, and there are many ways to do it. First you need to create an admin role, so some of your routes will only be available for someone who has the admin role. For that you can follow this laracasts tutorial : https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/16
You can also use a plugin to manage roles, like Zizaco's Entrust, it's built-up good, tested by a lot of users and easy to use : https://github.com/Zizaco/entrust
Next, to answer your question for the routes you can proceed like that :
Route::group(['middleware' => ['admin']], function () {
Route::group(['prefix' => 'admin'], function () {
Route::get('/your-path', 'YourController#yourMethod')->name('yourRouteName');
}
}
Any route within these two groups will need to be authenticated as admin and will return 'admin' prefix in your route, like so : www.yourwebsite.com/admin/your-path
If you don't use a plugin, you'll need to create your middleware to handle admins only.

Yii multiple user login in an application

I am a new in Yii framework, I just setup an application and separate front-end & Back-end part. Both User can register / log in properly. Now I want to login different user from front-end site.
Example : Front-End user are tow types
1. Customer
2. Merchant
I want to set different role of theme. How to possible it, Please share with me.
You will probably need to use Yii's RBAC. In order to implement and use RBAC in yii you need to follow the following steps:
1-configure main.php which is located at '/path/to/yourApp/protected/config/main.php'
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db', //your database config name
),
2-import yii's rbac database scheme into your database. You can find it under /path/to/yii/framework/web/auth/ directory
3-add your operations. Operations such as 'VIEW_POST' or 'EDIT_POST':
$auth=Yii::app()->authManager;
$auth->createOperation('VIEW_POST','view a post');
$auth->createOperation('EDIT_POST','edit a post');
4-create your roles. For example in your case you will have two roles. First Customer and second Merchant.
$role=$auth->createRole('CUSTOMER');
5- Assign operations to your roles:
$role->addChild('VIEW_POST');
6- All done! You can restrict the access like below:
if(Yii::app()->user->checkAccess('VIEW_POST'))
{
//user has access to view a post
}else{
//logged in user has no access to view a post
}
You can also check access with role like below:
if(Yii::app()->user->checkAccess('CUSTOMER')) {}
In order to assign a role to a user use the assign method:
$auth->assign('CUSTOMER','USERNAME | USER ID'); //user will hold the CUSTOMER ROLE
It might also be noted that, I assumed that you have implemented your authentication class. You can find more about Yii's RBAC and authentication in the following link which is Yii's official document:
Yii Authentication and Authorization

How to restrict access some part of module in ZendFramework 2 (i.e. only administrator can do some actions)

so!
I have a question: how to allow access some part of module only for adminisitrator, for example.
For example, I have module album. It has controllers index, delete, add, edit, full. I want full and index controller be available for all roles, but edit, delete and add action only for administrators.
What module I have to use to do that? I found Zend\Authentification.
Table is: username, password, role.
How to authentificate user?:
// do the authentication
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// success: store database row to auth's storage
// system. (Not the password though!)
$data = $authAdapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirect('/');
} else {
// failure: clear database row from session
$this->view->message = 'Login failed.';
}
After that I will get access to user data, for example, by:
Zend_Auth::getInstance()->getIdentity()->username;
So, in action, in which I want to restrict access I just need to use:
if(Zend_Auth::getInstance()->getIdentity()->role == admin) {
redirect("auth/login");
}
Right?
The questions:
Is my suggestion about how to check user role in each contoller correct?
Do I understand correctly how to work with Zend\Authentification and restrict access to some actions? So in future I will just use same for each action, right?
Additional question: Does Aclmodule uses for managing permissions? So Acl is needed to help Zend_Auth with permissions, right?
To be able to do this you have to build or implement an ACL (Access Control List). You can also use a third party solution in combination with the earlier mentioned Zend_Auth (or any other authentication module). You can read more on Zend ACL here: Zend ACL introduction
You could for example also take a look at BjyAuthorize. This ACL module provides a complete authorization solution for your application but depends on ZfcUser for user authentication and registration. It might be a good way to get started.
If you are done building or implementing BjyAuthorize you can easily tie your access permission checking to your routes (but there are many other ways). You can see how this works here on the BjyAuthorize GitHub page
These modules will teach you a lot about how authentication and authorization can be build into your Zend Framework 2 application.

Yii authorized access for the site index page

I am building administration backend (in yii) for the web app, and it should be disabled for usual users. In other words I have to make private access for http://www.taxitaxi.kz/dispatcher/index.php. I tried to insert some accessRules in sitecontroller, but it works in another way.
Awaiting your advices, thanks.
Add the rule in accessRules of your controller
array('allow',
'actions'=>array('actionName'),
'users'=>array('admin')
)
To make the controller use the rules you define in accessRules you also need to configure the accessControl filter.
public function filters()
{
return array('accessControl');
}