How to add a role to user when having basic User model in Yii2 - yii2

Building a lightweight app using basic installation of Yii2.
I need to assign a role for a user but don't want to have users and user roles stored in database.
How can I set a role for users defined in User->users class?
Default User model and default user definition look like this:
class User extends \yii\base\BaseObject implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],

You can use RBAC PhpManager for that that will store all roles info in files instead.
First configure your AuthManager component in config/web.php:
// ...
'components' => [
// ...
'authManager' => [
'class' => 'yii\rbac\PhpManager',
],
// ...
],
By default it uses 3 files to keep the data:
#app/rbac/items.php
#app/rbac/assignments.php
#app/rbac/rules.php
So make sure there is folder rbac in your application's root and that it's write-able by the www process. If you want to place the files somewhere else (or rename them) you can provide the new path in the configuration like:
'authManager' => [
'class' => 'yii\rbac\PhpManager',
'itemFile' => // new path here for items,
'assignmentFile' => // new path here for assignments,
'ruleFile' => // new path here for rules,
],
The rest now is just like in the Authorization Guide.
Prepare roles and permissions (example in console command - by running this command once you set all roles; remember that if you want to run it in console you need also configure console.php with the same component).
Assign role to a user (example - here it's done during the signup but you can do it also in the above command).
Now you can control access with direct check or behavior configuration.

Related

define access role to all user (user,guest,admin,..) in yii2

I use rbac (dektrium) and ACF to check to access users in my project (yii2). I created some role for example :admin, manager, suser,user,.. I have some actions that all user can use its for example view action. how can define in behaviors method that all user can use view action?
To do this we assigned actions to user '*' in yii1.
...
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('view'),
'users'=>array('*'),
),
...
in yii2 use this code ()
...
[
'allow' => true,
'actions' => ['view'],
'roles' => ['?'],
],
...
but when admin user or manager user want to access to myController/view shows forbidden. only guests can access to myController/view, how can define a role or access to access to all user by default?
If you want to allow everyone to access action then there is no need to apply access filter for that action. To avoid applying access filter for specific actions you can use $except property of yii\filters\AccessControl. For example like this:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'except' => ['view'],
'rules' => [
//rules for other actions ...
]
],
//other behaviors ...
];
}
Other option would be to use a combination of roles ? (guests) and # (all logged in users) like this:
[
'allow' => true,
'actions' => ['view'],
'roles' => ['?', '#'],
]
There is also $only property in yii\filters\AccessControl that allows to apply filter only to explicitly named actions. But it's better to use $except for security reasons.
Resources:
yii\filters\AccessControl
yii\filters\AccessRule::$roles

how to limit access url view on yii2 by id

I am basically a PHP developer & learning Yii2. I am working on web application that has account based login system. Like the way i was doing in PHP web applications, i want to stop another user from accessing the view if he/she is not authenticated. Its like if someone tries to access url(any related URL) externally:
www.example.com/permintaanbarang/index.php?r=user/view&id=1
chage to
www.example.com/permintaanbarang/index.php?r=user/view&id=2 by another user
At that time that person should be redirected to login page or Notice NotFound 404 as that person is not authorized to access account based page directly.
What are the directions to implement this in MVC framework???
A simple way for controlling access and avoid to guest user (not authenticated) to access is use filter for access control
<?php
namespace yourapp\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
In this sample you can see that you can configure the action you can access ofr all and for authenticated #
You can find useful this guide http://www.yiiframework.com/doc-2.0/guide-security-authorization.html and this reference http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html
In Yii2 you can also use a RBAC authrization component for define class of user and grant to this class specific accessing rules ..
and you can also check programmaticaly the RABC Auth for specific need eg:
if (!Yii::$app->user->isGuest) { // if the user is authenticated (not guest)
if ( Yii::$app->User->can('admin') ){ // if the role is admin
.....
you app code
There are AccessControlFilters for doing this

Yii2 roles and users

Can I statically define roles in authManager (in defaultRoles array in config) and assign them to users so behavior rules define access to actions?
As i have certain roles, I don't want to use auth_assignment and auth_item and ...
Assuming I create column in user table for role and every user has one role and roles are define in config file.
In fact I want to build access rules like 'admin' for users who are admin (Where yii says '#' for authenticated user and '?' for guest).
First create your roles somewhere like params then behaviors function can manage authentication easily
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'except' => [''],//or only
'rules' => [
[
'allow' => true,
'actions' => ['deletepic', 'regenerate'],
'matchCallback' => function ($rule, $action) {
return (myAuth(['root','admin']));
}
],
],
],
];
}
myAuth() will check current user role and return true if they role match requested action.

Yii2 mongodb: how to change database?

My application use many databases, they are in same structure, but data has no relation between different databases. I need to change database via request params.
In the config can only setup dsn, but I want to change database dynamically.
How can I do that.
I got myself:
$mongo = Yii::$app->get('mongodb');
$mongo->options['db'] = 'foo';
The simplest solution is to defined multiple connections in the configuration:
'components' =>
[
...
'mongodb' =>
[
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://localhost:27017/database1',
],
'othermongodb' =>
[
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://localhost:27017/database2',
],
...
]
You can then access your connections with Yii::$app->mongodb and Yii::$app->othermongodb (or using the get()-method if you prefer). This also allows you to specify the correct database for the ActiveRecord classes that come from a different database:
class MyOtherDBMongo extends \yii\mongodb\ActiveRecord
{
public static function getDb()
{
return \Yii::$app->get('othermongodb');
}
}

CakePHP 3 Auth on model other than User

I'm working on a project rebuild using CakePHP, and following the new Authentication documentation here:
http://book.cakephp.org/3.0/en/controllers/components/authentication.html
From what I'm reading, Cake3 uses the userModel='User' by default, but it has the option to set it to whatever you want. In my case, I have all the auth data in the 'Account' model (i.e. userModel => 'Account').
So, in my Account Entity, I added the following code:
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
Additionally, in my accounts table, my 'passwd' field is set to varchar(255) [I've read that's required for some reason].
When I use my default baked 'add' and 'edit' methods, the password is stored in plain text, and not hashed. The ONLY way I've found to get around this is to create a custom method in the AccountsTable class then call it using this kludge:
$this->request->data['passwd'] = $this->Accounts->hashPassword($this->request->data['passwd']);
My Auth component looks like this...
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Accounts',
'action' => 'login'
],
'authError' => 'Unauthorized Access',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'passwd'
],
'userModel'=>'Accounts'
]
]
]);
Is there a way to do this without dinking around with the raw request data?
Your mutator is named wrongly, the convention for mutators is _set followed by the camel cased field/property name. So since your field name is passwd, not password, it has to be named _setPasswd instead.
protected function _setPasswd($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
See also Cookbook > Entities > Accessors & Mutators