Add mkdocs and change menu names to avoid margin collisions (#468)

This commit is contained in:
Chris Smith
2022-08-18 15:39:18 -05:00
committed by GitHub
parent 99271a55c3
commit e460890be0
27 changed files with 30 additions and 28 deletions

View File

@ -0,0 +1,99 @@
Advanced Application Template
=============================
This page is dedicated for those who prefer to use more or less default
[Advanced Application Template](https://github.com/yiisoft/yii2-app-advanced) provided by the Yii core team. Please
check [their readme](https://github.com/yiisoft/yii2-app-advanced#readme) file on why and when you should use it,
for now we're going to explain on how Yii2 User Module extension could be used for the case if you prefer it.
> We highly recommend you to use [Sidekit Application Template](https://github.com/sidekit/yii2-app-template) which has sensible default
packages, and everything you need to start project in no time with batteries included! ;-)
>
> [Check this manual page](sidekit-application-template.md) if you decided to use it.
If you want to use the default [Basic Application Template](https://github.com/yiisoft/yii2-app-basic) with our
extension, then check [Basic Application Template documentation page](yii2-application-template.md).
Step 1 - Install Advanced Application template
----------------------------------------------
Please check [this document](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-installation.md)
on how you can install Advanced Application Template. We're not going to cover this process here.
Step 2 - Configure your application
-----------------------------------
For now we will consider you need to setup user module for the backend tier of your project. User module needs to set
and instantiate various settings, services, and parts to be used in application. That's why you have to include
bootstrap class in your application bootstrapping workflow by adding the following lines in your
`%PROJECT_DIR%/backend/config/main.php`:
```php
return [
// ... existing settings of the application
'modules' => [
'user' => [
'class' => Da\User\Module::class,
],
],
'components' => [
// ... configuration of the existing application components
],
];
```
That's all from the part of the web application.
Step 3 - Apply database schema migrations
-----------------------------------------
This is obvious extension like our which deals with users, roles, permissions, etc. have to use some database.
Our migrations are namespaced and available in `Da\User\Migration` namespace.
Before starting to work with database, please ensure you have deleted `m130524_201442_init.php` migration file
which comes from the default installation of the Advanced Application Template. It's located at
`%PROJECT_DIR%/console/migrations/m130524_201442_init.php` path.
There are two ways to apply migrations of this extension, the first one:
```php
./yii migrate --migrationNamespaces=Da\\User\\Migration
./yii migrate --migrationPath=@yii/rbac/migrations
./yii migrate
```
First command applies migration set of the user module, and the second one is for application migrations.
> Note, you cannot mix two ways: choose one of them, and stick with it.
The second way is more comfortable, and you don't have to remember to launch first command every time you obtain
new version of our extension. First of all add the following lines to the file
`%PROJECT_DIR%/console/config/main.php`:
```php
return [
// ...
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'@app/migrations',
'@yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
// ...
];
```
This basically instructs your application to always try to use migrations from the given namespace. Which again
is very convenient way to track new migration classes coming from this and possibly other extensions and sources.
> Namespaced migrations were introduced in Yii 2.0.10, so before using them consider updating your framework
> installation version.
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,82 @@
Available Actions
=================
The following is the list of action provided by the module:
| Action | Description | Query params | Method available | Note
| --- | --- | --- | --- | ---
| **/user/registration/register** | Displays registration form
| **/user/registration/resend** | Displays resend form
| **/user/registration/connect** | Connect a social network account | *code*
| **/user/registration/confirm** | Confirms a user | *id*, *code*
| **/user/security/login** | Displays login form
| **/user/security/logout** | Logs the user out | | POST only
| **/user/security/confirm** | Social account confirm | *id*, *code* | | Query params depend of SocialNetworkAccountQuery
| **/user/security/auth** | Social account login | | |
| **/user/recovery/request** | Displays recovery request form
| **/user/recovery/reset** | Displays password reset form | *id*, *code*
| **/user/settings/account** | Displays account settings form | | | email, username, password
| **/user/settings/confirm** | Confirms a new email | *id*, *code*
| **/user/settings/delete** | Delete self account | | POST only
| **/user/settings/disconnect** | Disconnect social account | | POST only
| **/user/settings/export** | Download personal data in a comma separated values format
| **/user/settings/gdpr-delete** | Displays delete personal data page |
| **/user/settings/networks** | Displays social network accounts settings page
| **/user/settings/privacy** | Displays GDPR data page
| **/user/settings/profile** | Displays profile settings form
| **/user/settings/two-factor** | Show 2fa (Two factor authentication) | *id* | | https://github.com/2amigos/2fa-library required
| **/user/settings/two-factor-enable** | Enabled 2fa | *id* | | https://github.com/2amigos/2fa-library required
| **/user/settings/two-factor-disable** | Disabled 2fa | *id* | POST only | https://github.com/2amigos/2fa-library required
| **/user/profile/show** | Displays user's profile | *id*
| **/user/admin/index** | Displays user management interface
| **/user/admin/create** | Displays create user form
| **/user/admin/update** | Displays update user form | *id*
| **/user/admin/update-profile** | Displays update user's profile form | *id*
| **/user/admin/info** | Displays user info | *id*
| **/user/admin/assignments** | Displays rbac user assignments | *id*
| **/user/admin/confirm** | Confirms a user | *id* | POST only
| **/user/admin/delete** | Deletes a user | *id* | POST only
| **/user/admin/block** | Blocks a user | *id* | POST only
| **/user/admin/switch-identity** | Switch identities between the current admin and user on list | | POST only
| **/user/admin/password-reset** | Send recovery message to the user | *id* | POST only
| **/user/admin/force-password-change** | Forces the user to change password at next login | *id* | POST only
| **/user/role/index** | Displays rbac roles management interface
| **/user/role/create** | Displays create rbac role form
| **/user/role/update** | Displays update rbac role form | *name*
| **/user/role/delete** | Deletes a rbac role | *name*
| **/user/permission/index** | Displays rbac permissions management interface
| **/user/permission/create** | Displays create rbac permission form
| **/user/permission/update** | Displays update rbac permission form | *name*
| **/user/permission/delete** | Deletes a rbac permission | *name*
| **/user/rule/index** | Displays rbac permissions management interface
| **/user/rule/create** | Displays create rbac rule form
| **/user/rule/update** | Displays update rbac rule form | *name*
| **/user/rule/delete** | Deletes a rbac rule | *name*
The module overrides some to make it simpler:
```php
'<id:\d+>' => 'profile/show',
'<action:(login|logout)>' => 'security/<action>',
'<action:(register|resend)>' => 'registration/<action>',
'confirm/<id:\d+>/<code:[A-Za-z0-9_-]+>' => 'registration/confirm',
'forgot' => 'recovery/request',
'recover/<id:\d+>/<code:[A-Za-z0-9_-]+>' => 'recovery/reset'
```
So they become:
- **/user/{id}** Displays user's profile (requires *id* query param)
- **/user/login** Displays login form
- **/user/logout** Logs out a user
- **/user/register** Displays registration form
- **/user/resend** Displays resend form
- **/user/confirm/{id}/{token}** Confirms a user (requires *id* and *token* query params)
- **/user/forgot** Displays recovery request form
- **/user/recover/{id}/{token}** Displays password reset form (requires *id* and *token* query params)
You can override them by setting the module's routes to an empty array. Then, configure the routes as you please.
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,306 @@
Configuration Options
=====================
The module comes with a set of attributes to configure. The following is the list of all available options:
#### enableSessionHistory (Type: `boolean, integer`, Default value: `false`)
If this option is to `true`, session history will be kept, [more](../guides/how-to-use-session-history.md).
#### numberSessionHistory (Type: `boolean, integer`, Default value: `false`)
Number of expired storing records `session history`, values:
- `false` Store all records without deleting
- `integer` Count of records for storing
#### timeoutSessionHistory (Type: `boolean, integer`, Default value: `false`)
How long store `session history` after expiring, values:
- `false` Store all records without deleting
- `integer` Time for storing after expiring in seconds
#### enableTwoFactorAuthentication (type: `boolean`, default: `false`)
Setting this attribute will allow users to configure their login process with two-factor authentication.
#### twoFactorAuthenticationCycles (type: `integer`, default: `1`)
By default, Google Authenticator App for two-factor authentication cycles in periods of 30 seconds. In order to allow
a bigger period so to avoid out of sync issues.
#### twoFactorAuthenticationValidators (type: `array`)
An array of arrays of channels availables for two factor authentication. The keys in the arrays have the following meaning:
class: it will be the validator class with namespace;
name: the name that will be displayed in the section to the user;
configurationUrl: the url to the action that will dispaly the configuration form for the validator;
codeDurationTime: time duration of the code in session in seconds (not applicable for Google authenticator);
smsSender: the reference to SmsSenderInterface for managing SMS send;
enabled: true if you want to enable the channel, false otherwise.
The following is the default configuration:
'google-authenticator'=>[
'class'=>\Da\User\Validator\TwoFactorCodeValidator::class,
'description'=>Yii::t('usuario', 'Google Authenticator'),
'configurationUrl'=>'user/settings/two-factor',
'enabled'=>true
],
'email'=>[
'class'=>\Da\User\Validator\TwoFactorEmailValidator::class,
'description'=>Yii::t('usuario', 'Email'),
'configurationUrl'=>'user/settings/two-factor-email',
'codeDurationTime'=>300,
'enabled'=>true
],
'sms'=>[
'class'=>\Da\User\Validator\TwoFactorTextMessageValidator::class,
'description'=>Yii::t('usuario', 'Text message'),
'configurationUrl'=>'user/settings/two-factor-sms',
'codeDurationTime'=>300,
'smsSender'=>'smsSender',
'enabled'=>true
]
For instructions about implementation of SMS sending see at the following link: https://www.yiiframework.com/extension/yetopen/yii2-sms-aruba
#### twoFactorAuthenticationForcedPermissions (type: `array`, default: `[]`)
The list of permissions for which two factor authentication is mandatory. In order to perform the check in every action you must configure a filter into your config file like this:
use Da\User\Filter\TwoFactorAuthenticationEnforceFilter;
...
'on beforeAction' => function() {
Yii::$app->controller->attachBehavior(
'enforceTwoFactorAuthentication',[
'class' => TwoFactorAuthenticationEnforceFilter::class,
'except' => ['login', 'logout', 'account', 'two-factor', 'two-factor-enable'],
]
);
},
...
This will redirect the user to their account page until the two factor authentication is enabled.
#### enableGdprCompliance (type: `boolean`, default: `false`)
Setting this attribute enables a serie of measures to comply with EU GDPR regulation, like data consent, right to be forgotten and data portability.
#### gdprPrivacyPolicyUrl (type: `array`, default: null)
The link to privacy policy. This will be used on registration form as "read our pivacy policy". It must follow the same format as `yii\helpers\Url::to`
#### gdprExportProperties (type: `array`)
An array with the name of the user identity properties to be included when user request download of his data.
Names can include relations like `profile.name`.
Defaults to:
```php
[
'email',
'username',
'profile.public_email',
'profile.name',
'profile.gravatar_email',
'profile.location',
'profile.website',
'profile.bio'
]
```
#### gdprAnonymizePrefix (type: `string`, default: `GDPR`)
Prefix to be used as a replacement when user requeste deletion of his data
#### gdprConsentMessage (type: `string`)
Use this to customize the message that will appear as hint in the give consent checkbox.
If you leave it empty the next message will be used:
>I agree processing of my personal data and the use of cookies to facilitate the operation of this site. For more information read our privacy policy
#### GdprRequireConsentToAll (type `boolean`, default `false`)
Whether require to already registered user give consent to process their data. According to GDPR this is mandatory.
To forbid user access to any function, until it gives consent, use the AccessRuleFilter included with this module.
#### GdprConsentExcludedUrls (type `array`, default `['user/settings/*']`)
List of urls that does not require explicit data processing consent to be accessed, like own profile, account... You can use wildcards like `route/to/*` .
#### enableRegistration (type: `boolean`, default: `true`)
Setting this attribute allows the registration process. If you set it to `false`, the module won't allow users to
register by throwing a `NotFoundHttpException` if the `RegistrationController::actionRegister()` is accessed.
#### enableEmailConfirmation (type: `boolean`, default: `true`)
If `true`, the module will send an email with a confirmation link that user needs to click through to complete its
registration process.
#### enableFlashMessages (type: `boolean`, default: `true`)
If `true` views will display flash messages. Disable this if you want to handle messages display in your views.
#### enableSwitchIdentities (type: `boolean`, default: `true`)
If `true` allows switching identities for the admin user.
#### generatePasswords (type: `boolean`, default: `true`)
If `true` the password field will be hidden on the registration page and passwords will be generated automatically and
sent to the user via email.
#### allowUnconfirmedEmailLogin (type: `boolean`, default: `false`)
If `true` it will allow users to login with unconfirmed emails.
#### allowPasswordRecovery (type: `boolean`, default: `true`)
If `true` it will enable password recovery process.
#### allowAdminPasswordRecovery (type: `boolean`, default: `true`)
If `true` it will enable administrator to send a password recovery email to a user.
#### maxPasswordAge (type: `integer`, default: `null`)
If set to an integer value it will check user password age. If the days since last password change are greater than this configuration value
user will be forced to change it. This enforcement is done only at login stage. In order to perform the check in every action you must configure
a filter into your controller like this:
```
use Da\User\Filter\PasswordAgeEnforceFilter;
class SiteController extends Controller
{
public function behaviors()
{
return [
[...]
'enforcePasswordAge' => [
'class' => PasswordAgeEnforceFilter::className(),
],
```
This will redirect the user to their account page until the password has been updated.
#### allowAccountDelete (type: `boolean`, default: `false`)
If `true` users will be able to remove their own accounts.
#### emailChangeStrategy (type: `integer`, default: `MailChangeStrategyInterface::TYPE_DEFAULT`)
Configures one of the three ways available to change user's password:
- **MailChangeStrategyInterface::TYPE_DEFAULT**: A confirmation message will be sent to the new user's email with a link
that needs to be click through to confirm it.
- **MailChangeStrategyInterface::TYPE_INSECURE**: Email will be changed without any confirmation message.
- **MailChangeStrategyInterface::TYPE_SECURE**: A confirmation message will be sent to the previous and new user's email
with a link that would require both to be click through to confirm the change.
#### rememberLoginLifespan (type: `integer`, default: `1209600`)
Configures the time length in seconds a user will be remembered without the need to login again. The default time is 2
weeks.
#### tokenConfirmationLifespan (type: `integer`, default: `86400`)
Configures the time length in seconds a confirmation token is valid. The default time is 24 hours.
#### tokenRecoveryLifespan (type: `integer`, default: `21600`)
Configures the time length in seconds a recovery token is valid. The default time is 6 hours.
#### administrators (type: `array`, default: `[]`)
Configures the usernames of those users who are considered `admininistrators`. The administrators can be
configured here or throughout RBAC with a special permission name. The recommended way is throughout
`administratorPermissionName` as they can be set dynamically throughout the RBAC interface, but use this attribute for
simple backends with static administrators that won't change throughout time.
#### administratorPermissionName (type: `string`, default: `null`)
Configures the permission name for `administrators`. See [AuthHelper](../../src/User/Helper/AuthHelper.php).
#### prefix (type: `string`, default: `user`)
Configures the URL prefix for the module.
#### mailParams (type: `array`, default: `[]`)
Configures the parameter values used on [MailFactory](../../src/User/Factory/MailFactory.php). The default values are:
```php
[
'fromEmail' => 'no-reply@example.com',
'welcomeMailSubject' => Yii::t('usuario', 'Welcome to {0}', $app->name),
'confirmationMailSubject' => Yii::t('usuario', 'Confirm account on {0}', $app->name),
'reconfirmationMailSubject' => Yii::t('usuario', 'Confirm email change on {0}', $app->name),
'recoveryMailSubject' => Yii::t('usuario', 'Complete password reset on {0}', $app->name),
'twoFactorMailSubject' => Yii::t('usuario', 'Code for two factor authentication on {0}', $app->name),
]
```
#### blowfishCost (type: `integer`, default: `10`)
Is the cost parameter used by the Blowfish hash algorithm. The higher the value of cost, the longer it takes to generate
the hash and to verify a password against it. Higher cost therefore slows down a brute-force attack. For the best
protected against brute-force attacks, set it to the highest value that is tolerable on production servers. The time
taken to compute the hash doubles for every increment by one of `$blowfishCost`.
#### consoleControllerNamespace (type: `string`, default: `Da\User\Command`)
Allows customization of the console application controller namespace for the module.
#### controllerNamespace (type: `string`, default: `Da\User\Controller`)
Allows customization of the web application controller namespace for the module.
#### classMap (type: `array`, default: `[]`)
Configures the definitions of the classes as they have to be override. For more information see
[Overriding Classes](../customizing/overriding-classes.md).
#### routes (type: `array`, default: `[]` )
The routes (url rules) of the module for the URL management. The default values are:
```php
[
'<id:\d+>' => 'profile/show',
'<action:(login|logout)>' => 'security/<action>',
'<action:(register|resend)>' => 'registration/<action>',
'confirm/<id:\d+>/<code:[A-Za-z0-9_-]+>' => 'registration/confirm',
'forgot' => 'recovery/request',
'recover/<id:\d+>/<code:[A-Za-z0-9_-]+>' => 'recovery/reset',
'settings/<action:\w+>' => 'settings/<action>',
]
```
#### viewPath (type: `string`, default: `@Da/User/resources/views`)
Configures the root directory of the view files. See [overriding views](../customizing/overriding-views.md).
#### switchIdentitySessionKey (type: `string`, default: `yuik_usuario`)
Configures the name of the session key that will be used to hold the original admin identifier.
#### restrictUserPermissionAssignment (type: `boolean`, default: `false`)
If `false`, allow the assignment of both roles and permissions to users.
Set to `true` to restrict user assignments to roles only.
#### disableIpLogging (type: `boolean`, default: `false`)
If `true` registration and last login IPs are not logged into users table, instead a dummy 127.0.0.1 is used
#### minPasswordRequirements (type: `array`, default: `['lower' => 1, 'digit' => 1, 'upper' => 1]`)
Minimum requirements when a new password is automatically generated.
Array structure: `"requirement" => minimum_number_characters`.
Possible array keys:
- lower: minimum number of lowercase characters;
- upper: minimum number of uppercase characters;
- digit: minimum number of digits;
- special: minimum number of special characters;
- min: minimum number of characters (= minimum length).
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,63 @@
Console Commands
================
The module comes with a set of console commands to facilitate some of the most common actions during development time:
- `user/create` to create a new user
- `user/confirm` to confirm a user
- `user/delete` to delete a user
- `user/password` to update a user's password
Configuration
-------------
To enable the commands add the following configuration details to your console config of your application:
```php
// ...
'modules' => [
'user' => Da\User\Module::class,
]
```
How to Use Them
---------------
#### user/create
If password is not set, it will automatically generate it. The newly created user will receive an email message with its
new credentials. If a role is provided, it will assign it to the user. Is important not note, that if the role doesn't
exist, the command will create it.
```php
./yii user/create <email> <username> [password] [role]
```
#### user/confirm
You can confirm a user whether by using its email or username.
```php
./yii user/confirm <email|username>
```
#### user/delete
You can delete a user whether by using its email or username.
```php
./yii user/delete <email|username>
```
#### user/password
You can update a user's password whether by using its email or username.
```php
./yii user/password <email|username> <password>
```
© [2amigos](http://www.2amigos.us/) 2013-2019

106
docs/install/mailer.md Normal file
View File

@ -0,0 +1,106 @@
Mailer
======
The way this module sends its emails is throughout the [`Mailer`](http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html)
component of Yii 2. Please, follow Yii 2's guidelines to set it up.
Nevertheless, you wish to configure the following attribute of the module: `mailParams`. the following is its default
values:
```php
[
'fromEmail' => 'no-reply@example.com',
'welcomeMailSubject' => Yii::t('usuario', 'Welcome to {0}', $app->name),
'confirmationMailSubject' => Yii::t('usuario', 'Confirm account on {0}', $app->name),
'reconfirmationMailSubject' => Yii::t('usuario', 'Confirm email change on {0}', $app->name),
'recoveryMailSubject' => Yii::t('usuario', 'Complete password reset on {0}', $app->name),
'twoFactorMailSubject' => Yii::t('usuario', 'Code for two factor authentication on {0}', $app->name),
]
```
Actually, the only thing required is the `fromEmail` value.
If you want to set it the same as senderEmail and senderName from your config params (like yii2-app-advanced template):
```php
...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'mailParams' => [
'fromEmail' => function() {
return [Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']];
}
],
],
],
...
```
If you look at the code of `Da\User\Factory\MailFactory.php`
you will easily find the reason why:
```php
// take this helper function for example:
public static function makeRecoveryMailerService($email, Token $token = null)
{
/** @var Module $module */
$module = Yii::$app->getModule('user');
$to = $email;
$from = $module->mailParams['fromEmail']; // fromEmail!!!
$subject = $module->mailParams['recoveryMailSubject']; // subject!!!
$params = [
'user' => $token && $token->user ? $token->user : null,
'token' => $token,
];
return static::makeMailerService($from, $to, $subject, 'recovery', $params);
}
```
With that information it creates an `Da\User\Service\MailService` instance and this class makes use of those values to
actually send the mails:
```php
public function run()
{
return $this->mailer
->compose(['html' => $this->view, 'text' => "text/{$this->view}"], $this->params)
->setFrom($this->from) // $this->from is actually fromEmail!!!
->setTo($this->to)
->setSubject($this->subject) // $this->subject is actually recoveryMailSubject!!!
->send();
}
```
> Tip: You can separate `from` by type of mailer of this module:
```php
...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'mailParams' => [
'fromEmail' =>
/**
* @param $type string The type of mail
* Da\User\Event\MailEvent::TYPE_WELCOME|Da\User\Event\MailEvent::TYPE_RECOVERY|
* Da\User\Event\MailEvent::TYPE_CONFIRM|Da\User\Event\MailEvent::TYPE_RECONFIRM
* @return array
*/
function ($type) {
switch ($type) {
case Da\User\Event\MailEvent::TYPE_WELCOME:
return [Yii::$app->params['supportEmail'] => Yii::t('app', '{0} welcome!', Yii::$app->name)];
break;
default:
return [Yii::$app->params['supportEmail'] => Yii::t('app', '{0} robot', Yii::$app->name)];
break;
}
},
],
],
],
...
```
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,467 @@
# Migration guide from Dektrium tools
yii2-usuario is 99% compatible with [dektrium](https://github.com/dektrium/) tools.
## Package removal
First of all you need to remove the old packages. Depending on your installation you
need to remove one or both:
```
composer remove dektrium/yii2-user
composer remove dektrium/yii2-rbac
```
## Install yii2-usuario
```
composer require 2amigos/yii2-usuario
```
## Configuration
Configure the `config/console.php` stuff:
```php
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
```
Configure the controller map for migrations
```php
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
```
Remove the *modules > rbac* configuration parameter, and replace the value of *modules > user* with:
```php
'user' => Da\User\Module::class,
```
In `config/web.php` remove *module > rbac* configuration and change the *modules > user* with:
```php
...
'user' => [
'class' => Da\User\Module::class,
// Othe yii2-usuario configuration parameters
'enableRegistration' => false,
],
...
```
* If you had `modelMap` customization you have to replace them with `classMap`.
* In your extended model replace the `BaseUser` inheritance from `dektrium\user\models\User` to `Da\User\Model\User`
* If you had controller remapping replace the inheritance from `dektrium\user\controllers\XX` to `Da\User\Controller\XX`
* Some properties has been renamed: from `enableConfirmation` to `enableEmailConfirmation`; from `enableGeneratingPassword` to `generatePasswords`
* Restore Identity url rule has been renamed: from `/user/admin/switch` to `/user/admin/switch-identity`
* Restore Identity session checker has changes: from
```php
if (Yii::$app->session->has(\dektrium\user\controllers\AdminController::ORIGINAL_USER_SESSION_KEY))
```
to
```php
/** @var Da\User\Module $module */
$module = Yii::$app->getModule('user');
if(Yii::$app->session->has($module->switchIdentitySessionKey))
```
* If you use event of Controllers see [events](../events) chapter of this docs. **All** of relative controller constant has been move to events class:
from `\dektrium\user\controllers\RecoveryController::EVENT_AFTER_REQUEST` to `\Da\User\Event\FormEvent::EVENT_AFTER_REQUEST`,
from `\dektrium\user\controllers\RecoveryController::EVENT_AFTER_RESET` to `\Da\User\Event\ResetPasswordEvent::EVENT_AFTER_RESET`, etc.
Map of constants can be find in [events](../events) chapter of this docs.
## BackendFilter and FrontendFilter
BackendFilter disable this controllers: 'profile', 'recovery', 'registration', 'settings';
FrontendFilter disable this controller: 'admin';
This functionality has been dropped. Use `deny` rule in your configuration directly. For example change `frontend` config like this:
```
'modules' => [
'user' => [
'controllerMap' => [
'admin' => [
'class' => Da\User\Controller\AdminController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'role' => [
'class' => Da\User\Controller\RoleController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'permission' => [
'class' => Da\User\Controller\PermissionController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'rule' => [
'class' => Da\User\Controller\RuleController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
],
],
],
```
## Mark migrations as applied in an existing project
If you already have a production project which has all the necessary user tables from dektrium simply run the following commands to
mark some migrations as already applied.
```
./yii migrate/mark "Da\User\Migration\m000000_000005_add_last_login_at"
./yii migrate/to "Da\User\Migration\m000000_000007_enable_password_expiration"
```
The first command will mark the migration as applied, the second will apply missing migrations.
The second command is optional as a simple ```./yii migrate/up``` would apply all missing migrations anyway.
## Rbac migrations
[yii2-rbac](https://github.com/dektrium/yii2-rbac) have a nice tool which are rbac migrations, which help writing new permissions and roles.
There's no such feature in yii2-usuario, but in case you need to still apply them you can:
1. create a migration component which basically it's the same as the original [Migration](https://github.com/dektrium/yii2-rbac/blob/master/migrations/Migration.php) object, with some minor changes. Copy the content below and save it in your `@app/components/RbacMigration.php`:
```php
<?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace app\components;
use yii\rbac\DbManager;
use yii\db\Migration;
use yii\di\Instance;
use yii\rbac\Item;
use yii\rbac\Permission;
use yii\rbac\Role;
use yii\rbac\Rule;
/**
* Migration for applying new RBAC items.
*
* @author Dmitry Erofeev <dmeroff@gmail.com>
*/
class RbacMigration extends Migration
{
/**
* @var string|DbManager The auth manager component ID that this migration should work with.
*/
public $authManager = 'authManager';
/**
* Initializes the migration.
* This method will set [[authManager]] to be the 'authManager' application component, if it is `null`.
*/
public function init()
{
parent::init();
$this->authManager = Instance::ensure($this->authManager, DbManager::className());
}
/**
* Creates new permission.
*
* @param string $name The name of the permission
* @param string $description The description of the permission
* @param string|null $ruleName The rule associated with the permission
* @param mixed|null $data The additional data associated with the permission
* @return Permission
*/
protected function createPermission($name, $description = '', $ruleName = null, $data = null)
{
echo " > create permission $name ...";
$time = microtime(true);
$permission = $this->authManager->createPermission($name);
$permission->description = $description;
$permission->ruleName = $ruleName;
$permission->data = $data;
$this->authManager->add($permission);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $permission;
}
/**
* Creates new role.
*
* @param string $name The name of the role
* @param string $description The description of the role
* @param string|null $ruleName The rule associated with the role
* @param mixed|null $data The additional data associated with the role
* @return Role
*/
protected function createRole($name, $description = '', $ruleName = null, $data = null)
{
echo " > create role $name ...";
$time = microtime(true);
$role = $this->authManager->createRole($name);
$role->description = $description;
$role->ruleName = $ruleName;
$role->data = $data;
$this->authManager->add($role);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $role;
}
/**
* Creates new rule.
*
* @param string $ruleName The name of the rule
* @param string|array $definition The class of the rule
* @return Rule
*/
protected function createRule($ruleName, $definition)
{
echo " > create rule $ruleName ...";
$time = microtime(true);
if (is_array($definition)) {
$definition['name'] = $ruleName;
} else {
$definition = [
'class' => $definition,
'name' => $ruleName,
];
}
/** @var Rule $rule */
$rule = \Yii::createObject($definition);
$this->authManager->add($rule);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $rule;
}
/**
* Finds either role or permission or throws an exception if it is not found.
*
* @param string $name
* @return Permission|Role|null
*/
protected function findItem($name)
{
$item = $this->authManager->getRole($name);
if ($item instanceof Role) {
return $item;
}
$item = $this->authManager->getPermission($name);
if ($item instanceof Permission) {
return $item;
}
return null;
}
/**
* Finds the role or throws an exception if it is not found.
*
* @param string $name
* @return Role|null
*/
protected function findRole($name)
{
$role = $this->authManager->getRole($name);
if ($role instanceof Role) {
return $role;
}
return null;
}
/**
* Finds the permission or throws an exception if it is not found.
*
* @param string $name
* @return Permission|null
*/
protected function findPermission($name)
{
$permission = $this->authManager->getPermission($name);
if ($permission instanceof Permission) {
return $permission;
}
return null;
}
/**
* Removes auth item.
*
* @param string|Item $item Either item name or item instance to be removed.
*/
protected function removeItem($item)
{
if (is_string($item)) {
$item = $this->findItem($item);
}
echo " > removing $item->name ...";
$time = microtime(true);
$this->authManager->remove($item);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
/**
* Adds child.
*
* @param Item|string $parent Either name or Item instance which is parent
* @param Item|string $child Either name or Item instance which is child
*/
protected function addChild($parent, $child)
{
if (is_string($parent)) {
$parent = $this->findItem($parent);
}
if (is_string($child)) {
$child = $this->findItem($child);
}
echo " > adding $child->name as child to $parent->name ...";
$time = microtime(true);
$this->authManager->addChild($parent, $child);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
/**
* Assigns a role to a user.
*
* @param string|Role $role
* @param string|int $userId
*/
protected function assign($role, $userId)
{
if (is_string($role)) {
$role = $this->findRole($role);
}
echo " > assigning $role->name to user $userId ...";
$time = microtime(true);
$this->authManager->assign($role, $userId);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
/**
* Updates role.
*
* @param string|Role $role
* @param string $description
* @param string $ruleName
* @param mixed $data
* @return Role
*/
protected function updateRole($role, $description = '', $ruleName = null, $data = null)
{
if (is_string($role)) {
$role = $this->findRole($role);
}
echo " > update role $role->name ...";
$time = microtime(true);
$role->description = $description;
$role->ruleName = $ruleName;
$role->data = $data;
$this->authManager->update($role->name, $role);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $role;
}
/**
* Updates permission.
*
* @param string|Permission $permission
* @param string $description
* @param string $ruleName
* @param mixed $data
* @return Permission
*/
protected function updatePermission($permission, $description = '', $ruleName = null, $data = null)
{
if (is_string($permission)) {
$permission = $this->findPermission($permission);
}
echo " > update permission $permission->name ...";
$time = microtime(true);
$permission->description = $description;
$permission->ruleName = $ruleName;
$permission->data = $data;
$this->authManager->update($permission->name, $permission);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $permission;
}
/**
* Updates rule.
*
* @param string $ruleName
* @param string $className
* @return Rule
*/
protected function updateRule($ruleName, $className)
{
echo " > update rule $ruleName ...";
$time = microtime(true);
/** @var Rule $rule */
$rule = \Yii::createObject([
'class' => $className,
'name' => $ruleName,
]);
$this->authManager->update($ruleName, $rule);
echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
return $rule;
}
}
```
2. change the inheritance of the `@app/rbac/migrations` files to `app\components\RbacMigration as Migration`
... and you're done! You can still apply your rbac migrations with `./yii migrate/up --migrationPath=@app/rbac/migrations`.
To create a new migration just run `yii migrate/create name_your_migration --migrationPath=@app/rbac/migrations` and remember to change parent class.

70
docs/install/rbac.md Normal file
View File

@ -0,0 +1,70 @@
RBAC
====
This module comes with RBAC package by default. We haven't found ourselves that we didn't require at least an admin
which doesn't require that level of security. Our projects always start with simple roles such as `admin` but later on
our customers always ask for different levels of permissions for multiple roles.
That is the reason why we include RBAC features by default, and whether you use it or not, you will have to apply
Yii's `rbac` schema migrations or override the views so `PermissionController` and `RoleController` are never
accessible.
We have added an access filter (`Da\User\Filter\AccessRuleFilter`) to allow you to work with those usernames you
configure as administrators of your app via the
[Module::administrators](configuration-options.md#administrators-type-array-default-) attribute.
> **Note**: Remember that you have to configure applications `authManager` with `'class' => 'Da\User\Component\AuthDbManagerComponent'`,
> prior to even apply the rbac migrations!
How to Use `AccessRuleFilter`
-----------------------------
The following is a fragment on how the `Da\User\Controller\AdminController` has configured the filter:
```php
// ...
use Da\User\Filter\AccessRuleFilter;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
// ...
class AdminController extends Controller
{
// ...
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'delete' => ['post'],
'confirm' => ['post'],
'block' => ['post'],
],
],
'access' => [
'class' => AccessControl::class,
'ruleConfig' => [
'class' => AccessRuleFilter::class,
],
'rules' => [
[
'allow' => true,
'roles' => ['admin'],
],
],
],
];
}
// ...
}
```
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,90 @@
2amigos Application Template
============================
This Application Template is our proposed structure for your Yii2 applications. It makes use
of a special library named `ConfigKit`
> For further information regarding the use of this template, please visit its
[README file](https://github.com/2amigos/yii2-app-template).
Step 1 - Install The Application template
-----------------------------------------
We will assume that you have composer installed globally on your computer and also the
`fxp/composer-asset/plugin:^1.3` that is required for all Yii2 apps.
```bash
composer create-project --prefer-dist --stability=dev 2amigos/yii2-app-template your-site-name
```
Step 2 - Configure your application
-----------------------------------
Go to the `config/web/modules` folder and create a new PHP file named `user.php`. Then on in its
contents write the configuration for the module:
```php
<?php
return [
'class' => Da\User\Module::class
];
```
Step 3 - Apply database schema migrations
-----------------------------------------
This is obvious extension like our which deals with users, roles, permissions, etc. have to use some database.
Our migrations are namespaced and available in `Da\User\Migration` namespace.
Before starting to work with database, please ensure you have deleted `m130524_201442_init.php` migration file
which comes from the default installation of the Advanced Application Template. It's located at
`%PROJECT_DIR%/console/migrations/m130524_201442_init.php` path.
There are two ways to apply migrations of this extension, the first one:
```php
./yii migrate --migrationNamespaces=Da\\User\\Migration
./yii migrate --migrationPath=@yii/rbac/migrations
./yii migrate
```
First command applies migration set of the user module, and the second one is for application migrations.
> Note, you cannot mix two ways: choose one of them, and stick with it.
The second way is more comfortable, and you don't have to remember to launch first command every time you obtain
new version of our extension. First of all add the following lines to the file
`%PROJECT_DIR%/console/config/main.php`:
```php
return [
// ...
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'@app/migrations',
'@yii/rbac/migrations',
],
],
],
// ...
];
```
This basically instructs your application to always try to use migrations from the given namespace. Which again
is very convenient way to track new migration classes coming from this and possibly other extensions and sources.
> Namespaced migrations were introduced in Yii 2.0.10, so before using them consider updating your framework
> installation version.
© [2amigos](http://www.2amigos.us/) 2013-2019