Giter Club home page Giter Club logo

yii2-auth's Introduction

Auth Module

Auth Module is a flexible user registration, authentication & RBAC module for Yii2. It provides user authentication, registration and RBAC support to your Yii2 site.

Installation

The preferred way to install this extension is through composer.

Either run

$ php composer.phar require robregonm/yii2-auth "*"

or add

"robregonm/yii2-auth": "*"

to the require section of your composer.json file.

Usage

Once the extension is installed, modify your application configuration to include:

return [
	'modules' => [
	    ...
	        'auth' => [
	            'class' => 'auth\Module',
	            'layout' => '//homepage', // Layout when not logged in yet
	            'layoutLogged' => '//main', // Layout for logged in users
	            'attemptsBeforeCaptcha' => 3, // Optional
	            'supportEmail' => '[email protected]', // Email for notifications
	            'passwordResetTokenExpire' => 3600, // Seconds for token expiration
	            'superAdmins' => ['admin'], // SuperAdmin users
	            'signupWithEmailOnly' => false, // false = signup with username + email, true = only email signup
	            'tableMap' => [ // Optional, but if defined, all must be declared
	                'User' => 'user',
	                'UserStatus' => 'user_status',
	                'ProfileFieldValue' => 'profile_field_value',
	                'ProfileField' => 'profile_field',
	                'ProfileFieldType' => 'profile_field_type',
	            ],
	        ],
	    ...
	],
	...
	'components' => [
	    ...
		'authManager' => [
			'class' => '\yii\rbac\DbManager',
			'ruleTable' => 'AuthRule', // Optional
			'itemTable' => 'AuthItem',  // Optional
			'itemChildTable' => 'AuthItemChild',  // Optional
			'assignmentTable' => 'AuthAssignment',  // Optional
		],
		'user' => [
			'class' => 'auth\components\User',
			'identityClass' => 'auth\models\User', // or replace to your custom identityClass
			'enableAutoLogin' => true,
		],
	    ...
	]
];

And run migrations:

$ php yii migrate/up --migrationPath=@auth/migrations

License

Auth module is released under the BSD-3 License. See the bundled LICENSE.md for details.

#INSTALLATION

./yii migrate/up --migrationPath=@auth/migrations

URLs

  • Login: yourhost/auth/default/login
  • Logout: yourhost/auth/default/logout
  • Sign-up: yourhost/auth/default/signup
  • Reset Password: yourhost/auth/default/reset-password
  • User management: yourhost/auth/user/index
  • User profile: yourhost/auth/profile/view

Flattr this git repo

yii2-auth's People

Contributors

cansozeri avatar djfly avatar fwerner13 avatar matyunya avatar mikebelozorov avatar robregonm avatar youanden 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-auth's Issues

Calling unknown method: yii\web\User::getIsSuperAdmin()

I am a newbie to Yii so please pardon me if its really something stupid

Login:
Logout:
Sign-up:
Reset Password:

are working fine for me. But when i am trying to access "User management", it throws me this error

Calling unknown method: yii\web\User::getIsSuperAdmin()

vendor\robregonm\yii2-auth\controllers\UserController.php – yii\base\Component::__call('getIsSuperAdmin', []) at line 32
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'matchCallback' => function () {
return \Yii::$app->user->getIsSuperAdmin();
},
],
],
],
];
}

I checked the User.php, it has a function named "can" but nothing like getIsSuperAdmin.

P.S. The links you have given are not working in the pattern mentioned in Readme.md, instead they are working like this

yourhost/web/index.php?r=auth/default/login

can not update user status

Hello,

Thanx for great module.

I can not update user status when I use the actionUpdate controller, Nothing happend and status not changed after I submit the form. I think I have to add a setAttribute in the controller or something else, because load($_post) is not update the $model->status. What can I do that ?? Am I missing something ??

By the way I added the auth role code in your update and create controllers, because I could not find a class for that in your module as shown below. Is it the right way to do this ??

Regards,

public function actionUpdate($id){

        $model = $this->findModel($id);

    if ($model->load($_POST) && $model->save()) {

        /*Auth Role save*/
        $authManager=new DbManager;

        /*Control Role Type if exists assign*/
        $sonuc = $authManager->getRole($_POST['User']['role']);

        if($sonuc!==null)
        {
            $authManager->revokeAll($model->id);
            $authManager->assign($sonuc,$model->id);
        }

        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

Not hashing password when creating user from admin view

Hi,

When we try to create a user from admin view /auth/user/create the method actionCreate of UserController is not hashing the password so we can't save it for the first time.

When we update user at /auth/user/update the method actionUpdate have the correct code so we can save password hashed at database.

if (isset($_POST['User']['password'])) {
$model->setPassword($_POST['User']['password']);
}

Calling unknown method: auth\components\User::checkAccess()

In class auth\components\User
I can only work like this

public function checkAccess($operation, $params = [], $allowCaching = true)
{
        // Always return true when SuperAdmin user
        if ($this->getIsSuperAdmin()) {
            return true;
        }
        return parent::can($operation, $params, $allowCaching);
}

not

public function checkAccess($operation, $params = [], $allowCaching = true)
{
        // Always return true when SuperAdmin user
        if ($this->getIsSuperAdmin()) {
            return true;
        }
        return parent::checkAccess($operation, $params, $allowCaching);
}

Questions on Overriding/Extending the auth\models\User model

I am working with schema that has already been defined and populated (hence profile attributes are not currently possible) and am trying to override the rules() function without changing anything in the vendor folder.

I am using the advanced yii2 beta organization and have attempted a variety of configurations (passing a different identity class), forcing my User model at common/models as well as backend/models to an edited copy of your auth\models\User class with no luck.

I'm excited by the organization of Yii and PHP 5.4s array syntax that would let me write rules like

public function rules()
{
  return [
    ['first_name', 'required']
  ] + parent::rules();
}

Is there a way you know of where I can override your User model class?

Thank you for your time.

Cannot open index, got invalid table name

Database Exception – yii\db\Exception

SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ''
The SQL being executed was: SHOW FULL COLUMNS FROM ``
Error Info: Array
(
[0] => 42000
[1] => 1103
[2] => Incorrect table name ''
)

Caused by: PDOException

SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ''

requested query
SHOW FULL COLUMNS FROM ``

config:
'modules' => [
'gii' => 'yii\gii\Module',
'auth' => [
'class' => 'auth\Module',
'layout' => '//homepage', // Layout when not logged in yet
'layoutLogged' => '//main', // Layout for logged in users
'attemptsBeforeCaptcha' => 3, // Optional
'supportEmail' => '[email protected]', // Email for notifications
'passwordResetTokenExpire' => 3600, // Seconds for token expiration
'superAdmins' => ['admin'], // SuperAdmin users
'tableMap' => [ // Optional, but if defined, all must be declared
'User' => 'user',
'UserStatus' => 'user_status',
'ProfileFieldValue' => 'profile_field_value',
'ProfileField' => 'profile_field',
'ProfileFieldType' => 'profile_field_type',
],
],
],

components:
'user' => [
'class' => 'auth\components\User',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
'ruleTable' => 'AuthRule',
'itemTable' => 'AuthItem',
'itemChildTable' => 'AuthItemChild',
'assignmentTable' => 'AuthAssignment',
'defaultRoles' => ['guest'],
],

install failed

php composer.phar require robregonm/yii2-auth "*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for robregonm/yii2-auth * -> satisfiable by robregonm/yii2-auth[0.5.0].
- robregonm/yii2-auth 0.5.0 requires yiisoft/yii2-composer dev-master -> no matching package found.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

Can not install, got error when applying db tables migration

Can not install, got error when applying db tables migration. Please, help with detailed instructions.
These are console outputs.
$ yii migrate/up --migrationPath=@auth/migrations
Yii Migration Tool (based on Yii v2.0.0-dev)

Total 2 new migrations to be applied:
m000000_000001_CreateRbacTables
m000000_000002_CreateUserTables

Apply the above migrations? (yes|no) [no]:yes
* applying m000000_000001_CreateRbacTables
> execute SQL: /

drop table if exists auth_assignment ... done (time: 0.001s)
> execute SQL:
drop table if exists auth_item_child ... done (time: 0.001s)
> execute SQL:
drop table if exists auth_item ... done (time: 0.001s)
> execute SQL:

create table auth_item
(
name varchar(64) not null,
type integer not null,
description text,
biz_rule text,
data text,
primary key (name),
key type (type)
) engine InnoDB ... done (time: 0.447s)
> execute SQL:

create table auth_item_child
(
parent varchar(64) not null,
child varchar(64) not null,
primary key (parent,child),
foreign key (parent) references auth_item (name) on delete cascade on u
pdate cascade,
foreign key (child) references auth_item (name) on delete cascade on up
date cascade
) engine InnoDB ... done (time: 0.399s)
> execute SQL:

create table auth_assignment
(
item_name varchar(64) not null,
user_id integer not null,
biz_rule text,
data text,
primary key (item_name,user_id),
foreign key (item_name) references auth_item (name) on delete cascade o
n update cascade
) engine InnoDB ... done (time: 0.243s)
*** applied m000000_000001_CreateRbacTables (time: 1.144s)

*** applying m000000_000002_CreateUserTables
Exception: Trying to get property of non-object (D:\vhosts\helpdesk\vendor\robre
gonm\yii2-auth\migrations\m000000_000002_CreateUserTables.php:9)
#0 D:\vhosts\helpdesk\vendor\yiisoft\yii2\console\controllers\MigrateController.

php(513): yii\db\Migration->up()
#1 D:\vhosts\helpdesk\vendor\yiisoft\yii2\console\controllers\MigrateController.

UserController access controll

I think there is a big security problem, that the full userController has not access control. In this case anybody could change all of the users' log-in name and password.

I inserted the following to require user to log-in

// name space
use yii\filters\AccessControl;
// access controll
'access' => [
            'class' => AccessControl::className(),
                'rules' => [
                       [
                           'actions' => ['index','view','update','delete','create'],
                           'allow' => true,
                           'roles' => ['@'],
                      ],
                 ],
            ],

Exception 'yii\db\Exception' with message 'could not find driver'

Saludos Ingeniero.

Estoy tratando de instalar tu extensión, sin embargo cuando trato de correr la rutina de actualizacion de la base de datos con el comando yii migrate/up --migrationPath=@auth/migrations aparece el error anterior.

Estoy trabajando con una base de datos postgresql bajo Windows con el entorno de desarrollo WAMP.

run yii migrate have error

Welcome to Git (version 1.8.1.2-preview20130201)

Run 'git help git' to display the help index.
Run 'git help ' to display help for specific commands.
dsf@DSF-PC ~
$ cd d:/xampp/htdocs/a
dsf@DSF-PC /d/xampp/htdocs/a
$ php yii migrate/up --migrationPath=@auth/migrations
Yii Migration Tool (based on Yii v2.0.0-dev)

Total 2 new migrations to be applied:
m000000_000001_CreateRbacTables
m000000_000002_CreateUserTables

Apply the above migrations? (yes|no) [no]:yes
*** applying m000000_000001_CreateRbacTables
Exception: Unknown component ID: authManager (D:\xampp\htdocs\a\vendor\yiisoft\y
ii2\di\ServiceLocator.php:135)
#0 D:\xampp\htdocs\a\vendor\robregonm\yii2-auth\migrations\m000000_000001_Create

RbacTables.php(14): yii\di\ServiceLocator->get('authManager')
#1 D:\xampp\htdocs\a\vendor\yiisoft\yii2\db\Migration.php(65): m000000_000001_Cr

eateRbacTables->safeUp()
#2 D:\xampp\htdocs\a\vendor\yiisoft\yii2\console\controllers\MigrateController.p

hp(512): yii\db\Migration->up()
#3 D:\xampp\htdocs\a\vendor\yiisoft\yii2\console\controllers\MigrateController.p

hp(181): yii\console\controllers\MigrateController->migrateUp('m000000_000001_..
.')
#4 [internal function]: yii\console\controllers\MigrateController->actionUp(0)
#5 D:\xampp\htdocs\a\vendor\yiisoft\yii2\base\InlineAction.php(54): call_user_fu

nc_array(Array, Array)
#6 D:\xampp\htdocs\a\vendor\yiisoft\yii2\base\Controller.php(127): yii\base\Inli

neAction->runWithParams(Array)
#7 D:\xampp\htdocs\a\vendor\yiisoft\yii2\console\Controller.php(83): yii\base\Co

ntroller->runAction('up', Array)
#8 D:\xampp\htdocs\a\vendor\yiisoft\yii2\base\Module.php(434): yii\console\Contr

oller->runAction('up', Array)
#9 D:\xampp\htdocs\a\vendor\yiisoft\yii2\console\Application.php(164): yii\base\

Module->runAction('migrate/up', Array)
#10 D:\xampp\htdocs\a\vendor\yiisoft\yii2\console\Application.php(140): yii\cons

ole\Application->runAction('migrate/up', Array)
#11 D:\xampp\htdocs\a\vendor\yiisoft\yii2\base\Application.php(339): yii\console

\Application->handleRequest(Object(yii\console\Request))
#12 D:\xampp\htdocs\a\yii(30): yii\base\Application->run()
#13 {main}

*** failed to apply m000000_000001_CreateRbacTables (time: 0.124s)

Migration failed. The rest of the migrations are canceled.
dsf@DSF-PC /d/xampp/htdocs/a
$

Profile status update

Profile scenario missing 'status'. Without status field you'll not be able to disable user or suspend or reactivate though admin interface

public function scenarios()
{
    return [
        'profile' => ['username', 'email', 'password_hash', 'password'],
        'resetPassword' => ['password_hash'],
        'requestPasswordResetToken' => ['email'],
        'login' => ['last_visit_time'],
    ] + parent::scenarios();
}

Really need RBAC

Any chance that RBAC functionality will ever be published in this extension? I truly cannot believe that Yii 2.0 was ever pushed out the door with full RBAC functionality. At this point, there is no way to utilize it in any kind of production environment where you virtually universally have users with varying levels of permissions/roles/etc. I had really hoped that Yii2 would be useful, but at this point, without any viable authorization control, it just isn't. (And no, doing access control by whether someone is logged in or not isn't viable access control. That's a joke.)

What should be stored in profieField?

Hy Robregonm!

After I run migrate I get these new tables:
ProfileFieldType, ProfileField, ProfileFieldValue

Could you give me some details about how this structure works?
It is works as a dynamically configurable profile by each user?

Thanks in advanced!
monghuz

No existen mensajes en español en vista de registro "sign up"

Cambios a realizar.

  1. Crear mensajes en messages/es/auth.user.php
Variable Traducción
Sign up Registrarse
Already registered? Sign in! Ya esta registrado? Ingress aquí!
  1. Llamar mensajes en el modelo SignupForm
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => Yii::t('auth.user', 'Username'),
            'email' => Yii::t('auth.user', 'Email'),
            'password_hash' => Yii::t('auth.user', 'Password Hash'),
            'password_reset_token' => Yii::t('auth.user', 'Password Reset Token'),
            'auth_key' => Yii::t('auth.user', 'Auth Key'),
            'status' => Yii::t('auth.user', 'Status'),
            'last_visit_time' => Yii::t('auth.user', 'Last Visit Time'),
            'create_time' => Yii::t('auth.user', 'Create Time'),
            'update_time' => Yii::t('auth.user', 'Update Time'),
            'delete_time' => Yii::t('auth.user', 'Delete Time'),
        ];
    }
  1. Llamar mensajes en view signup
$this->title = \Yii::t('auth.user', 'Sign up');
...
<?= Html::submitButton(\Yii::t('auth.user', 'Sign up'), ['class' => 'btn btn-success btn-block']) ?>
...
 <?= Html::a(\Yii::t('auth.user', 'Already registered? Sign in!'), ['/auth/default/login']) ?>

twig extends main.htm

Hi,

I want to use twig and your project is in vendor folder, but I want to extend my main.htm in login.htm from the root views folder. But when I use extend in twig it always call your current folder. Do you add a folder path to your module, how can I change it to extend a file from root not your current folder

file_get_contents(/var/www/crm/vendor/robregonm/yii2-auth/views/default/main.htm): failed to open stream: No such file or directory

I want this /var/www/crm/views/site/main.htm

Thanx ..

problem on install composer

i have try install but have this error :
C:\xampp\htdocs\newtest>php composer.phar require robregonm/yii2-auth "dev-maste
r"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package robregonm/yii2-auth 1.0.0 could not be found.
Problem 2
- Installation request for robregonm/yii2-auth dev-master -> satisfiable by
robregonm/yii2-auth[dev-master].
- robregonm/yii2-auth dev-master requires yiisoft/yii2-composer dev-master -

no matching package found.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common
problems.

Installation failed, reverting ./composer.json to its original content.

missing view file

I have noticed missing view file like resetpassword and register page.

Is that intentional?

Thanks

Class 'auth\models\ProfileFieldValue' not found

Hi if I call $model->getProfileFieldValue() function, I get fatal error Class 'auth\models\ProfileFieldValue' not found .. What can I do for this and how can I load profile relational data for the user in your project ?

search module

Hi,

I have sarch the database with your form type and your function addCondition adds additional slashes into the mysql code as shown below, so no result founds.

SELECT COUNT(*) FROM user WHERE username LIKE '%%cansozeri%%'

The mysql query has to be like this

SELECT COUNT(*) FROM user WHERE username LIKE '%cansozeri%'

I think this is the code that can be change ..

$value = '%' . strtr($value, ['%'=>'%', '_'=>'_', ''=>'\']) . '%';

override controller

silly question.
I want to override the controller how to do it right?
i write:
namespace app\controllers;
use auth\models\PasswordResetRequestForm;
use auth\models\ResetPasswordForm;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\helpers\Security;
use auth\models\LoginForm;
use auth\models\User;
class LoginController extends auth\controllers\DefaultController {
//put your code here
public function actionLogin() {
parent::actionLogin();
}
and got error "Class 'app\controllers\auth\controllers\DefaultController' not found"

Forbidden (#403) when try access to /auth/user/index

Cuando trato de ingresar a la vista de administracion de usuarios /auth/user/index luego de haber ingresado a la app como administrador obtengo el mensaje que no tengo permitido dicha accion. Donde configuro los modelos a los que puede tener acceso cada usuario.

Pido disculpas por las preguntas recurrentes - y si parecen ser tontas - pero estoy tratando de entender la lógica del sistema de autenticacion basado en roles RBAC. Gracias por tu apoyo!

waiting for admin interfaces

Hi,
waiting for admin interfaces can you give me some note about how to fill the auth_db tables?

Thank you
Jack

"User" instead of "user" name table when running db migration at install

Al momento de correr la rutina de actualización de base de datos de yii para postgresql se crea una tabla con el nombre [User] en vez de [user] provocando un error cuando se trata de consultar el usuario valido para hacer login a la aplicación utilizando la ruta: [http://localhost/basic/web/index.php?r=auth/default/login]. Cree directamente una copia de la tabla con el nombre [user] junto con el usuario inicial que sea crea por defecto para continuar con la prueba de tu extensión.

Unable to install

Try to install on yii2 fresh installation, basic template.

composer require robregonm/yii2-auth "dev-master"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for robregonm/yii2-auth dev-master -> satisfiable by robregonm/yii2-auth[dev-master].
- robregonm/yii2-auth dev-master requires yiisoft/yii2-swiftmailer dev-master -> no matching package found.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

Session time

Hi Ricardo,
How can I set the session time out? like 1800 or 3600 seconds
In this moment on my app the session is always open.
Thank you so much!

The password is not updated

Hello,

When I update the user, everything can be updated but password not, I investigate the logs with yii debug and there is no db request for password update.

Manage RBAC via interface?

Hello,

I have finally got the extension functional and now I wanted to know the use of auth_assignment, auth_item, auth_item_child, auth_rule tables that were created with migration tool as I dont see any interface to manage these.

What Paths Are Used

I got the extension installed, migrated up successfully, and made the changes to my config as indicated in your instructions. Now, for the life of me, I can't figure out how to use the functionality of the extension. Specifically, I can't find how to even get to the login page. I've tried the following:

  • advanced.dev/login
  • advanced.dev/user/login
  • advanced.dev/auth/login
  • advanced.dev/auth/user/login

They all produce a 404 error. Similarly, all of the following produce 404 errors:

  • advanced.dev/auth
  • advanced.dev/user

Your installation instructions give fairly scanty directions on how to install; I was successful in doing that only after figuring out and completing many other steps not included in the instructions. Could you possibly provide some support on where to go after installation? I'd like to at least be able to log in and manage users.

Also the tables created as part of the migrations for this extension seem to suggest some sort of ACL, but I can find anything for the management of ACL in the extension. Am I missing something?

Time Zones

Need column time_sone for user table.
That column will be have time zone for only just registrated users.

Bad Request (#400) on logout session

Since 2 days ago , when I refreshed my yii2 project via composer I can't logout with yii2-auth.

All other function seams good, but when I try to logout I get the followin error:
yii\web\HttpException:400

Here is the error stack from yii debugger:

exception 'yii\web\BadRequestHttpException' with message 'Unable to verify your data submission.' in C:\xampp-portable\htdocs\yii2\vendor\yiisoft\yii2\web\Controller.php:109
Stack trace:
#0 C:\xampp-portable\htdocs\yii2\vendor\yiisoft\yii2\base\Controller.php(146): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 C:\xampp-portable\htdocs\yii2\vendor\yiisoft\yii2\base\Module.php(429): yii\base\Controller->runAction('logout', Array)
#2 C:\xampp-portable\htdocs\yii2\vendor\yiisoft\yii2\web\Application.php(82): yii\base\Module->runAction('auth/default/lo...', Array)
#3 C:\xampp-portable\htdocs\yii2\vendor\yiisoft\yii2\base\Application.php(367): yii\web\Application->handleRequest(Object(yii\web\Request))
#4 C:\xampp-portable\htdocs\yii2\web\index.php(12): yii\base\Application->run()
#5 {main}

I tried to find the root of this error without success. :(

Adding Roles when create edit or view users

Ok now I propose to add roles in your code, because when we create or edit users, we should add or update roles to user.

Now I have added this functions in your user model.

/**
    Return user Roles
    **/
    public function getRole($id = null)
    {
        /** @var \yii\rbac\DbManager $authManager */
        $authManager = Yii::$app->get('authManager');

        if($id===null)
        {

            $Ridentity = $authManager->getRolesByUser($this->id);

        }
        else
        {
            $Ridentity = $authManager->getRolesByUser($id);
        }

        if($Ridentity)
        {
            foreach ($Ridentity as $item)
            {
               $role[$item->name] = $item->name;

            }
        }
        else
        {
            $role=null;
        }


        return $role;

    }

    function getRoleArray()
    {
        return implode(',', $this->role);
    }

    public function getRoleTypes()
    {
        /** @var \yii\rbac\DbManager $authManager */
        $roller = Yii::$app->get('authManager')->getRoles();

        foreach ($roller as $item)
        {
           $role[$item->name] = $item->name;

        }


        return $role;
    }

function getRoleTypes
=>Retrieve the roles from database, so we can use it to fill multiple select field when we create user.

function getRoleArray
=>Return roles to a string when we view the user.

function getRole
=>Retrieve the roles of the user, view and update pages.

form.php (create and update)

<?= $form->field($model, 'role')->dropDownList($model->RoleTypes,['multiple' => true])?>

and view.php

<?php echo DetailView::widget([
        'model' => $model,
        'attributes' => [
            //'id',
            'username',
            'email:email',
            'password_hash',
            'password_reset_token',
            'auth_key',
            [
                'attribute' => 'status',
                'value' => $model->getStatus()
            ],
            [
                'attribute' => 'role',
                'value' => $model->getRoleArray()
            ],
            'last_visit_time',
            'create_time',
            'update_time',
            'delete_time',
        ],
    ]); ?>

and in user controller a function to create or update roles

protected function setRole($id,$roles)
    {
        if(!empty( $roles ))
        {
            /** @var \yii\rbac\DbManager $authManager */
            $authManager = \Yii::$app->get('authManager');

            $authManager->revokeAll($id);

            foreach ($roles as $item)
            {
               $r = $authManager->createRole($item);
               $authManager->assign($r,$id);

            }
        }
        else
        {
            throw new NotFoundHttpException('Bad Request.');
        }

    }

//usage
$this->setRole($id,$_POST['User']['role']);

What do you think ??

I am using this code now and I can create update and view roles of the user within your pages view.php, create.php and update.php.

If you provide a simple or more proper way, I will be very greatfull, but I think we should create or update role of the user when we use your create or update user form at the same time ..

delete user

When you delete user, you just set the delete time, but dont set the status.

And because of the status is reamin active, the deleted user can login.
I add one row to UserController which set status when delete user.

public function delete()
{
    $db = static::getDb();
    $transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
    try {
        $result = false;
        if ($this->beforeDelete()) {
            $this->setAttribute('status', static::STATUS_DELETED);
            $this->save(false);
        }

migration errors

** applying m000000_000001_CreateRbacTables
Exception: Unknown component ID: authManager (/var/www/weekendtrip/vendor/yiisoft/yii2/di/ServiceLocator.php:136)

on console config needs add this:
'authManager' => [
'class' => 'yii\rbac\DbManager',
],

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.