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

111
docs/guides/first-steps.md Normal file
View File

@ -0,0 +1,111 @@
First steps to use Yii2-usuario
===============================
After installing the extension and having configured everything, you need setup your application with the all the user related stuff, e.g.
* creating first users, roles, permissions, ...
* assigning permissions and roles to users
* extending your controllers with access restrictions
* starting user management
## Creating your first user
There are several ways to do that:
* using migrations
* using the Command line [Console Commands](../install/console-commands.md)
### Creating the first Administrator during a migration
This is helpful e.g. when using you Yii2 applicatio with Docker and need to start the Docker Container with basic user settings.
We will create an ```admin```user with a ```adminisrator``` role.
Put this in your migration:
class m... extends Migration
{
public function safeUp()
{
$auth = Yii::$app->authManager;
// create a role named "administrator"
$administratorRole = $auth->createRole('admin');
$administratorRole->description = 'Administrator';
$auth->add($administratorRole);
// create permission for certain tasks
$permission = $auth->createPermission('user-management');
$permission->description = 'User Management';
$auth->add($permission);
// let administrators do user management
$auth->addChild($administratorRole, $auth->getPermission('user-management'));
// create user "admin" with password "verysecret"
$user = new \Da\User\Model\User([
'scenario' => 'create',
'email' => "email@example.com",
'username' => "admin",
'password' => "verysecret" // >6 characters!
]);
$user->confirmed_at = time();
$user->save();
// assign role to our admin-user
$auth->assign($administratorRole, $user->id);
}
public function safeDown()
{
$auth = Yii::$app->authManager;
// delete permission
$auth->remove($auth->getPermission('user-management'));
// delete admin-user and administrator role
$administratorRole = $auth->getRole("administrator");
$user = \Da\User\Model\User::findOne(['username'=>"admin"]);
$auth->revoke($administratorRole, $user->id);
$user->delete();
$auth->remove($administratorRole);
}
## User Management
Having setup the ```admin``` user you can start using user management at
http://yourapp/index.php?r=user/admin
You should be prompted a login screen and the enter ```admin/verysecret```.
## Working with authentication
Usually access restrictions to controller actions care specified in
[```behaviors()```](http://stuff.cebe.cc/yii2docs/guide-security-authorization.html).
Additionally, in your code you can directly use permission checks. This is
helpful e.g. in ```./views/layouts/main.php```.
Examples:
// Is current user a guest (not signed in?)
if (Yii::$app->user->isGuest) {
...
}
// Get roles of user
$roles = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
// Does current user have permission to do "user-management"?
if (Yii::$app->user->can("user-management")) {
...
}
### Recommended Reading
It is helpful to basically understand how Yii2 does authantication. The you can get in Yii2-usuario more quickly.
- [The Definitive Guide to Yii 2.0: Authentication](https://www.yiiframework.com/doc/guide/2.0/en/security-authentication)

52
docs/guides/gdpr.md Normal file
View File

@ -0,0 +1,52 @@
# GDPR and Yii2-usuario
EU regulation
The General Data Protection Regulation (GDPR) (EU) 2016/679 is a regulation in EU law on data protection and privacy for all individuals within the European Union and the European Economic Area. It also addresses the export of personal data outside the EU and EEA. The GDPR aims primarily to give control to citizens and residents over their personal data and to simplify the regulatory environment for international business by unifying the regulation within the EU
## Enable GDPR
To enable support in yii2-usuario set `enableGdprCompliance` to `true` and set
`gdprPrivacyPolicyUrl` with an url pointing to your privacy policy.
### At this moment a few measures apply to your app:
#### Data processing consent:
GDPR says: [Article 7](https://gdpr.algolia.com/gdpr-article-7)
> Where processing is based on consent, the controller shall be able to demonstrate that the data subject has consented to processing of his or her personal data.\[...]
All users must give consent of data processing to register.
Also consent will be stored in db with the user data.
If you have users before GDPR law you can force them to give consent via GDPRrequireConsentToAll. You must use also in your accessControl behaviors the yii2-usuario accessRuleFilter. Any registerd user that has not give consent will be redirected in any action to the consent screen except those defined in `GDPRconsentExcludedUrls`
#### Data portability
GDPR says: [Article 20](https://gdpr.algolia.com/gdpr-article-20)
> The data subject shall have the right to receive the personal data concerning him or her, which he
> or she has provided to a controller, in a structured, commonly used and machine-readable format\[...]
Users now have a privacy page in their account settings where they can export his/her personal data
in a csv file.
If you collect additional personal information you can to export by adding to
`gdprExportProperties`.
> Export use `ArrayHelper::getValue()` to extract information, so you can use links to relations.
#### Right to be forgotten
GDPR says: [Article 17](https://gdpr.algolia.com/gdpr-article-17)
> The data subject shall have the right to obtain from the controller the erasure of personal data concerning him or her without undue delay and the controller shall have the obligation to erase personal data without undue delay\[...]
In privacy page, users will find a button to delete their personal information.
The behavior differs depending module configuration.
If `$allowAccountDelete` is set to `true` the account will be fully deleted when clicking *Delete* button,
while when if that setting is set to `false` the module will remove social network connections and
replace the personal data with a custom alias defined in `$gdprAnonymizePrefix`.
The account will be blocked and marked as `gdpr_deleted`.
That way you can keep your site operation as normal.
> If you need to delete additional information use the `GdprEvent::EVENT_BEFORE_DELETE`.

View File

@ -0,0 +1,150 @@
How to Add Captcha Widget
=========================
In order to add the Yii 2 captcha widget you need to:
- Override the Form class you wish to add the captcha rule to
- Override the view where the form is rendering
- Add captcha action to a controller
- Configure Module and Application
Override the Form
-----------------
For the sake of the example, we are going to override the `Da\User\Form\RecoveryForm` class:
```php
namespace app\forms;
class RecoveryForm extends Da\User\Form\RecoveryForm {
public $captcha;
public function rules() {
$rules = parent::rules();
$rules[] = ['captcha', 'required'];
$rules[] = ['captcha', 'captcha'];
return $rules;
}
}
```
Overriding the View
-------------------
Create a new file and name it `request.php` and add it in `@app/views/user/recovery`. Add the captcha widget to it:
```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
/**
* @var yii\web\View $this
* @var yii\widgets\ActiveForm $form
* @var \Da\User\Form\RecoveryForm $model
*/
$this->title = Yii::t('usuario', 'Recover your password');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?= Html::encode($this->title) ?></h3>
</div>
<div class="panel-body">
<?php $form = ActiveForm::begin(
[
'id' => $model->formName(),
'enableAjaxValidation' => true,
'enableClientValidation' => false,
]
); ?>
<?= $form->field($model, 'email')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'captcha')
->widget(Captcha::className(), ['captchaAction' => ['/site/captcha']]) ?>
<?= Html::submitButton(Yii::t('usuario', 'Continue'), ['class' => 'btn btn-primary btn-block']) ?><br>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
```
Add Captcha Action to a Controller
----------------------------------
```php
namespace app\controllers;
class RecoveryController extends \yii\web\Controller
{
// ...
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
],
];
}
// ...
}
```
Configure Module and Application
--------------------------------
Finally, we have to configure the module and the application to ensure is using our form and our view:
```php
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'classMap' => [
'RecoveryForm' => 'app\forms\RecoveryForm'
],
'controllerMap' => [
'recovery' => [
                'class' => '\app\controllers\RecoveryController'
]
]
]
],
// ...
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'@Da/User/resources/views' => '@app/views/user'
]
]
]
]
```
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,54 @@
How to Implement Two Factor Auth (2FA)
======================================
Two Factor Authentication products add an additional layer of security. Typically, users are asked to prove their
identity by providing simple credentials such as an email address and a password. A second factor (2F) adds an extra
layer of unauthorized access protection by prompting the user to provide an additional means of authentication such as
a physical token (e.g. a card) or an additional secret that only they know.
With this module is quite easy. It basically implements two factor authentication using the following 2amigos libraries:
- [2amigos/2fa-library](https://github.com/2amigos/2fa-library)
- [2amigos/qrcode-library](https://github.com/2amigos/qrcode-library)
Enable Two Factor
-----------------
Install required libraries with:
```
composer require 2amigos/2fa-library "^1.0"
composer require 2amigos/qrcode-library "^1.1"
```
Then enable two factor authentication in your config:
```php
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableTwoFactorAuthentication' => true
]
]
```
Now, when the user go to its settings via `user/settings`, it will display the option to enable two factor
authentication or not.
When enabled, the module will show a modal with a QrCode that has to be scanned by the Google Authenticator App
(**Recommended**. You can download from
[Google Play](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2) or
[iTunes](https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8)).
The application will display a code that needs to be inserted into the modal input box. If code verification goes well,
it will enable the two factor for the user.
If a user has enabled the two factor, and after successfully login via username and email, it will render a new section
where user will have to enter the code displayed on its Google Authenticator App in order to complete with the login
process.
### Recommended Reading
- [2amigos Two Factor Library Docs]()http://2fa-library.readthedocs.io/en/latest/)
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,61 @@
How to Switch Identities with a user
====================================
If you are admin, you can impersonate (switch identities with another user). This action is taken when you, as an admin,
needs to check the panel of a user. Whether for support or simply checking whether is using correctly your system
according to your terms and conditions.
The default view of this module provides the mechanism on the grid that displays the users by placing a user icon on
its actions column. Once, clicked, it will call the **/user/admin/switch-identity** and make the transition. Then will
redirect you to the index page (`goHome()`) and is there where you will have to take the correspondent actions to
display the views appropriated for that user.
How to rollback to admin user
-----------------------------
The way to do it is by calling that action again. The link to do that could be written like this:
```php
$module = Yii::$app->getModule('user');
if(Yii::$app->session->has($module->switchIdentitySessionKey)) {
echo Html::a('Switch to Admin', ['/user/admin/switch-identity'], ['data-method' => 'post']);
}
```
> Note: If you use RBAC we can add access for all user to to this action for back to original user available.
```php
...
'modules' => [
'user' => [
'controllerMap' => [
'admin' => [
'class' => Da\User\Controller\AdminController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [
['allow' => true, 'actions' => ['switch-identity']],
['allow' => true, 'permissions' => ['administrateUser']],
],
],
],
],
],
],
...
```
> Also you can define access role `'administratorPermissionName' => 'admin',` where `admin` is have `administrateUser` permission
```php
...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administratorPermissionName' => 'admin',
],
],
...
```
Check the [switchIdentitySessionKey](../install/configuration-options.md#switchidentitysessionkey) documentation
for further information regarding this configuration option.
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,158 @@
How to Use ReCaptcha Widget
============================
We have included a [Google ReCAPTCHA](https://developers.google.com/recaptcha) widget if you wish to use it instead of
Yii's captcha. The widget is based on reCaptcha v2.0.
To make use of the widget you need to:
- [Signup for a reCaptcha API site key](https://www.google.com/recaptcha/admin#createsite)
- Configure the `ReCaptchaComponent` on the `components` section of your application configuration
- Override the Form class you wish to add the captcha rule to
- Override the view where the form is rendering
- Configure Module and Application
Configuring the ReCaptchaComponent
----------------------------------
Once you have the API site key you will also be displayed a secret key. You have to configure the component as follows:
```php
'components' => [
'recaptcha' => [ // *important* this name must be like this
'class' => 'Da\User\Component\ReCaptchaComponent',
'key' => 'yourSiteKey',
'secret' => 'secretKeyGivenByGoogle
]
]
```
Override the Form
-----------------
For the sake of the example, we are going to override the `Da\User\Form\RecoveryForm` class. Create a new file `RecoveryForm`
add it to @app/models/Forms/ and put the following in it:
```
<?php
namespace app\models\Forms;
use Da\User\Form\RecoveryForm as BaseForm;
class RecoveryForm extends BaseForm {
public $captcha;
public function rules() {
$rules = parent::rules();
$rules[] = [['captcha'], 'required'];
$rules[] = [['captcha'], 'Da\User\Validator\ReCaptchaValidator'];
return $rules;
}
public function scenarios()
{
return [
self::SCENARIO_REQUEST => ['email', 'captcha'],
self::SCENARIO_RESET => ['password'],
];
}
}
```
Overriding the View
-------------------
Create a new file and name it `request.php` and add it in `@app/views/user/recovery`. Add the captcha widget to it:
```
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use Da\User\Widget\ReCaptchaWidget;
/**
* @var yii\web\View $this
* @var yii\widgets\ActiveForm $form
* @var \Da\User\Form\RecoveryForm $model
*/
$this->title = Yii::t('usuario', 'Recover your password');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?= Html::encode($this->title) ?></h3>
</div>
<div class="panel-body">
<?php $form = ActiveForm::begin(
[
'id' => $model->formName(),
'enableAjaxValidation' => false,
'enableClientValidation' => false,
]
); ?>
<?= $form->field($model, 'email')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'captcha')->widget(ReCaptchaWidget::className(), ['theme' => 'light']) ?>
<?= Html::submitButton(Yii::t('usuario', 'Continue'), ['class' => 'btn btn-primary btn-block']) ?><br>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
```
Configure Module and Application
--------------------------------
Finally, we have to configure the module and the application to ensure is using our form and our view:
```php
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'classMap' => [
'RecoveryForm' => 'app\models\Forms\RecoveryForm'
],
]
],
// ...
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'@Da/User/resources/views' => '@app/views/user'
]
]
]
]
```
Notes For Other Forms
---------------------
The outward facing forms (i.e. forms that you don't need to login to use) also include `registrationForm`, `resendForm`.
- All three forms need `'enableAjaxValidation' => false` in the view override.
- `registrationForm` & `resendForm` do not need `scenarios()` in the form override.
- `registrationForm` needs fix #347 to work.
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,60 @@
How to enable session history
============================
Session history list user sessions.
User can delete all sessions except current.
Configure Module and Application
--------------------------------
```php
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableSessionHistory' => true,
]
],
// ...
'components' => [
'session' => Da\User\Service\SessionHistory\SessionHistoryDecorator::class,
]
// ...
'container' => [
'singletons' => [
Da\User\Service\SessionHistory\TerminateSessionsServiceInterface::class => Da\User\Service\SessionHistory\TerminateSessionsService::class
]
]
// ...
'controllerMap' => [
'migrate' => [
...
'migrationNamespaces' => [
'Da\User\Migration\Session',
],
],
],
```
Additionally for upping migration can use
```
./yii migrate --migrationNamespaces=Da\\User\\Migration\Session
```
Setting user screenshot:
![Settings user screenshot](./session-history/settings.png)
Admin screenshot:
![Admin screenshot](./session-history/admin.png)
© [2amigos](http://www.2amigos.us/) 2013-2019

View File

@ -0,0 +1,7 @@
Separate Frontend and Backend Sessions
======================================
- TODO
© [2amigos](http://www.2amigos.us/) 2013-2019

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

View File

@ -0,0 +1,58 @@
Social Network Authentication
=============================
If you wish to add user registration and login throughout social networks the first thing you need to do is to add the
official [Yii's auth client extension](https://github.com/yiisoft/yii2-authclient) to your application. The preferred
way to install is through [composer](http://getcomposer.org/download/).
Either run
```
composer require --prefer-dist yiisoft/yii2-authclient
```
or add
```json
"yiisoft/yii2-authclient": "~2.1.0"
```
to the `require` section of your composer.json.
After you need to configure the `authClientCollection::clients` on your Application `components` section:
```php
// ...
'components' => [
// ...
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'Da\User\AuthClient\Facebook',
'clientId' => 'facebook_client_id',
'clientSecret' => 'facebook_client_secret'
]
]
]
]
```
We have override the clients that come with Yii official's auth extension so to provide them with a signature that
would help us access the email and username with ease.
The following is the list of clients supported by the module:
- **Facebook** - `Da\User\AuthClient\Facebook`
- **Github** - `Da\User\AuthClient\Github`
- **Google** - `Da\User\AuthClient\Google`
- **LinkedIn** - `Da\User\AuthClient\LinkedIn`
- **Twitter** - `Da\User\AuthClient\Twitter`
- **VKontakte** - `Da\User\AuthClient\VKontakte`
- **Yandex** - `Da\User\AuthClient\Yandex`
For further information about how to configure the clients, please visit the
[Official Yii Auth Client Extension documentation](https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/installation.md).
© [2amigos](http://www.2amigos.us/) 2013-2019