Yii2 REST API BasicAuth not working - yii2

Im implementing REST API Authentication module as following step
1. Create user by Admin
2. First tim: login by Basic Auth to return access_token
3. Use access_token at step 2 to Auth user by. QueryParamAuth
as this instruction it work with QueryParamAuth
https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md
But it not work at step2. Auth by BasicAuth
I debug it. $this->auth always return null. Although $username and $password right
class HttpBasicAuth extends AuthMethod
/**
* #var callable a PHP callable that will authenticate the user with the HTTP basic auth information.
* The callable receives a username and a password as its parameters. It should return an identity object
* that matches the username and password. Null should be returned if there is no such identity.
*
* The following code is a typical implementation of this callable:
*
* ```php
* function ($username, $password) {
* return \app\models\User::findOne([
* 'username' => $username,
* 'password' => $password,
* ]);
* }
* ```
*
* If this property is not set, the username information will be considered as an access token
* while the password information will be ignored. The [[\yii\web\User::loginByAccessToken()]]
* method will be called to authenticate and login the user.
*/
public $auth;
public function authenticate($user, $request, $response)
{
$username = $request->getAuthUser();
$password = $request->getAuthPassword();
if ($this->auth) {
if ($username !== null || $password !== null) {
$identity = call_user_func($this->auth, $username, $password);
var_dump($identity);
die();
if ($identity !== null) {
$user->switchIdentity($identity);
} else {
$this->handleFailure($response);
}
return $identity;
}
} elseif ($username !== null) {
$identity = $user->loginByAccessToken($username, get_class($this));
if ($identity === null) {
$this->handleFailure($response);
}
return $identity;
}
return null;
}
My question is how can i implement $this->auth function?

HTTP Basic Auth
// controller code
Way 1: user Auth using auth-token
use yii\filters\auth\HttpBasicAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
Above code will validate user by access token (as mentioned in the doc)
when window prompts to enter username & password
username: hErEaccE55T0ken
password:
Way 2:
To implement custom auth using username & password, sample code (chris code works)
i m using user_email, user_password
public $user_password;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
return $behaviors;
}
/**
* Finds user by user_email and user_password
*
* #param string $username
* #param string $password
* #return static|null
*/
public function Auth($username, $password) {
// username, password are mandatory fields
if(empty($username) || empty($password))
return null;
// get user using requested email
$user = \app\models\User::findOne([
'user_email' => $username,
]);
// if no record matching the requested user
if(empty($user))
return null;
// hashed password from user record
$this->user_password = $user->user_password;
// validate password
$isPass = \app\models\User::validatePassword($password);
// if password validation fails
if(!$isPass)
return null;
// if user validates (both user_email, user_password are valid)
return $user;
}

I implement HttpBasicAuth->auth in my controller where I attach HttpBasicAuth as a behavior like so:
class MyController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
]
return $behaviors;
}
public function auth($username, $password)
{
// Do whatever authentication on the username and password you want.
// Create and return identity or return null on failure
}
// ... Action code ...
}

Related

Yii2 validate password in for RESTapi

If you do not use a password, the REST request passes. Otherwise, you get an error:
Error:
"name": "Unauthorized",
"message": "Your request was made with invalid credentials.",
"code": 0,
"status": 401,
"type": "yii\\web\\UnauthorizedHttpException"
Access in User model:
public static function findIdentityByAccessToken($username, $password = null)
{
// throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
//return static::findOne(['username' => $username]);
$user = static::findOne(['username' => $username]);
if ($user != null and $user->validatePassword($password)) {
return $user;
} else {
return null;
}
}
And validatePassword function:
public function validatePassword($password)
{
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
}
How to authenticate?
REST APIs work usually by authenticating using tokens. There are different types of auth tokens. This example is using basic auth:
Controller
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
You then need to add a authorization header to your request with the value
Basic base64_encode(username:password)

Login access not working in yii2

Im using yii2 for my project. I need to use two different tables for login (Login page is same). I have two models Admin and User. And i have one LoginFrom for login.
I can login properly but the problem is after logged in i cannot get whether the admin is logged in or the user is logged in.
I have set it in config file (web.php) like below:
'admin' => [
'identityClass' => 'app\models\Admin',
'enableAutoLogin' => false,
'class' => 'yii\web\User',
'authTimeout' => 1200, // in Seconds. 1200 seconds means 20 mins
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'authTimeout' => 1200
],
So im getting logged in user details by using below method:
\Yii::$app->admin->identity;
\Yii::$app->user->identity;
My problem is if im logged in as admin i can get user values also by using this : \Yii::$app->user->identity; or if im logged in as user i can get admin values by using this : \Yii::$app->admin->identity;.
My LoginForm.php is :
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login()
{
if ($this->validate()) {
if(!empty($this->getUser()['phone_number'])) {
return Yii::$app->admin->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
}
return false;
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
if(!$this->_user) {
$this->_user = Admin::findByUsername($this->username);
}
}
return $this->_user;
}
}
I cant find the problem and if i logged in identity creating for both the users so i could'nt write access rules in particular controller to allow admin only to access the controller.Please help me :(
From reading the comments I think you should just create a unifying table for the two identities where they both get their IDs from. Then make that the identity class. The reason you are able to see the details in both identity classes is that they have the same ID.

Yii2 basic validate password

on my users controller I create to use it like registration, I create
public function actionCreate()
{
$model = new Userlogin();
$model->password = null;
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
It's work , it hash the password , but I don't know how to validate the password and make it work in login I did read that I have to use this
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
but I don't know how to use it or where I have to use it
create new action , name it login
be sure to get user hash password from db
public function actionLogin() {
$hash = User::find()->where('username='.$_POST['username'])->One();
if (Yii::$app->getSecurity()->validatePassword($_POST['password'], $hash->password_hash)) {
// all good, logging user in
} else {
// wrong password
}
}
I found the solution for someone if he is in the same situation
in create action
public function actionCreate()
{
$model = new Userlogin();
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->security->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and in user model change
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
to
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}
this solution from : https://stackoverflow.com/a/29508651/6562828
I'm using Userlogin as model for user but if anyone is using User model it's in user model
IMHO, the code :
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
can be used for POST method when user do login, and inside "// all good, logging user in", you will do something with Web Session, saving session for specify user, then yay, user logged in,
after that, you can use Session for checking, "is user are logged in ?", etc,
here some good link about Yii Session Handling : http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html

Yii: How to validatePassword with Edvlerblog\Adldap2 using userprincipalname instead of samaccountname

Question
Currently looking for how other people handled the validate password function when they need to authenticate with the userprincipalname instead of the Edvlerblog\Adldap2 validatePassword function which uses samaccountname.
Please provide feedback in the comments if you are struggling with
anything specific so we can update the documentation.
Current Implementation
For app/common/model/LoginForm
getUser
The Edvlerblog\Adldap2 getUser() function works, and even caches the queryLdapUserObject, allowing you to fetch any of the AD attributes.
protected function getUser()
{
if ($this->_user === null) {
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
}
return $this->_user;
}
validatePassword()
Currently, the following validatePassword function does not work for me because in my instance AD must authenticate against the userprincipalname instead of the samaccount name.
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
A solution
Here is one workaround thanks to the Edvlerblog\Adldap2 who recently released 3.0.5 addressing a couple issues and providing some examples in his readme docs.
Please note the addition of findByAttribute(), allowing the following:
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
validatePassword() w/ userprincipalname
Update your login model: common\models\LoginForm.php
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user) {
$this->addError('username', 'Incorrect username.');
} else {
// Note: queryLdapUserObject is a cached object,
// so the ldap fetch does not get called :-).
$userprincipalname = $this->_user->queryLdapUserObject()->getAttribute('userprincipalname');
$auth = Yii::$app->ad->auth()->attempt($userprincipalname[0], $this->password);
if (!$auth) {
$this->addError('password', 'Incorrect password.');
}
}
}
}
getUser() w/userprincipalname
/**
* Finds user by [[username]]
*
* #return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
}
return $this->_user;
}
Yii2 ldap Component Configuration
Reference: https://github.com/Adldap2/Adldap2/blob/master/docs/configuration.md
Config in your frontend\config\main:
'components' => [
'log' => [... ],
'authManager' => [... ],
'ad' => [
'class' => 'Edvlerblog\Adldap2\Adldap2Wrapper',
'providers' => [
'default' => [
'autoconnect' => true,
'config' => [
'domain_controllers' => ['your.ldap.domain.com'],
'base_dn' => "OU=XXX,OU=XXX,DC=ccccccc,DC=xxxx,DC=com",
'admin_username' => "your_username",
'admin_password' => "your_password",
'port' => 389,
],
],
],
],
],

Yii2 RBAC Multiple Assignments for Each User Based on Groups

My application technically has two areas, a global area (feedback, user profile, user settings, etc) and a group area (contacts, projects, group profile, group settings, etc).
I am using the RBAC DBManager for the global area, and it works just fine, but I am having issues implementing an authorization mechanism for the group area.
The reason, is that groups can be shared among the users, and a user may have multiple assignments in the group_access table (id, group_id, user_id, item_name) as they may be members of multiple groups, and they may have different permission levels for those groups.
Here is my auth setup:
$auth = Yii::$app->authManager;
// group permissions
$manageGroupUsers = $auth->createPermission('manage_group_users');
$manageGroupUsers->description = 'Manage Group Users';
$auth->add($manageGroupUsers);
$manageGroupSettings = $auth->createPermission('manage_group_settings');
$manageGroupSettings->description = 'Manage Group Settings';
$auth->add($manageGroupSettings);
// app permissions
$manageAppUsers = $auth->createPermission('manage_app_users');
$manageAppUsers->description = 'Manage App Users';
$auth->add($manageAppUsers);
$manageAppGroups = $auth->createPermission('manage_app_groups');
$manageAppGroups->description = 'Manage App Groups';
$auth->add($manageAppGroups);
$manageAppSettings = $auth->createPermission('manage_app_settings');
$manageAppSettings->description = 'Manage App Settings';
$auth->add($manageAppSettings);
$manageAppFeedback = $auth->createPermission('manage_app_feedback');
$manageAppFeedback->description = 'Manage App Feedback';
$auth->add($manageAppFeedback);
// group roles
// -- create role
$groupUser = $auth->createRole('group_user');
$groupUser->description = 'Group Users';
$auth->add($groupUser);
// -- create role
$groupAdmin = $auth->createRole('group_admin');
$groupAdmin->description = 'Group Administrators';
$auth->add($groupAdmin);
// add permissions
$auth->addChild($groupAdmin, $manageGroupUsers);
$auth->addChild($groupAdmin, $manageGroupSettings);
// inherit permissions
$auth->addChild($groupAdmin, $groupUser);
// -- create role
$groupCreator = $auth->createRole('group_creator');
$groupCreator->description = 'Group Creators';
$auth->add($groupCreator);
// inherit permissions
$auth->addChild($groupCreator, $groupAdmin);
// app roles
// -- create role
$appUser = $auth->createRole('app_user');
$appUser->description = 'App Users';
$auth->add($appUser);
// -- create role
$appSupport = $auth->createRole('app_support');
$appSupport->description = 'Support Users';
$auth->add($appSupport);
// add permissions
$auth->addChild($appSupport, $manageAppFeedback);
// -- create role
$appAdmin = $auth->createRole('app_admin');
$appAdmin->description = 'App Administrators';
$auth->add($appAdmin);
// add permissions
$auth->addChild($appAdmin, $manageAppUsers);
$auth->addChild($appAdmin, $manageAppGroups);
$auth->addChild($appAdmin, $manageAppSettings);
// inherit permissions
$auth->addChild($appAdmin, $appUser);
$auth->addChild($appAdmin, $appSupport);
// -- create role
$appCreator = $auth->createRole('app_creator');
$appCreator->description = 'App Creators';
$auth->add($appCreator);
// inherit permissions
$auth->addChild($appCreator, $appAdmin);
My group_access table has the same schema as the auth_assignment table, with the exception that it has a group_id column, and the user_id column is NOT unique.
The user will only have one assignment concerning the global area, but may have many different assigments on the group area as they might have admin privelidges on group a, but only user privielidges on group b.
My DB is set up like:
Users (status_id, username, auth_key, password_hash, email, etc)
Groups (status_id, name, description, etc)
Group_Access (group_id, user_id, item_name) Each user gets one assignment for each group they have access to.
sample_group_access_records [
[
'id' => 1,
'user_id' => 35,
'group_id' => 17,
'item_name' => 'group_admin'
],
[
'id' => 2,
'user_id' => 35,
'group_id' => 356,
'item_name' => 'group_user'
],
[
'id' => 3,
'user_id' => 35,
'group_id' => 211,
'item_name' => 'group_creator'
],
];
The checkAccess function can qualify the userID, and I can even use the shorter "can" version which works great for the logged in user, but I need to check access based on a user option like below:
Option::getOption('user', 'active_group_id')
This is a custom function that pulls the active group id from a user options table. If a user switches groups, this will be changed. My options model has three types 'app', 'user', 'group'.
It would be nice if I could figure out a function that works the same was as the native checkAccess but be called checkGroupAccess and automatically get the active_group_id and pull the user assignments from the group_access table and perform the permission check.
I hope this makes sense.
Thank you for your time.
Mike
** UPDATED **
So, I have a solution, that uses custom checkAccess functions to check for proper permissions on the group or global areas.
I have two tables (user_access, group_access) that have a similar schema to the default {{auth_assignment}} table, of which I am not using now. I am using the {{auth_item}}, {{auth_item_child}}, and {{auth_rule}} tables.
I have two models, one for each of the access tables GroupAccess => group_access, and UserAccess => user_access.
I also have a model for the access functions and have mapped it to the components configuration.
Here is my access model:
<?php
namespace app\models;
use Yii;
class Access
{
public function canUser($type, $permissionName, $params = [])
{
switch ($type) {
case 'group':
$userID = Yii::$app->user->identity->id;
$groupID = Yii::$app->options->getOption('user', 'active_group_id');
$queryAll = GroupAccess::find()
->where('user_id = :user_id and group_id = :group_id', [':user_id' => $userID, ':group_id' => $groupID])
->asArray()
->all();
$assignments = [];
foreach ($queryAll as $queryItem) {
$assignments[$queryItem['item_name']] = [
'userId' => $queryItem['user_id'],
'roleName' => $queryItem['item_name'],
'createdAt' => $queryItem['created_date'],
];
}
$result = self::checkAccess($userID, $permissionName, $assignments, $params);
return $result;
break;
case 'user':
$userID = Yii::$app->user->identity->id;
$queryAll = UserAccess::find()
->where(['user_id' => $userID])
->asArray()
->all();
$assignments = [];
foreach ($queryAll as $queryItem) {
$assignments[$queryItem['item_name']] = [
'userId' => $queryItem['user_id'],
'roleName' => $queryItem['item_name'],
'createdAt' => $queryItem['created_date'],
];
}
$result = self::checkAccess($userID, $permissionName, $assignments, $params);
return $result;
break;
}
}
public function checkAccess($userID, $permissionName, $assignments, $params = [])
{
$auth = Yii::$app->authManager;
$auth->loadFromCache();
if ($auth->items !== null) {
return $auth->checkAccessFromCache($userID, $permissionName, $params, $assignments);
} else {
return $auth->checkAccessRecursive($userID, $permissionName, $params, $assignments);
}
}
public function assign($type, $role, $userID = null, $groupID = null)
{
switch ($type) {
case 'group':
// clear existing assigments
self::revoke('group', $userID, $groupID);
$groupAccess = new GroupAccess();
$groupAccess->group_id = $groupID;
$groupAccess->user_id = $userID;
$groupAccess->item_name = $role;
$groupAccess->created_date = time();
return $groupAccess->save();
break;
case 'user':
// clear existing assignments
self::revoke('user', $userID);
$userAccess = new UserAccess();
$userAccess->user_id = $userID;
$userAccess->item_name = $role;
$userAccess->created_date = time();
return $userAccess->save();
break;
}
}
public function revoke($type, $userID, $groupID = null)
{
switch ($type) {
case 'group':
GroupAccess::deleteAll('user_id = :user_id and group_id = :group_id', [':user_id' => $userID, ':group_id' => $groupID]);
break;
case 'user':
UserAccess::deleteAll('user_id = :user_id', [':user_id' => $userID]);
break;
}
}
}
And here are some sample uses to access the functions:
// get the user option
echo Yii::$app->options->getOption('user', 'active_group_id');
// assign group role
Yii::$app->access->assign('group', 'group_creator', 22, 18);
// assign user role
Yii::$app->access->assign('user', 'app_user', 22);
// revoke group access
Yii::$app->access->revoke('group', 22, 18);
// revoke user access
Yii::$app->access->revoke('user', 22);
// test user permission
var_dump(Yii::$app->access->canUser('user', 'manage_app_settings'));
// test the group permission
var_dump(Yii::$app->access->canUser('group', 'manage_group_settings'));
In essence, I copied the checkAccess function from the DbManager and reworked it a little to check for user access based on group.
The only issue, is that I had to make a change to the actual source DbManager class to make the $items (property), checkAccessFromCache (function), and checkAccessRecursive (function) all public so they can be accessed outside of the class. The main drawback is updateability...
Any way around this?
Thanks.
Here is a working final solution.
So, another day, more refactoring.
My final solution uses the checkAccess function in the DbManager/ManagerInterface source files, but I added the $assignments parameter to be passed. The main issue is that I had to build my own assignments list for checking. Make sure you comment out the lines where the $assignments variable is set.
Here is my new access model:
<?php
namespace app\models;
use Yii;
class Access
{
public function canUser($type, $permissionName, $params = [])
{
$auth = Yii::$app->authManager;
switch ($type) {
case 'group':
$userID = Yii::$app->user->identity->id;
$groupID = Yii::$app->options->getOption('user', 'active_group_id');
$queryAll = GroupAccess::find()
->where('user_id = :user_id and group_id = :group_id', [':user_id' => $userID, ':group_id' => $groupID])
->asArray()
->all();
$assignments = [];
foreach ($queryAll as $queryItem) {
$assignments[$queryItem['item_name']] = [
'userId' => $queryItem['user_id'],
'roleName' => $queryItem['item_name'],
'createdAt' => $queryItem['created_date'],
];
}
$result = $auth->checkAccess($userID, $permissionName, $assignments, $params);
return $result;
break;
case 'user':
$userID = Yii::$app->user->identity->id;
$queryAll = UserAccess::find()
->where('user_id = :user_id', [':user_id' => $userID])
->asArray()
->all();
$assignments = [];
foreach ($queryAll as $queryItem) {
$assignments[$queryItem['item_name']] = [
'userId' => $queryItem['user_id'],
'roleName' => $queryItem['item_name'],
'createdAt' => $queryItem['created_date'],
];
}
$result = $auth->checkAccess($userID, $permissionName, $assignments, $params);
return $result;
break;
}
}
public function assign($type, $role, $userID = null, $groupID = null)
{
switch ($type) {
case 'group':
// clear existing assigments
self::revoke('group', $userID, $groupID);
$groupAccess = new GroupAccess();
$groupAccess->group_id = $groupID;
$groupAccess->user_id = $userID;
$groupAccess->item_name = $role;
$groupAccess->created_date = time();
return $groupAccess->save();
break;
case 'user':
// clear existing assignments
self::revoke('user', $userID);
$userAccess = new UserAccess();
$userAccess->user_id = $userID;
$userAccess->item_name = $role;
$userAccess->created_date = time();
return $userAccess->save();
break;
}
}
public function revoke($type, $userID, $groupID = null)
{
switch ($type) {
case 'group':
GroupAccess::deleteAll('user_id = :user_id and group_id = :group_id', [':user_id' => $userID, ':group_id' => $groupID]);
break;
case 'user':
UserAccess::deleteAll('user_id = :user_id', [':user_id' => $userID]);
break;
}
}
}
And here is the modified checkAccess function in DbManager:
public function checkAccess($userId, $permissionName, $assignments, $params = [])
{
//$assignments = $this->getAssignments($userId);
$this->loadFromCache();
if ($this->items !== null) {
return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments);
} else {
return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
}
}
And here is the modified checkAccess function in ManagerInterface.php:
public function checkAccess($userId, $permissionName, $assignments, $params = []);
I did not change the $items, checkAccessFromCache, and checkAccessRecursive functions to public from protected.
And here is my UserAccess model:
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "app_user_access".
*
* #property integer $id
* #property integer $user_id
* #property string $item_name
* #property integer $created_date
*
* #property AppAuthItem $itemName
* #property AppUsers $user
*/
class UserAccess extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'app_user_access';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'item_name', 'created_date'], 'required'],
[['user_id', 'created_date'], 'integer'],
[['item_name'], 'string', 'max' => 64]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'item_name' => 'Item Name',
'created_date' => 'Created Date',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemName()
{
return $this->hasOne(AppAuthItem::className(), ['name' => 'item_name']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(AppUsers::className(), ['id' => 'user_id']);
}
}
And here is the the GroupAccess Model:
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "app_group_access".
*
* #property integer $id
* #property integer $group_id
* #property integer $user_id
* #property string $item_name
* #property integer $created_date
*
* #property AppUsers $user
* #property AppAuthItem $itemName
* #property AppGroups $group
*/
class GroupAccess extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'app_group_access';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['group_id', 'user_id', 'item_name', 'created_date'], 'required'],
[['group_id', 'user_id', 'created_date'], 'integer'],
[['item_name'], 'string', 'max' => 64]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'group_id' => 'Group ID',
'user_id' => 'User ID',
'item_name' => 'Item Name',
'created_date' => 'Created Date',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(AppUsers::className(), ['id' => 'user_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemName()
{
return $this->hasOne(AppAuthItem::className(), ['name' => 'item_name']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getGroup()
{
return $this->hasOne(AppGroups::className(), ['id' => 'group_id']);
}
}
And once again, some useful samples:
// assign group role
Yii::$app->access->assign('group', 'group_creator', 24, 20);
// assign user role
Yii::$app->access->assign('user', 'app_user', 24);
// revoke group
Yii::$app->access->revoke('group', 22, 18);
// revoke user
Yii::$app->access->revoke('user', 22);
// test user permission
var_dump(Yii::$app->access->canUser('user', 'manage_app_settings'));
// test the group permission
var_dump(Yii::$app->access->canUser('group', 'manage_group_settings'));