chieff / yii2-user-management-module
User with improved RBAC
Requires
- chieff/yii2-components: dev-master
- chieff/yii2-date-range-picker-widget: dev-master
- chieff/yii2-grid-bulk-actions-widget: dev-master
- chieff/yii2-grid-page-size-widget: dev-master
- ikimea/browser: 1.12.0
- kartik-v/yii2-widget-datetimepicker: *
- rmrevin/yii2-fontawesome: ~3.5
- webvimark/bootstrap-switch: ^1.0.0
- webvimark/helpers: ^1.0.0
This package is auto-updated.
Last update: 2024-04-22 09:55:00 UTC
README
Perks
- User management
- RBAC (roles, permissions and stuff) with web interface
- Registration, authorization, password recovery and so on
- Visit log (also with denied auths)
- Optimised (zero DB queries during usual user workflow)
- Nice widgets like GhostMenu or GhostHtml::a where elements are visible only if user has access to route where they point
- Ip blocking
Installation
The preferred way to install this extension is through composer.
Either run
composer require chieff/yii2-user-management-module
or add
"chieff/yii2-user-management-module": "dev-master"
to the require section of your composer.json
file.
Forked
It is a fork of webvimark module-user-management, so be sure that you are not using that module in require section of composer. This may have an impact because of this fork uses same namespaces. Also you can not use:
But don't be scared, this fork includes that packages but with another name for better working!
Configuration
- In your config/web.php
'components' => [ 'user' => [ 'class' => 'webvimark\modules\UserManagement\components\UserConfig', // Default values: // 'enableAutoLogin' => true, // 'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true], // 'loginUrl' => '/user-management/auth/login', // Comment this if you don't want to record user logins 'on afterLogin' => function($event) { \webvimark\modules\UserManagement\models\UserVisitLog::newVisitor($event->identity->id); } ], ], 'modules' => [ 'user-management' => [ 'class' => 'webvimark\modules\UserManagement\UserManagementModule', // Default values: // 'useEmailAsLogin' => false, // 'enableRegistration' => false, // 'inactiveUsersAfterRegistration' => false, // 'emailConfirmationRequired' => false, // 'userCanHaveMultipleRoles' => true, // 'freePasswordRecovery' => true, // 'freeEmailNotConfirmed' => false, // 'freeRecoveryMessagesIfEmailNotExists' => false, // 'maxAttempts' => 5, // 'attemptsTimeout' => 60, // 'blockUserViaAttempts' => true, // 'blockUserAttempts' => 5, // 'blockUserTime' => 86400, // 'logDeniedAuths' => false, // 'registrationFormClass' => 'webvimark\modules\UserManagement\models\forms\RegistrationForm', // 'registrationFormClassView' => '', // example: '@vendor\chieff\yii2-user-profile-module\views\auth\registration' // 'registrationFormScenario' => '', // 'profileModelClass' => '', // example: '\chieff\modules\UserProfile\models\UserProfile' // 'userCreatePath' => '', // example: '/user-profile/profile/create' // 'userUpdatePath' => '', // example: '/user-profile/profile/update' // 'userViewPath' => '', // example: '/user-profile/profile/view' // 'rolesAfterRegistration' => [], // type here roles that you want to use after registration by default // 'usePasswordGenerator' => true, // 'passwordGeneratorWithSymbols' => true, // 'passwordGeneratorLength' => 8, // Add regexp validation to passwords. Default pattern does not restrict user and can enter any set of characters. // The example below allows user to enter : // any set of characters // (?=\S{8,}): of at least length 8 // (?=\S*[a-z]): containing at least one lowercase letter // (?=\S*[A-Z]): and at least one uppercase letter // (?=\S*[\d]): and at least one number // $: anchored to the end of the string // 'passwordRegexp' => '^\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$', // Here you can set your handler to change layout for any controller or action // Tip: you can use this event in any module 'on beforeAction' => function(yii\base\ActionEvent $event) { if ($event->action->uniqueId == 'user-management/auth/login') { $event->action->controller->layout = 'loginLayout.php'; } }, ], ],
To learn about events check:
- http://www.yiiframework.com/doc-2.0/guide-concept-events.html
- http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format
Layout handler example in AuthHelper::layoutHandler()
To see full list of options check UserManagementModule file
- In your config/console.php (this is needed for migrations and working with console, skip this step if you use yii2-advanced)
'modules' => [ 'user-management' => [ 'class' => 'webvimark\modules\UserManagement\UserManagementModule', 'controllerNamespace' => 'vendor\webvimark\modules\UserManagement\controllers', // To prevent yii help from crashing ], ],
- Run migrations from the console
./yii migrate --migrationPath=vendor/chieff/yii2-user-management-module/migrations/
If you want delete tables later and didn't migrate another tables, use:
./yii migrate/down 11 --migrationPath=vendor/chieff/yii2-user-management-module/migrations/
- In you base controller
public function behaviors() { return [ 'ghost-access' => [ 'class' => 'webvimark\modules\UserManagement\components\GhostAccessControl', ], ]; }
Where you can go
use webvimark\modules\UserManagement\components\GhostMenu; use webvimark\modules\UserManagement\UserManagementModule; echo GhostMenu::widget([ 'encodeLabels'=>false, 'activateParents'=>true, 'items' => [ [ 'label' => 'Backend routes', 'items' => UserManagementModule::menuItems() ], [ 'label' => 'Frontend routes', 'items' => [ ['label' => 'Login', 'url' => ['/user-management/auth/login']], ['label' => 'Logout', 'url' => ['/user-management/auth/logout']], ['label' => 'Registration', 'url' => ['/user-management/auth/registration']], ['label' => 'Change own password', 'url' => ['/user-management/auth/change-own-password']], ['label' => 'Password recovery', 'url' => ['/user-management/auth/password-recovery']], ['label' => 'E-mail confirmation', 'url' => ['/user-management/auth/confirm-email']], ], ], ], ]);
Also you can get links for nav:
use webvimark\modules\UserManagement\components\GhostMenuArray; $menuItems = GhostMenuArray::buildDefault(); $menuItems = array_merge($menuItems, [ [ 'label' => 'Блог', 'url' => ['/topic/index'], 'items' => [ [ 'label' => 'Категории', 'url' => ['/topic-category/index'], ], [ 'label' => 'Страницы', 'url' => ['/topic/index'] ] ] ] ]);
and get links for different places buildDefaultBackend or buildDefaultFrontend.
First steps
From the menu above at first you'll se only 2 element: "Login" and "Logout" because you have no permission to visit other urls and to render menu we using GhostMenu::widget(). It's render only element that active user can visit.
Also same functionality has GhostNav::widget() and GhostHtml:a()
-
Login as superadmin/superadmin
-
Go to "Permissions" and play there
-
Go to "Roles" and play there
-
Go to "User" and play there
-
Go to "Routes" and play there
-
Relax
Usage
You controllers may have two properties that will make whole controller or selected action accessible to everyone
public $freeAccess = true;
Or
public $freeAccessActions = ['first-action', 'another-action'];
Here are list of the useful helpers. For detailed explanation look in the corresponding functions.
User::hasRole($roles, $superAdminAllowed = true) User::hasPermission($permission, $superAdminAllowed = true) User::canRoute($route, $superAdminAllowed = true) User::assignRole($userId, $roleName) User::revokeRole($userId, $roleName) User::getCurrentUser($fromSingleton = true)
Role, Permission and Route all have following methods
Role::create($name, $description = null, $groupCode = null, $ruleName = null, $data = null) Role::addChildren($parentName, $childrenNames, $throwException = false) Role::removeChildren($parentName, $childrenNames)
Events
Events can be handled via config file like following
'modules' => [ 'user-management' => [ 'class' => 'webvimark\modules\UserManagement\UserManagementModule', 'on afterRegistration' => function(UserAuthEvent $event) { // Here you can do your own stuff like assign roles, send emails and so on }, ], ],
List of supported events can be found in UserAuthEvent class
FAQ
Question: I want users to register and login with they e-mails! Mmmmm... And they should confirm it too!
Answer: See configuration properties $useEmailAsLogin and $emailConfirmationRequired
Question: I want to have profile for user with avatar, birthday and stuff. What should I do ?
Answer: Profiles are to project-specific, so you'll have to implement them yourself (but you can find example here - https://github.com/webvimark/user-management/wiki/Profile-and-custom-registration). Here is how to do it without modifying this module:
-
Create table and model for profile, that have user_id (connect with "user" table)
-
Check AuthController::actionRegistration() how it works (you can skip this part)
-
Define your layout for registration. Check example in AuthHelper::layoutHandler(). Now use theming to change registraion.php file
-
Define your own UserManagementModule::$registrationFormClass. In this class you can do whatever you want like validating custom forms and saving profiles
-
Create your controller where user can view profiles
If you want to get ready solution use my own profile module - yii2-user-profile-module
Icons
To see icons:
class AppAsset extends AssetBundle { // ... public $depends = [ // ... 'rmrevin\yii\fontawesome\AssetBundle' ]; }
Datepicker
For date and datetime fields used kartik-v/yii2-widget-datepicker and kartik-v/yii2-widget-datetimepicker , it need bootstrap directive of version. Put in config/params.php code below for version that you are using:
<?php
return [
'bsVersion' => '4',
'adminEmail' => 'admin@example.com',
// ...
];