@ -8,9 +8,9 @@ dos métodos de autorización: Filtro de Control de Acceso y Control Basado en R
## Filtro de Control de Acceso <spanid="access-control-filter"></span>
Filtro de Control de Acceso (ACF) es un único método de autorización implementado como [[yii\filters\AccessControl]], el cual
es mejor utilizado por aplicaciones que sólo requieran un control de acceso simple. Como su nombre lo indica, ACF es
es mejor utilizado por aplicaciones que sólo requieran un control de acceso simple. Como su nombre lo indica, ACF es
un [filtro](structure-filters.md) de acción que puede ser utilizado en un controlador o en un módulo. Cuando un usuario solicita
la ejecución de una acción, ACF comprobará una lista de [[yii\filters\AccessControl::rules|reglas de acceso]]
la ejecución de una acción, ACF comprobará una lista de [[yii\filters\AccessControl::rules|reglas de acceso]]
para determinar si el usuario tiene permitido acceder a dicha acción.
El siguiente código muestra cómo utilizar ACF en el controlador `site`:
@ -48,7 +48,7 @@ class SiteController extends Controller
En el código anterior, ACF es adjuntado al controlador `site` en forma de behavior (comportamiento). Esta es la forma típica de utilizar
un filtro de acción. La opción `only` especifica que el ACF debe ser aplicado solamente a las acciones `login`, `logout` y `signup`.
Las acciones restantes en el controlador `site` no están sujetas al control de acceso. La opción `rules` lista
Las acciones restantes en el controlador `site` no están sujetas al control de acceso. La opción `rules` lista
las [[yii\filters\AccessRule|reglas de acceso]], y se lee como a continuación:
- Permite a todos los usuarios invitados (sin autenticar) acceder a las acciones `login` y `signup`. La opción `roles`
@ -57,7 +57,7 @@ las [[yii\filters\AccessRule|reglas de acceso]], y se lee como a continuación:
a los "usuarios autenticados".
ACF ejecuta la comprobación de autorización examinando las reglas de acceso una a una desde arriba hacia abajo hasta que encuentra
una regla que aplique al contexto de ejecución actual. El valor `allow` de la regla que coincida será entonces utilizado
una regla que aplique al contexto de ejecución actual. El valor `allow` de la regla que coincida será entonces utilizado
para juzgar si el usuario está autorizado o no. Si ninguna de las reglas coincide, significa que el usuario NO está autorizado,
y el ACF detendrá la ejecución de la acción.
@ -97,7 +97,7 @@ La comparación es sensible a mayúsculas. Si la opción está vacía o no defin
- `?`: coincide con el usuario invitado (sin autenticar)
- `@`: coincide con el usuario autenticado
El utilizar otro nombre de rol invocará una llamada a [[yii\web\User::can()]], que requiere habilitar RBAC
El utilizar otro nombre de rol invocará una llamada a [[yii\web\User::can()]], que requiere habilitar RBAC
(a ser descrito en la próxima subsección). Si la opción está vacía o no definida, significa que la regla se aplica a todos los roles.
* [[yii\filters\AccessRule::ips|ips]]: especifica con qué [[yii\web\Request::userIP|dirección IP del cliente]] coincide esta regla.
@ -231,7 +231,7 @@ return [
necesita declararse `authManager` adicionalmente a `config/web.php`.
> En el caso de yii2-advanced-app, `authManager` sólo debe declararse en `common/config/main.php`.
`DbManager` utiliza cuatro tablas de la BD para almacenar los datos:
`DbManager` utiliza cuatro tablas de la BD para almacenar los datos:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: la tabla para almacenar los ítems de autorización. Por defecto "auth_item".
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: la tabla para almacentar la jerarquía de los ítems de autorización. Por defecto "auth_item_child".
@ -362,10 +362,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user el ID de usuario.
* @param string|int $user el ID de usuario.
* @param Item $item el rol o permiso asociado a la regla
* @param array $params parámetros pasados a ManagerInterface::checkAccess().
* @return boolean un valor indicando si la regla permite al rol o permiso con el que está asociado.
* @return bool un valor indicando si la regla permite al rol o permiso con el que está asociado.
@ -45,12 +45,12 @@ La méthode [[yii\base\Model::rules()|rules()]] doit retourner un tableau de rè
```php
[
// obligatoire, spécifie quels attributs doivent être validés par cette règle.
// Pour un attribut unique, vous pouvez utiliser le nom de l'attribut directement
// Pour un attribut unique, vous pouvez utiliser le nom de l'attribut directement
// sans le mettre dans un tableau
['attribute1', 'attribute2', ...],
// obligatoire, spécifier le type de cette règle.
// Il peut s'agir d'un nom de classe, d'un alias de validateur ou du nom d'une méthode de validation
// Il peut s'agir d'un nom de classe, d'un alias de validateur ou du nom d'une méthode de validation
'validator',
// facultatif, spécifie dans quel(s) scénario(s) cette règle doit être appliquée
@ -64,23 +64,23 @@ La méthode [[yii\base\Model::rules()|rules()]] doit retourner un tableau de rè
]
```
Pour chacune des règles vous devez spécifier au moins à quels attributs la règle s'applique et quel est le type de cette règle. Vous pouvez spécifier le type de la règle sous l'une des formes suivantes:
Pour chacune des règles vous devez spécifier au moins à quels attributs la règle s'applique et quel est le type de cette règle. Vous pouvez spécifier le type de la règle sous l'une des formes suivantes:
* l'alias d'un validateur du noyau, comme `required`, `in`, `date`, etc. Reportez-vous à la sous-section [Validateurs du noyau](tutorial-core-validators.md) pour une liste complète des validateurs du noyau.
* le nom d'une méthode de validation dans la classe du modèle, ou une fonction anonyme. Reportez-vous à la sous-section [Inline Validators](#inline-validators) pour plus de détails.
* un nom de classe de validateur pleinement qualifié. Reportez-vous à la sous-section [Validateurs autonomes](#standalone-validators) pour plus de détails.
Une règle peut être utilisée pour valider un ou plusieurs attributs, et un attribut peut être validé par une ou plusieurs règles. Une règle peut s'appliquer dans certains [scenarios](structure-models.md#scenarios) seulement en spécifiant l'option `on`. Si vous ne spécifiez pas l'option `on`, la règle s'applique à tous les scénarios.
Une règle peut être utilisée pour valider un ou plusieurs attributs, et un attribut peut être validé par une ou plusieurs règles. Une règle peut s'appliquer dans certains [scenarios](structure-models.md#scenarios) seulement en spécifiant l'option `on`. Si vous ne spécifiez pas l'option `on`, la règle s'applique à tous les scénarios.
Quand la méthode `validate()` est appelée, elle suit les étapes suivantes pour effectuer l'examen de validation:
1. Détermine quels attributs doivent être validés en obtenant la liste des attributs de [[yii\base\Model::scenarios()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces attributs sont appelés *attributs actifs*.
1. Détermine quels attributs doivent être validés en obtenant la liste des attributs de [[yii\base\Model::scenarios()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces attributs sont appelés *attributs actifs*.
2. Détermine quelles règles de validation doivent être appliquées en obtenant la liste des règles de [[yii\base\Model::rules()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces règles sont appelées *règles actives*.
3. Utilise chacune des règles actives pour valider chacun des attributs qui sont associés à cette règle. Les règles sont évaluées dans l'ordre dans lequel elles sont listées.
3. Utilise chacune des règles actives pour valider chacun des attributs qui sont associés à cette règle. Les règles sont évaluées dans l'ordre dans lequel elles sont listées.
Selon les étapes de validation décrites ci-dessus, un attribut est validé si, et seulement si, il est un attribut actif déclaré dans `scenarios()` et est associé à une ou plusieurs règles actives déclarées dans `rules()`.
> Note: il est pratique le nommer les règles, c.-à-d.
> Note: il est pratique le nommer les règles, c.-à-d.
>
> ```php
> public function rules()
@ -105,7 +105,7 @@ Selon les étapes de validation décrites ci-dessus, un attribut est validé si,
### Personnalisation des messages d'erreur <spanid="customizing-error-messages"></span>
La plupart des validateurs possèdent des messages d'erreurs qui sont ajoutés au modèle en cours de validation lorsque ses attributs ne passent pas la validation. Par exemple, le validateur [[yii\validators\RequiredValidator|required]] ajoute le message "Username cannot be blank." (Le nom d'utilisateur ne peut être vide.) au modèle lorsque l'attribut `username` ne passe pas la règle de validation utilisant ce validateur.
La plupart des validateurs possèdent des messages d'erreurs qui sont ajoutés au modèle en cours de validation lorsque ses attributs ne passent pas la validation. Par exemple, le validateur [[yii\validators\RequiredValidator|required]] ajoute le message "Username cannot be blank." (Le nom d'utilisateur ne peut être vide.) au modèle lorsque l'attribut `username` ne passe pas la règle de validation utilisant ce validateur.
Vous pouvez personnaliser le message d'erreur d'une règle en spécifiant la propriété `message` lors de la déclaration de la règle, comme ceci:
@ -118,14 +118,14 @@ public function rules()
}
```
Quelques validateurs peuvent prendre en charge des messages d'erreur additionnels pour décrire précisément les différentes causes de non validation. Par exemple, le validateur [[yii\validators\NumberValidator|number]] prend en charge[[yii\validators\NumberValidator::tooBig|tooBig (trop grand)]] et [[yii\validators\NumberValidator::tooSmall|tooSmall (trop petit)]] pour décrire la cause de non validation lorsque la valeur à valider est trop grande ou trop petite, respectivement. Vous pouvez configurer ces messages d'erreur comme vous configureriez d'autres propriétés de validateurs dans une règle de validation.
Quelques validateurs peuvent prendre en charge des messages d'erreur additionnels pour décrire précisément les différentes causes de non validation. Par exemple, le validateur [[yii\validators\NumberValidator|number]] prend en charge[[yii\validators\NumberValidator::tooBig|tooBig (trop grand)]] et [[yii\validators\NumberValidator::tooSmall|tooSmall (trop petit)]] pour décrire la cause de non validation lorsque la valeur à valider est trop grande ou trop petite, respectivement. Vous pouvez configurer ces messages d'erreur comme vous configureriez d'autres propriétés de validateurs dans une règle de validation.
### Événement de validation <spanid="validation-events"></span>
Losque la méthode [[yii\base\Model::validate()]] est appelée, elle appelle deux méthodes que vous pouvez redéfinir pour personnaliser le processus de validation:
* [[yii\base\Model::beforeValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_BEFORE_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de pré-traitement (p. ex. normaliser les données entrées) avant que l'examen de validation n'ait lieu. La méthode retourne une valeur booléenne indiquant si l'examen de validation doit avoir lieu ou pas.
* [[yii\base\Model::beforeValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_BEFORE_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de pré-traitement (p. ex. normaliser les données entrées) avant que l'examen de validation n'ait lieu. La méthode retourne une valeur booléenne indiquant si l'examen de validation doit avoir lieu ou pas.
* [[yii\base\Model::afterValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_AFTER_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de post-traitement après que l'examen de validation a eu lieu.
@ -145,7 +145,7 @@ La propriété [[yii\validators\Validator::when|when]] accepte une fonction de r
/**
* @param Model $model le modèle en cours de validation
* @param string $attribute l'attribut en cours de validation
* @return boolean`true` si la règle doit être appliqué, `false` si non
* @return bool `true` si la règle doit être appliqué, `false` si non
*/
function ($model, $attribute)
```
@ -163,7 +163,7 @@ Si vous avez aussi besoin de la prise en charge côté client de la validation c
### Filtrage des données <spanid="data-filtering"></span>
Les entrées utilisateur nécessitent souvent d'être filtrées ou pré-traitées. Par exemple, vous désirez peut-être vous débarrasser des espaces devant et derrière l'entrée `username`. Vous pouvez utiliser les règles de validation pour le faire.
Les entrées utilisateur nécessitent souvent d'être filtrées ou pré-traitées. Par exemple, vous désirez peut-être vous débarrasser des espaces devant et derrière l'entrée `username`. Vous pouvez utiliser les règles de validation pour le faire.
Les exemples suivants montrent comment se débarrasser des espaces dans les entrées et transformer des entrées vides en `nulls` en utilisant les validateurs du noyau [trim](tutorial-core-validators.md#trim) et [default](tutorial-core-validators.md#default):
@ -176,7 +176,7 @@ return [
Vous pouvez également utiliser le validateur plus général [filter](tutorial-core-validators.md#filter) pour accomplir un filtrage plus complexe des données.
Comme vous le voyez, ces règles de validation ne pratiquent pas un examen de validation proprement dit. Plus exactement, elles traitent les valeurs et les sauvegardent dans les attributs en cours de validation.
Comme vous le voyez, ces règles de validation ne pratiquent pas un examen de validation proprement dit. Plus exactement, elles traitent les valeurs et les sauvegardent dans les attributs en cours de validation.
### Gestion des entrées vides <spanid="handling-empty-inputs"></span>
@ -185,7 +185,7 @@ Lorsque les entrées sont soumises par des formulaires HTML, vous devez souvent
```php
return [
// définit "username" et "email" comme *null* si elles sont vides
// définit "username" et "email" comme *null* si elles sont vides
[['username', 'email'], 'default'],
// définit "level" à 1 si elle est vide
@ -206,7 +206,7 @@ Par défaut, une entrée est considérée vide si sa valeur est une chaîne de c
## Validation ad hoc <spanid="ad-hoc-validation"></span>
Parfois vous avez besoin de faire une *validation ad hoc* pour des valeurs qui ne sont pas liées à un modèle.
Parfois vous avez besoin de faire une *validation ad hoc* pour des valeurs qui ne sont pas liées à un modèle.
Si vous n'avez besoin d'effectuer qu'un seul type de validation (p. ex. valider une adresse de courriel), vous pouvez appeler la méthode [[yii\validators\Validator::validate()|validate()]] du validateur désiré, comme ceci:
@ -221,7 +221,7 @@ if ($validator->validate($email, $error)) {
}
```
> Note: tous les validateurs ne prennent pas en charge ce type de validation. Le validateur du noyau [unique](tutorial-core-validators.md#unique), qui est conçu pour travailler avec un modèle uniquement, en est un exemple.
> Note: tous les validateurs ne prennent pas en charge ce type de validation. Le validateur du noyau [unique](tutorial-core-validators.md#unique), qui est conçu pour travailler avec un modèle uniquement, en est un exemple.
Si vous avez besoin de validations multiples pour plusieurs valeurs, vous pouvez utiliser [[yii\base\DynamicModel]] qui prend en charge, à la fois les attributs et les règles à la volée. Son utilisation ressemble à ce qui suit:
@ -241,7 +241,7 @@ public function actionSearch($name, $email)
}
```
La méthode [[yii\base\DynamicModel::validateData()]] crée une instance de `DynamicModel`, définit les attributs utilisant les données fournies (`name` et `email` dans cet exemple), puis appelle [[yii\base\Model::validate()]] avec les règles données.
La méthode [[yii\base\DynamicModel::validateData()]] crée une instance de `DynamicModel`, définit les attributs utilisant les données fournies (`name` et `email` dans cet exemple), puis appelle [[yii\base\Model::validate()]] avec les règles données.
En alternative, vous pouvez utiliser la syntaxe plus *classique* suivante pour effectuer la validation ad hoc:
@ -266,7 +266,7 @@ Après l'examen de validation, vous pouvez vérifier si la validation a réussi
## Création de validateurs <spanid="creating-validators"></span>
En plus de pouvoir utiliser les [validateurs du noyau](tutorial-core-validators.md) inclus dans les versions publiées de Yii, vous pouvez également créer vos propres validateurs. Vous pouvez créer des validateurs en ligne et des validateurs autonomes.
En plus de pouvoir utiliser les [validateurs du noyau](tutorial-core-validators.md) inclus dans les versions publiées de Yii, vous pouvez également créer vos propres validateurs. Vous pouvez créer des validateurs en ligne et des validateurs autonomes.
### Validateurs en ligne <spanid="inline-validators"></span>
@ -281,7 +281,7 @@ Un validateur en ligne est un validateur défini sous forme de méthode de modè
function ($attribute, $params)
```
Si un attribut ne réussit pas l'examen de validation, la méthode/fonction doit appeler [[yii\base\Model::addError()]] pour sauvegarder le message d'erreur dans le modèle de manière à ce qu'il puisse être retrouvé plus tard pour être présenté à l'utilisateur.
Si un attribut ne réussit pas l'examen de validation, la méthode/fonction doit appeler [[yii\base\Model::addError()]] pour sauvegarder le message d'erreur dans le modèle de manière à ce qu'il puisse être retrouvé plus tard pour être présenté à l'utilisateur.
Voici quelques exemples:
@ -351,7 +351,7 @@ class CountryValidator extends Validator
Si vous voulez que votre validateur prennent en charge la validation d'une valeur sans modèle, vous devez redéfinir la méthode [[yii\validators\Validator::validate()]]. Vous pouvez aussi redéfinir [[yii\validators\Validator::validateValue()]] au lieu de `validateAttribute()` et `validate()`, parce que, par défaut, les deux dernières méthodes sont appelées en appelant `validateValue()`.
Ci-dessous, nous présentons un exemple de comment utiliser la classe de validateur précédente dans votre modèle.
Ci-dessous, nous présentons un exemple de comment utiliser la classe de validateur précédente dans votre modèle.
```php
namespace app\models;
@ -380,7 +380,7 @@ class EntryForm extends Model
## Validation côté client <spanid="client-side-validation"></span>
La validation côté client basée sur JavaScript est souhaitable lorsque l'utilisateur fournit les entrées via des formulaires HTML, parce que cela permet à l'utilisateur de détecter plus vite les erreurs et lui apporte ainsi un meilleur ressenti. Vous pouvez utiliser ou implémenter un validateur qui prend en charge la validation côté client *en plus* de la validation côté serveur.
La validation côté client basée sur JavaScript est souhaitable lorsque l'utilisateur fournit les entrées via des formulaires HTML, parce que cela permet à l'utilisateur de détecter plus vite les erreurs et lui apporte ainsi un meilleur ressenti. Vous pouvez utiliser ou implémenter un validateur qui prend en charge la validation côté client *en plus* de la validation côté serveur.
> Info: bien que la validation côté client soit souhaitable, ce n'est pas une obligation. Son but principal est d'apporter un meilleur ressenti à l'utilisateur. Comme pour les données venant de l'utilisateur, vous ne devriez jamais faire confiance à la validation côté client. Pour cette raison, vous devez toujours effectuer la validation côté serveur en appelant [[yii\base\Model::validate()]], comme nous l'avons décrit dans les sous-sections précédentes.
@ -433,7 +433,7 @@ Le formulaire HTML construit par le code suivant contient deux champs de saisie
En arrière plan, [[yii\widgets\ActiveForm]] lit les règles de validation déclarées dans le modèle et génère le code JavaScript approprié pour la prise en charge de la validation côté client. Lorsqu'un utilisateur modifie la valeur d'un champ de saisie ou soumet le formulaire, le code JavaScript est appelé.
Si vous désirez inhiber la validation côté client complètement, vous pouvez configurer la propriété [[yii\widgets\ActiveForm::enableClientValidation]] à `false` (faux). Vous pouvez aussi inhiber la validation côté client pour des champs de saisie individuels en configurant leur propriété [[yii\widgets\ActiveField::enableClientValidation]] à `false`. Lorsque `enableClientValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, c'est la première configuration qui prévaut.
Si vous désirez inhiber la validation côté client complètement, vous pouvez configurer la propriété [[yii\widgets\ActiveForm::enableClientValidation]] à `false` (faux). Vous pouvez aussi inhiber la validation côté client pour des champs de saisie individuels en configurant leur propriété [[yii\widgets\ActiveField::enableClientValidation]] à `false`. Lorsque `enableClientValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, c'est la première configuration qui prévaut.
### Mise en œuvre de la validation côté client <spanid="implementing-client-side-validation"></span>
@ -445,7 +445,7 @@ Pour créer un validateur qui prend en charge la validation côté client, vous
- `messages`: un tableau utilisé pour contenir les messages d'erreurs pour l'attribut;
- `deferred`: un tableau dans lequel les objets différés peuvent être poussés (explication dans la prochaine sous-section).
Dans l'exemple suivant, nous créons un `StatusValidator` qui valide une entrée si elle représente l'identifiant d'une donnée existante ayant un état valide. Le validateur prend en charge à la fois la validation côté serveur et la validation côté client.
Dans l'exemple suivant, nous créons un `StatusValidator` qui valide une entrée si elle représente l'identifiant d'une donnée existante ayant un état valide. Le validateur prend en charge à la fois la validation côté serveur et la validation côté client.
```php
namespace app\components;
@ -511,7 +511,7 @@ JS;
Dans ce qui précède, la variable `deferred` est fournie par Yii, et représente un tableau de d'objets différés. La méthode `$.get()` crée un objet différé qui est poussé dans le tableau `deferred`.
Vous pouvez aussi créer explicitement un objet différé et appeler sa méthode `resolve()` lorsque la fonction de rappel asynchrone est activée . L'exemple suivant montre comment valider les dimensions d'une image à charger sur le serveur du côté client.
Vous pouvez aussi créer explicitement un objet différé et appeler sa méthode `resolve()` lorsque la fonction de rappel asynchrone est activée . L'exemple suivant montre comment valider les dimensions d'une image à charger sur le serveur du côté client.
```php
public function clientValidateAttribute($model, $attribute, $view)
@ -538,7 +538,7 @@ JS;
> Note: La méthode `resolve()` doit être appelée après que l'attribut a été validé. Autrement la validation principale du formulaire ne se terminera pas.
Pour faire simple, le tableau `deferred` est doté d'une méthode raccourci `add()` qui crée automatiquement un objet différé et l'ajoute au tableau `deferred`. En utilisant cette méthode, vous pouvez simplifier l'exemple ci-dessus comme suit:
Pour faire simple, le tableau `deferred` est doté d'une méthode raccourci `add()` qui crée automatiquement un objet différé et l'ajoute au tableau `deferred`. En utilisant cette méthode, vous pouvez simplifier l'exemple ci-dessus comme suit:
```php
public function clientValidateAttribute($model, $attribute, $view)
@ -567,7 +567,7 @@ JS;
Quelques validations ne peuvent avoir lieu que côté serveur, parce que seul le serveur dispose des informations nécessaires. Par exemple, pour valider l'unicité d'un nom d'utilisateur, il est nécessaire de consulter la table des utilisateurs côté serveur. Vous pouvez utiliser la validation basée sur AJAX dans ce cas. Elle provoquera une requête AJAX en arrière plan pour exécuter l'examen de validation tout en laissant à l'utilisateur le même ressenti que lors d'une validation côté client normale.
Pour activer la validation AJAX pour un unique champ de saisie, configurez la propriété [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] de ce champ à `true` et spécifiez un `identifiant` unique de formulaire:
Pour activer la validation AJAX pour un unique champ de saisie, configurez la propriété [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] de ce champ à `true` et spécifiez un `identifiant` unique de formulaire:
```php
use yii\widgets\ActiveForm;
@ -592,7 +592,7 @@ $form = ActiveForm::begin([
]);
```
> Note: lorsque la propriété `enableAjaxValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, la première configuration prévaut.
> Note: lorsque la propriété `enableAjaxValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, la première configuration prévaut.
Vous devez aussi préparer le serveur de façon à ce qu'il puisse prendre en charge les requêtes de validation AJAX . Cela peut se faire à l'aide d'un fragment de code comme celui qui suit dans les actions de contrôleur:
L'authentification est le processus qui consiste à vérifier l'identité d'un utilisateur. Elle utilise ordinairement un identifiant (p. ex. un nom d'utilisateur ou une adresse de courriels) et un jeton secret (p. ex. un mot de passe ou un jeton d'accès) pour juger si l'utilisateur est bien qui il prétend être. L'authentification est à la base de la fonctionnalité de connexion.
Yii fournit une base structurée d'authentification qui interconnecte des composants variés pour prendre en charge la connexion. Pour utiliser cette base structurée, vous devez essentiellement accomplir les tâches suivantes:
* Configurer le composant d'application [[yii\web\User|user]];
* Créer une classe qui implémente l'interface [[yii\web\IdentityInterface]].
@ -13,7 +13,7 @@ Yii fournit une base structurée d'authentification qui interconnecte des compo
Le composant d'application [[yii\web\User|user]] gère l'état d'authentification de l'utilisateur. Il requiert que vous spécifiiez une [[yii\web\User::identityClass|classe d'identité]] contenant la logique réelle d'authentification.
Dans la configuration suivante de l'application, la [[yii\web\User::identityClass|classe d'identité]] pour [[yii\web\User|user]] est configurée sous le nom `app\models\User` dont la mise en œuvre est expliquée dans la sous-section suivante:
```php
return [
'components' => [
@ -30,12 +30,12 @@ return [
La [[yii\web\User::identityClass|classe d'identité]] doit implémenter l'interface [[yii\web\IdentityInterface]] qui comprend les méthodes suivantes:
* [[yii\web\IdentityInterface::findIdentity()|findIdentity()]]: cette méthode recherche une instance de la classe d'identité à partir de l'identifiant utilisateur spécifié. Elle est utilisée lorsque vous devez conserver l'état de connexion via et durant la session.
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: cette méthode recherche une instance de la classe d'identité à partir du jeton d'accès spécifié. Elle est utilisée lorsque vous avez besoin d'authentifier un utilisateur par un jeton secret (p. ex. dans une application pleinement REST sans état).
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: cette méthode recherche une instance de la classe d'identité à partir du jeton d'accès spécifié. Elle est utilisée lorsque vous avez besoin d'authentifier un utilisateur par un jeton secret (p. ex. dans une application pleinement REST sans état).
* [[yii\web\IdentityInterface::getId()|getId()]]: cette méthode retourne l'identifiant de l'utilisateur que cette instance de la classe d'identité représente.
* [[yii\web\IdentityInterface::getAuthKey()|getAuthKey()]]: cette méthode retourne une clé utilisée pour vérifier la connexion basée sur les témoins de connexion (*cookies*). La clé est stockée dans le témoin de connexion `login` et est ensuite comparée avec la version côté serveur pour s'assurer que le témoin de connexion est valide.
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: cette méthode met en œuvre la logique de vérification de la clé de connexion basée sur les témoins de connexion.
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: cette méthode met en œuvre la logique de vérification de la clé de connexion basée sur les témoins de connexion.
Si une méthode particulière n'est pas nécessaire, vous devez l'implémenter avec un corps vide. Par exemple, si votre application est une application sans état et pleinement REST, vous devez seulement implémenter [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]] et [[yii\web\IdentityInterface::getId()|getId()]] et laisser toutes les autres méthodes avec un corps vide.
Si une méthode particulière n'est pas nécessaire, vous devez l'implémenter avec un corps vide. Par exemple, si votre application est une application sans état et pleinement REST, vous devez seulement implémenter [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]] et [[yii\web\IdentityInterface::getId()|getId()]] et laisser toutes les autres méthodes avec un corps vide.
Dans l'exemple qui suit, une [[yii\web\User::identityClass|classe d'identité]] est mise en œuvre en tant que classe [Active Record](db-active-record.md) associée à la table de base de données `user`.
@ -55,8 +55,8 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Trouve une identité à partir de l'identifiant donné.
*
* @param string|integer $id l'identifiant à rechercher
* @return IdentityInterface|null l'objet identité qui correspond à l'identifiant donné
* @param string|int $id l'identifiant à rechercher
* @return IdentityInterface|null l'objet identité qui correspond à l'identifiant donné
*/
public static function findIdentity($id)
{
@ -64,7 +64,7 @@ class User extends ActiveRecord implements IdentityInterface
}
/**
* Trouve une identité à partir du jeton donné
* Trouve une identité à partir du jeton donné
*
* @param string $token le jeton à rechercher
* @return IdentityInterface|null l'objet identité qui correspond au jeton donné
@ -92,7 +92,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean si la clé d'authentification est valide pour l'utilisateur courant
* @return bool si la clé d'authentification est valide pour l'utilisateur courant
*/
public function validateAuthKey($authKey)
{
@ -107,7 +107,7 @@ Comme nous l'avons expliqué précédemment, vous devez seulement implémenter `
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -121,12 +121,12 @@ class User extends ActiveRecord implements IdentityInterface
}
```
> Note: ne confondez pas la classe d'identité `User` avec la classe [[yii\web\User]]. La première est la classe mettant en œuvre la logique d'authentification. Elle est souvent mise en œuvre sous forme de classe [Active Record](db-active-record.md) associée à un moyen de stockage persistant pour conserver les éléments d'authentification de l'utilisateur. La deuxième est une classe de composant d'application qui gère l'état d'authentification de l'utilisateur.
> Note: ne confondez pas la classe d'identité `User` avec la classe [[yii\web\User]]. La première est la classe mettant en œuvre la logique d'authentification. Elle est souvent mise en œuvre sous forme de classe [Active Record](db-active-record.md) associée à un moyen de stockage persistant pour conserver les éléments d'authentification de l'utilisateur. La deuxième est une classe de composant d'application qui gère l'état d'authentification de l'utilisateur.
## Utilisation de [[yii\web\User]] <spanid="using-user"></span>
Vous utilisez [[yii\web\User]] essentiellement en terme de composant d'application `user`.
Vous utilisez [[yii\web\User]] essentiellement en terme de composant d'application `user`.
Vous pouvez détecter l'identité de l'utilisateur courant en utilisant l'expression `Yii::$app->user->identity`. Elle retourne une instance de la [[yii\web\User::identityClass|classe d'identité]] représentant l'utilisateur connecté actuellement ou `null` si l'utilisateur courant n'est pas authentifié (soit un simple visiteur). Le code suivant montre comment retrouver les autres informations relatives à l'authentification à partir de [[yii\web\User]]:
La méthode [[yii\web\User::login()]] assigne l'identité de l'utilisateur courant à [[yii\web\User]]. Si la session est [[yii\web\User::enableSession|activée]], elle conserve l'identité de façon à ce que l'état d'authentification de l'utilisateur soit maintenu durant la session tout entière. Si la connexion basée sur les témoins de connexion (*cookies*) est [[yii\web\User::enableAutoLogin|activée]], elle sauvegarde également l'identité dans un témoin de connexion de façon à ce que l'état d'authentification de l'utilisateur puisse être récupéré du témoin de connexion durant toute la période de validité du témoin de connexion.
Pour activer la connexion basée sur les témoins de connexion, vous devez configurer [[yii\web\User::enableAutoLogin]] à `true` (vrai) dans la configuration de l'application. Vous devez également fournir une durée de vie lorsque vous appelez la méthode [[yii\web\User::login()]].
Pour activer la connexion basée sur les témoins de connexion, vous devez configurer [[yii\web\User::enableAutoLogin]] à `true` (vrai) dans la configuration de l'application. Vous devez également fournir une durée de vie lorsque vous appelez la méthode [[yii\web\User::login()]].
Pour déconnecter un utilisateur, appelez simplement
Pour déconnecter un utilisateur, appelez simplement
```php
Yii::$app->user->logout();
@ -167,13 +167,13 @@ Notez que déconnecter un utilisateur n'a de sens que si la session est activée
La classe [[yii\web\User]] lève quelques événements durant le processus de connexion et celui de déconnexion.
La classe [[yii\web\User]] lève quelques événements durant le processus de connexion et celui de déconnexion.
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: levé au début de [[yii\web\User::login()]].
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] de l'objet événement à `false` (faux), le processus de connexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: levé après une connexion réussie.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: levé au début de [[yii\web\User::logout()]].
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] à `false` (faux) le processus de déconnexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: levé après une déconnexion réussie.
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] à `false` (faux) le processus de déconnexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: levé après une déconnexion réussie.
Vous pouvez répondre à ces événements pour mettre en œuvre des fonctionnalités telles que l'audit de connexion, les statistiques d'utilisateurs en ligne. Par exemple, dans le gestionnaire pour l'événement [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]], vous pouvez enregistrer le temps de connexion et l'adresse IP dans la tale `user`.
L'autorisation est le processus qui vérifie si un utilisateur dispose des permissions suffisantes pour faire quelque chose. Yii fournit deux méthodes d'autorisation: le filtre de contrôle d'accès (ACF — Access Control Filter) et le contrôle d'accès basé sur les rôles (RBAC — Role-Based Access Control).
L'autorisation est le processus qui vérifie si un utilisateur dispose des permissions suffisantes pour faire quelque chose. Yii fournit deux méthodes d'autorisation: le filtre de contrôle d'accès (ACF — Access Control Filter) et le contrôle d'accès basé sur les rôles (RBAC — Role-Based Access Control).
## Filtre de contrôle d'accès <spanid="access-control-filter"></span>
@ -43,8 +43,8 @@ class SiteController extends Controller
Dans le code précédent, le filtre de contrôle d'accès est attaché au contrôleur `site` en tant que comportement (*behavior*). C'est la manière typique d'utiliser un filtre d'action. L'option `only` spécifie que le filtre de contrôle d'accès doit seulement être appliqué aux actions `login`, `logout` et `signup`. Toutes les autres actions dans le contrôleur `site`ne sont pas sujettes au contrôle d'accès. L'option `rules` liste les [[yii\filters\AccessRule|règles d'accès]], qui se lisent comme suit:
- Autorise tous les visiteurs (non encore authentifiés) à accéder aux actions `login` et `signup`. l'option `roles` contient un point d'interrogation `?` qui est un signe particulier représentant les «visiteurs non authentifiés».
- Autorise les utilisateurs authentifiés à accéder à l'action `logout`. L'arobase `@` est un autre signe particulier représentant les «utilisateurs authentifiés».
- Autorise tous les visiteurs (non encore authentifiés) à accéder aux actions `login` et `signup`. l'option `roles` contient un point d'interrogation `?` qui est un signe particulier représentant les «visiteurs non authentifiés».
- Autorise les utilisateurs authentifiés à accéder à l'action `logout`. L'arobase `@` est un autre signe particulier représentant les «utilisateurs authentifiés».
Le filtre de contrôle d'accès effectue les vérifications d'autorisation en examinant les règles d'accès une par une en commençant par le haut, jusqu'à ce qu'il trouve une règle qui correspond au contexte d'exécution courant. La valeur `allow` de la règle correspondante est utilisée ensuite pour juger si l'utilisateur est autorisé ou pas. Si aucune des règles ne correspond, cela signifie que l'utilisateur n'est PAS autorisé, et le filtre de contrôle d'accès arrête la suite de l'exécution de l'action.
@ -69,24 +69,24 @@ Les [[yii\filters\AccessRule|règles d'accès]] acceptent beaucoup d'options. Ci
* [[yii\filters\AccessRule::allow|allow]]: spécifie s'il s'agit d'une règle "allow" (autorise) ou "deny" (refuse).
* [[yii\filters\AccessRule::actions|actions]]: spécifie à quelles actions cette règle correspond. Ce doit être un tableau d'identifiants d'action. La comparaison est sensible à la casse. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les actions.
* [[yii\filters\AccessRule::actions|actions]]: spécifie à quelles actions cette règle correspond. Ce doit être un tableau d'identifiants d'action. La comparaison est sensible à la casse. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les actions.
* [[yii\filters\AccessRule::controllers|controllers]]: spécifie à quels contrôleurs cette règle correspond. Ce doit être un tableau d'identifiants de contrôleurs. Si cette option est vide ou non définie, la règle s'applique à tous les contrôleurs.
* [[yii\filters\AccessRule::controllers|controllers]]: spécifie à quels contrôleurs cette règle correspond. Ce doit être un tableau d'identifiants de contrôleurs. Si cette option est vide ou non définie, la règle s'applique à tous les contrôleurs.
* [[yii\filters\AccessRule::roles|roles]]: spécifie à quels rôles utilisateur cette règle correspond. Deux rôles spéciaux sont reconnus, et ils sont vérifiés via [[yii\web\User::isGuest]]:
- `?`: correspond à un visiteur non authentifié.
- `@`: correspond à un visiteur authentifié.
L'utilisation d'autres noms de rôle déclenche l'appel de [[yii\web\User::can()]], qui requiert l'activation du contrôle d'accès basé sur les rôles qui sera décrit dans la prochaine sous-section. Si cette option est vide ou non définie, cela signifie que la règle s'applique à tous les rôles.
L'utilisation d'autres noms de rôle déclenche l'appel de [[yii\web\User::can()]], qui requiert l'activation du contrôle d'accès basé sur les rôles qui sera décrit dans la prochaine sous-section. Si cette option est vide ou non définie, cela signifie que la règle s'applique à tous les rôles.
* [[yii\filters\AccessRule::ips|ips]]: spécifie à quelles [[yii\web\Request::userIP|adresses IP de client]] cette règle correspond. Une adresse IP peut contenir le caractère générique `*` à la fin pour indiquer que la règle correspond à des adresses IPayant le même préfixe. Par exemple, '192.168.*' correspond à toutes les adresse IP dans le segment '192.168.'. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les adresses IP.
* [[yii\filters\AccessRule::verbs|verbs]]: spécifie à quelles méthodes de requête (p. ex. `GET`, `POST`) cette règle correspond. La comparaison est insensible à la casse.
* [[yii\filters\AccessRule::verbs|verbs]]: spécifie à quelles méthodes de requête (p. ex. `GET`, `POST`) cette règle correspond. La comparaison est insensible à la casse.
* [[yii\filters\AccessRule::matchCallback|matchCallback]]: spécifie une fonction de rappel PHP qui peut être appelée pour déterminer si cette règle s'applique.
* [[yii\filters\AccessRule::matchCallback|matchCallback]]: spécifie une fonction de rappel PHP qui peut être appelée pour déterminer si cette règle s'applique.
* [[yii\filters\AccessRule::denyCallback|denyCallback]]: spécifie une fonction de rappel PHP qui peut être appelée lorsqu'une règle refuse l'accès.
* [[yii\filters\AccessRule::denyCallback|denyCallback]]: spécifie une fonction de rappel PHP qui peut être appelée lorsqu'une règle refuse l'accès.
Ci-dessous nous présentons un exemple qui montre comment utiliser l'option `matchCallback`, qui vous permet d'écrire une logique d'accès arbitraire:
@ -125,26 +125,26 @@ class SiteController extends Controller
## Contrôle d'accès basé sur les rôles <spanid="rbac"></span>
Le contrôle d'accès basé sur les rôles (Role-Based Access Control – RBAC) fournit un contrôle d'accès centralisé simple mais puissant. Reportez-vous à [Wikipedia](http://en.wikipedia.org/wiki/Role-based_access_control) pour des détails comparatifs entre le contrôle d'accès basé sur les rôles et d'autres schéma de contrôle d'accès plus traditionnels.
Le contrôle d'accès basé sur les rôles (Role-Based Access Control – RBAC) fournit un contrôle d'accès centralisé simple mais puissant. Reportez-vous à [Wikipedia](http://en.wikipedia.org/wiki/Role-based_access_control) pour des détails comparatifs entre le contrôle d'accès basé sur les rôles et d'autres schéma de contrôle d'accès plus traditionnels.
Yii met en œuvre un contrôle d'accès basé sur les rôlesgénéral hiérarchisé, qui suit le [modèle NIST RBAC](http://csrc.nist.gov/rbac/sandhu-ferraiolo-kuhn-00.pdf). Il fournit la fonctionnalité de contrôle d'accès basé sur les rôles via le [composant d'application](structure-application-components.md)[[yii\RBAC\ManagerInterface|authManager]].
L'utilisation du contrôle d'accès basé sur les rôles implique deux partie de travail. La première partie est de construire les données d'autorisation du contrôle d'accès basé sur les rôles, et la seconde partie est d'utiliser les données d'autorisation pour effectuer les vérifications d'autorisation d'accès là où elles sont nécessaires.
L'utilisation du contrôle d'accès basé sur les rôles implique deux partie de travail. La première partie est de construire les données d'autorisation du contrôle d'accès basé sur les rôles, et la seconde partie est d'utiliser les données d'autorisation pour effectuer les vérifications d'autorisation d'accès là où elles sont nécessaires.
Pour faciliter la description qui suit, nous allons d'abord introduire quelques concepts sur le contrôle d'accès basé sur les rôles.
Pour faciliter la description qui suit, nous allons d'abord introduire quelques concepts sur le contrôle d'accès basé sur les rôles.
### Concepts de base <spanid="basic-concepts"></span>
Un rôle représente une collection de *permissions* (p. ex. créer des articles, mettre des articles à jour). Un rôle peut être assigné à un ou plusieurs utilisateurs. Pour vérifier qu'un utilisateur dispose d'une permission spécifiée, nous pouvons vérifier si un rôle contenant cette permission a été assigné à l'utilisateur.
Un rôle représente une collection de *permissions* (p. ex. créer des articles, mettre des articles à jour). Un rôle peut être assigné à un ou plusieurs utilisateurs. Pour vérifier qu'un utilisateur dispose d'une permission spécifiée, nous pouvons vérifier si un rôle contenant cette permission a été assigné à l'utilisateur.
Associée à chacun des rôles, il peut y avoir une *règle*. Une règle représente un morceau de code à exécuter lors de l'accès pour vérifier si le rôle correspondant, ou la permission correspondante, s'applique à l'utilisateur courant. Par exemple, la permission «mettre un article à jour» peut disposer d'une règle qui vérifie si l'utilisateur courant est celui qui a créé l'article. Durant la vérification de l'accès, si l'utilisateur n'est PAS le créateur de l'article, il est considéré comme ne disposant pas la permission «mettre un article à jour».
Associée à chacun des rôles, il peut y avoir une *règle*. Une règle représente un morceau de code à exécuter lors de l'accès pour vérifier si le rôle correspondant, ou la permission correspondante, s'applique à l'utilisateur courant. Par exemple, la permission «mettre un article à jour» peut disposer d'une règle qui vérifie si l'utilisateur courant est celui qui a créé l'article. Durant la vérification de l'accès, si l'utilisateur n'est PAS le créateur de l'article, il est considéré comme ne disposant pas la permission «mettre un article à jour».
À la fois les rôles et les permissions peuvent être organisés en une hiérarchie. En particulier, un rôle peut être constitué d'autres rôles ou permissions; Yii met en œuvre une hiérarchie *d'ordre partiel* qui inclut la hiérarchie plus spécifique dite *en arbre*. Tandis qu'un rôle peut contenir une permission, l'inverse n'est pas vrai.
À la fois les rôles et les permissions peuvent être organisés en une hiérarchie. En particulier, un rôle peut être constitué d'autres rôles ou permissions; Yii met en œuvre une hiérarchie *d'ordre partiel* qui inclut la hiérarchie plus spécifique dite *en arbre*. Tandis qu'un rôle peut contenir une permission, l'inverse n'est pas vrai.
### Configuration du contrôle d'accès basé sur les rôles <spanid="configuring-rbac"></span>
Avant que nous ne nous lancions dans la définition des données d'autorisation et effectuions la vérification d'autorisation d'accès, nous devons configurer le composant d'application [[yii\base\Application::authManager|gestionnaire d'autorisations (*authManager*)]]. Yii fournit deux types de gestionnaires d'autorisations: [[yii\rbac\PhpManager]] et [[yii\rbac\DbManager]]. Le premier utilise un script PHP pour stocker les données d'autorisation, tandis que le second stocke les données d'autorisation dans une base de données. Vous pouvez envisager d'utiliser le premier si votre application n'a pas besoin d'une gestion des rôles et des permissions très dynamique.
Avant que nous ne nous lancions dans la définition des données d'autorisation et effectuions la vérification d'autorisation d'accès, nous devons configurer le composant d'application [[yii\base\Application::authManager|gestionnaire d'autorisations (*authManager*)]]. Yii fournit deux types de gestionnaires d'autorisations: [[yii\rbac\PhpManager]] et [[yii\rbac\DbManager]]. Le premier utilise un script PHP pour stocker les données d'autorisation, tandis que le second stocke les données d'autorisation dans une base de données. Vous pouvez envisager d'utiliser le premier si votre application n'a pas besoin d'une gestion des rôles et des permissions très dynamique.
#### Utilisation de `PhpManager`<spanid="using-php-manager"></span>
@ -165,7 +165,7 @@ return [
Le gestionnaire `authManager` peut désormais être obtenu via `\Yii::$app->authManager`.
Par défaut, [[yii\rbac\PhpManager]] stocke les données du contrôle d'accès basé sur les rôles dans des fichiers du dossier `@app/rbac`. Assurez-vous que le dossier et tous les fichiers qui sont dedans sont accessibles en écriture par le processus du serveur Web si la hiérarchie des permissions a besoin d'être changée en ligne.
Par défaut, [[yii\rbac\PhpManager]] stocke les données du contrôle d'accès basé sur les rôles dans des fichiers du dossier `@app/rbac`. Assurez-vous que le dossier et tous les fichiers qui sont dedans sont accessibles en écriture par le processus du serveur Web si la hiérarchie des permissions a besoin d'être changée en ligne.
#### Utilisation de `DbManager`<spanid="using-db-manager"></span>
@ -187,7 +187,7 @@ return [
> Dans le cas du modèle yii2-advanced-app, la propriété `authManager` doit être déclarée seulement une fois dans `common/config/main.php`.
`DbManager` utilise quatre tables de base de données pour stocker ses données:
`DbManager` utilise quatre tables de base de données pour stocker ses données:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: la table pour stocker les items d'autorisation. Valeur par défaut «auth_item».
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: la table pour stocker la hiérarchie des items d'autorisation. Valeur par défaut «auth_item_child».
@ -228,7 +228,7 @@ class RbacController extends Controller
@ -264,7 +264,7 @@ Après avoir exécuté la commande `yii rbac/init` vous vous retrouverez avec la
![Hiérarchie simple du contrôle d'accès basé sur les rôles](images/rbac-hierarchy-1.png "Simple RBAC hierarchy")
Le rôle *Author* peut créer des articles, le rôle *admin* peut mettre les articles à jour et faire tout ce que le rôle *author* peut faire.
Le rôle *Author* peut créer des articles, le rôle *admin* peut mettre les articles à jour et faire tout ce que le rôle *author* peut faire.
Si votre application autorise l'enregistrement des utilisateurs, vous devez assigner des rôles à ces nouveaux utilisateurs une fois. Par exemple, afin que tous les utilisateurs enregistrés deviennent des auteurs (rôle *author*) dans votre modèle de projet avancé, vous devez modifier la méthode `frontend\models\SignupForm::signup()` comme indiqué ci-dessous:
@ -311,10 +311,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user l'identifiant de l'utilisateur.
* @param Item $item le rôle ou la permission avec laquelle cette règle est associée
* @param string|int $user l'identifiant de l'utilisateur.
* @param Item $item le rôle ou la permission avec laquelle cette règle est associée
* @param array $params les paramètres passés à ManagerInterface::checkAccess().
* @return boolean une valeur indiquant si la règles autorise le rôle ou la permission qui lui est associé.
* @return bool une valeur indiquant si la règles autorise le rôle ou la permission qui lui est associé.
*/
public function execute($user, $item, $params)
{
@ -377,7 +377,7 @@ Ici que se passe-t-il si l'utilisateur courant est John:
Nous commençons à `updatePost` et passons par `updateOwnPost`. Afin d'obtenir l'autorisation, la méthode `execute()` de `AuthorRule` doit retourner `true` (vrai). La méthode reçoit ses paramètres `$params` de l'appel à la méthode `can()` et sa valeur est ainsi `['post' => $post]`. Si tout est bon, nous arrivons à `author` auquel John est assigné.
Nous commençons à `updatePost` et passons par `updateOwnPost`. Afin d'obtenir l'autorisation, la méthode `execute()` de `AuthorRule` doit retourner `true` (vrai). La méthode reçoit ses paramètres `$params` de l'appel à la méthode `can()` et sa valeur est ainsi `['post' => $post]`. Si tout est bon, nous arrivons à `author` auquel John est assigné.
Dans le cas de Jane, c'est un peu plus simple puisqu'elle a le rôle admin:
@ -427,11 +427,11 @@ Si toutes les opérations CRUD sont gérées ensemble, alors c'est une bonne id
### Utilisation des rôles par défaut <spanid="using-default-roles"></span>
Un rôle par défaut est un rôle qui est assigné *implicitement* à tous les *utilisateurs*. L'appel de la méthode [[yii\rbac\ManagerInterface::assign()]] n'est pas nécessaire, et les données d'autorisations ne contiennent pas ses informations d'assignation.
Un rôle par défaut est un rôle qui est assigné *implicitement* à tous les *utilisateurs*. L'appel de la méthode [[yii\rbac\ManagerInterface::assign()]] n'est pas nécessaire, et les données d'autorisations ne contiennent pas ses informations d'assignation.
Un rôle par défaut est ordinairement associé à une règle qui détermine si le rôle s'applique à l'utilisateur en cours de vérification.
Les rôles par défaut sont souvent utilisés dans des applications qui ont déjà une sorte d'assignation de rôles. Par exemple, un application peut avoir une colonne «group» dans sa table des utilisateurs pour représenter à quel groupe de privilèges chacun des utilisateurs appartient. Si chaque groupe de privilèges peut être mis en correspondance avec un rôle du contrôle d'accès basé sur les rôles, vous pouvez utiliser la fonctionnalité de rôle par défaut pour assigner automatiquement un rôle du contrôle d'accès basé sur les rôles à chacun des utilisateurs. Prenons un exemple pour montrer comment cela se fait.
Les rôles par défaut sont souvent utilisés dans des applications qui ont déjà une sorte d'assignation de rôles. Par exemple, un application peut avoir une colonne «group» dans sa table des utilisateurs pour représenter à quel groupe de privilèges chacun des utilisateurs appartient. Si chaque groupe de privilèges peut être mis en correspondance avec un rôle du contrôle d'accès basé sur les rôles, vous pouvez utiliser la fonctionnalité de rôle par défaut pour assigner automatiquement un rôle du contrôle d'accès basé sur les rôles à chacun des utilisateurs. Prenons un exemple pour montrer comment cela se fait.
Supposons que dans la table des utilisateurs, il existe en colonne `group` qui utilise la valeur 1 pour représenter le groupe des administrateurs et la valeur 2 pour représenter le groupe des auteurs. Vous envisagez d'avoir deux rôles dans le contrôle d'accès basé sur les rôles `admin` et`author` pour représenter les permissions de ces deux groupes respectivement. Vous pouvez configurer le contrôle d'accès basé sur les rôles comme suit :
@ -443,7 +443,7 @@ use Yii;
use yii\rbac\Rule;
/**
* Vérifie si le groupe utilisateurs correspond
* Vérifie si le groupe utilisateurs correspond
*/
class UserGroupRule extends Rule
{
@ -497,4 +497,4 @@ return [
];
```
Désormais, si vous effectuez une vérification d'autorisation d'accès, les deux rôles `admin` et `author` seront vérifiés en évaluant les règles qui leur sont associées. Si les règles retournent `true` (vrai), cela signifie que le rôle s'applique à l'utilisateur courant. En se basant sur la mise en œuvre des règles ci-dessus, cela signifie que si la valeur du `group` d'un utilisateur est 1, le rôle `admin` s'applique à l'utilisateur, si la valeur du `group` est 2, le rôle `author` s'applique.
Désormais, si vous effectuez une vérification d'autorisation d'accès, les deux rôles `admin` et `author` seront vérifiés en évaluant les règles qui leur sont associées. Si les règles retournent `true` (vrai), cela signifie que le rôle s'applique à l'utilisateur courant. En se basant sur la mise en œuvre des règles ci-dessus, cela signifie que si la valeur du `group` d'un utilisateur est 1, le rôle `admin` s'applique à l'utilisateur, si la valeur du `group` est 2, le rôle `author` s'applique.
Jedna z głównych zasad mówi, że nigdy nie należy ufać danym otrzymanym od użytkownika oraz że zawsze należy walidować je przed użyciem.
Rozważmy [model](structure-models.md) wypełniony danymi pobranymi od użytkownika. Możemy zweryfikować je poprzez wywołanie metody [[yii\base\Model::validate()|validate()]].
Metoda zwróci wartość `boolean` wskazującą, czy walidacja się powiodła, czy też nie. Jeśli nie, można pobrać informacje o błędach za pomocą właściwości
Metoda zwróci wartość `boolean` wskazującą, czy walidacja się powiodła, czy też nie. Jeśli nie, można pobrać informacje o błędach za pomocą właściwości
[[yii\base\Model::errors|errors]].
Dla przykładu,
Dla przykładu,
```php
$model = new \app\models\ContactForm();
@ -28,7 +28,7 @@ if ($model->validate()) {
## Deklaracja zasad <spanid="declaring-rules"></span>
Aby metoda [[yii\base\Model::validate()|validate()]] naprawdę zadziałała, należy zdefiniować zasady walidacji dla atrybutów, które mają jej podlegać.
Powinno zostać to zrobione przez nadpisanie metody [[yii\base\Model::rules()|rules()]]. Poniższy przykład pokazuje jak zostały zadeklarowane zasady walidacji dla modelu
Powinno zostać to zrobione przez nadpisanie metody [[yii\base\Model::rules()|rules()]]. Poniższy przykład pokazuje jak zostały zadeklarowane zasady walidacji dla modelu
`ContactForm`:
```php
@ -66,10 +66,10 @@ Metoda [[yii\base\Model::rules()|rules()]] powinna zwracać tablicę zasad, gdzi
]
```
Dla każdej z zasad musisz określić co najmniej jeden atrybut, którego ma ona dotyczyć, oraz określić rodzaj zasady jako
Dla każdej z zasad musisz określić co najmniej jeden atrybut, którego ma ona dotyczyć, oraz określić rodzaj zasady jako
jedną z następujących form:
* alias walidatora podstawowego, np. `required`, `in`, `date` itd. Zajrzyj do sekcji [Podstawowe walidatory](tutorial-core-validators.md),
* alias walidatora podstawowego, np. `required`, `in`, `date` itd. Zajrzyj do sekcji [Podstawowe walidatory](tutorial-core-validators.md),
aby uzyskać pełną listę walidatorów podstawowych.
* nazwa metody walidacji w klasie modelu lub funkcja anonimowa. Po więcej szczegółów zajrzyj do sekcji [Walidatory wbudowane](#inline-validators).
* pełna nazwa klasy walidatora. Po więcej szczegółów zajrzyj do sekcji [Walidatory niezależne](#standalone-validators).
@ -80,14 +80,14 @@ Jeśli nie dodasz opcji `on` oznacza to, że zasada zostanie użyta w każdym sc
Wywołanie metody [[yii\base\Model::validate()|validate()]] powoduje podjęcie następujących kroków w celu wykonania walidacji:
1. Określenie, które atrybuty powinny zostać zweryfikowane poprzez pobranie ich listy z metody [[yii\base\Model::scenarios()|scenarios()]], używając aktualnego
1. Określenie, które atrybuty powinny zostać zweryfikowane poprzez pobranie ich listy z metody [[yii\base\Model::scenarios()|scenarios()]], używając aktualnego
[[yii\base\Model::scenario|scenariusza]]. Wybrane atrybuty nazywane są *atrybutami aktywnymi*.
2. Określenie, które zasady walidacji powinny zostać użyte przez pobranie ich listy z metody [[yii\base\Model::rules()|rules()]], używając aktualnego
2. Określenie, które zasady walidacji powinny zostać użyte przez pobranie ich listy z metody [[yii\base\Model::rules()|rules()]], używając aktualnego
[[yii\base\Model::scenario|scenariusza]]. Wybrane zasady nazywane są *zasadami aktywnymi*.
3. Użycie każdej aktywnej zasady do walidacji każdego aktywnego atrybutu, który jest powiązany z konkretną zasadą. Zasady walidacji są wykonywane w kolejności,
3. Użycie każdej aktywnej zasady do walidacji każdego aktywnego atrybutu, który jest powiązany z konkretną zasadą. Zasady walidacji są wykonywane w kolejności,
w jakiej zostały zapisane.
Odnosząc się do powyższych kroków, atrybut zostanie zwalidowany wtedy i tylko wtedy, gdy jest on aktywnym atrybutem zadeklarowanym w
Odnosząc się do powyższych kroków, atrybut zostanie zwalidowany wtedy i tylko wtedy, gdy jest on aktywnym atrybutem zadeklarowanym w
[[yii\base\Model::scenarios()|scenarios()]] oraz jest powiązany z jedną lub wieloma aktywnymi zasadami zadeklarowanymi w [[yii\base\Model::rules()|rules()]].
> Note: Czasem użyteczne jest nadanie nazwy zasadzie np.
@ -131,8 +131,8 @@ public function rules()
```
Niektóre walidatory mogą wspierać dodatkowe wiadomości błedów, aby bardziej precyzyjnie określić problemy powstałe przy walidacji.
Dla przykładu, walidator [[yii\validators\NumberValidator|number]] dodaje [[yii\validators\NumberValidator::tooBig|tooBig]] oraz
[[yii\validators\NumberValidator::tooSmall|tooSmall]] do opisania sytuacji, kiedy poddawana walidacji liczba jest za duża lub za mała.
Dla przykładu, walidator [[yii\validators\NumberValidator|number]] dodaje [[yii\validators\NumberValidator::tooBig|tooBig]] oraz
[[yii\validators\NumberValidator::tooSmall|tooSmall]] do opisania sytuacji, kiedy poddawana walidacji liczba jest za duża lub za mała.
Możesz skonfigurować te wiadomości tak, jak pozostałe właściwości walidatorów podczas deklaracji zasady.
@ -140,10 +140,10 @@ Możesz skonfigurować te wiadomości tak, jak pozostałe właściwości walidat
Podczas wywołania metody [[yii\base\Model::validate()|validate()]] zostaną wywołane dwie metody, które możesz nadpisać, aby dostosować proces walidacji:
Możesz nadpisać tę metodę lub odnieść się do zdarzenia, aby wykonać dodatkowe operacje po zakończonej walidacji.
@ -166,7 +166,7 @@ Właściwość [[yii\validators\Validator::when|when]] pobiera możliwą do wywo
/**
* @param Model $model model, który podlega walidacji
* @param string $attribute atrybut, który podlega walidacji
* @return boolean wartość zwrotna; czy reguła powinna zostać zastosowana
* @return bool wartość zwrotna; czy reguła powinna zostać zastosowana
*/
function ($model, $attribute)
```
@ -188,10 +188,10 @@ Dla przykładu,
### Filtrowanie danych <spanid="data-filtering"></span>
Dane od użytkownika często muszą zostać przefiltrowane. Dla przykładu, możesz chcieć wyciąć znaki spacji na początku i na końcu pola `username`.
Dane od użytkownika często muszą zostać przefiltrowane. Dla przykładu, możesz chcieć wyciąć znaki spacji na początku i na końcu pola `username`.
Aby osiągnąć ten cel, możesz również użyć zasad walidacji.
Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić puste pole na wartość `null` przy użyciu podstawowych walidatorów
Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić puste pole na wartość `null` przy użyciu podstawowych walidatorów
[trim](tutorial-core-validators.md#trim) oraz [default](tutorial-core-validators.md#default):
```php
@ -203,7 +203,7 @@ Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić pus
Możesz użyć również bardziej ogólnego walidatora [filter](tutorial-core-validators.md#filter), aby przeprowadzić złożone filtrowanie.
Jak pewnie zauważyłeś, te zasady walidacji tak naprawdę nie walidują danych. Zamiast tego przetwarzają wartości, a następnie przypisują je do atrybutów,
Jak pewnie zauważyłeś, te zasady walidacji tak naprawdę nie walidują danych. Zamiast tego przetwarzają wartości, a następnie przypisują je do atrybutów,
* @param mixed $params wartość parametru podanego w zasadzie walidacji
* @param mixed $params wartość parametru podanego w zasadzie walidacji
*/
function ($attribute, $params)
```
@ -359,7 +359,7 @@ class MyForm extends Model
```
> Note: Domyślnie wbudowane walidatory nie zostaną zastosowane, jeśli ich powiązane atrybuty otrzymają puste wartości lub wcześniej nie przeszły którejś z zasad walidacji.
> Jeśli chcesz się upewnić, że zasada zawsze zostanie zastosowana, możesz skonfigurować właściwość [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] i/lub
> Jeśli chcesz się upewnić, że zasada zawsze zostanie zastosowana, możesz skonfigurować właściwość [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] i/lub
> [[yii\validators\Validator::skipOnError|skipOnError]], przypisując jej wartość `false` w deklaracji zasady walidacji. Dla przykładu:
Walidator niezależy jest klasą rozszerzającą [[yii\validators\Validator|Validator]] lub klasy po nim dziedziczące.
Walidator niezależy jest klasą rozszerzającą [[yii\validators\Validator|Validator]] lub klasy po nim dziedziczące.
Możesz zaimplementować jego logikę walidacji poprzez nadpisanie metody [[yii\validators\Validator::validateAttribute()|validateAttribute()]].
Jeśli atrybut nie przejdzie walidacji, wywołaj metodę [[yii\base\Model::addError()|addError()]] do zapisania wiadomości błędu w modelu, tak jak w
Jeśli atrybut nie przejdzie walidacji, wywołaj metodę [[yii\base\Model::addError()|addError()]] do zapisania wiadomości błędu w modelu, tak jak w
[walidatorach wbudowanych](#inline-validators).
@ -396,7 +396,7 @@ class CountryValidator extends Validator
```
Jeśli chcesz, aby walidator wspierał walidację wartości bez modelu, powinieneś nadpisać metodę [[yii\validators\Validator::validate()|validate()]].
Możesz nadpisać także [[yii\validators\Validator::validateValue()|validateValue()]] zamiast `validateAttribute()` oraz `validate()`,
Możesz nadpisać także [[yii\validators\Validator::validateValue()|validateValue()]] zamiast `validateAttribute()` oraz `validate()`,
ponieważ domyślnie te dwie metody są implementowane użyciem metody `validateValue()`.
Poniżej znajduje się przykład użycia powyższej klasy walidatora w modelu.
@ -428,20 +428,20 @@ class EntryForm extends Model
## Walidacja po stronie klienta <spanid="client-side-validation"></span>
Walidacja po stronie klienta, bazująca na kodzie JavaScript jest wskazana, kiedy użytkownicy dostarczają dane przez formularz HTML,
ponieważ pozwala na szybszą walidację błędów, a tym samym zapewnia lepszą ich obsługę dla użytkownika. Możesz użyć lub zaimplementować walidator,
Walidacja po stronie klienta, bazująca na kodzie JavaScript jest wskazana, kiedy użytkownicy dostarczają dane przez formularz HTML,
ponieważ pozwala na szybszą walidację błędów, a tym samym zapewnia lepszą ich obsługę dla użytkownika. Możesz użyć lub zaimplementować walidator,
który wspiera walidację po stronie klienta jako *dodatek* do walidacji po stronie serwera.
> Info: Walidacja po stronie klienta nie jest wymagana. Głównym jej celem jest poprawa jakości korzystania z formularzy dla użytkowników.
> Podobnie jak w przypadku danych wejściowych pochodzących od użytkowników, nigdy nie powinieneś ufać walidacji przeprowadanej po stronie klienta.
> Z tego powodu należy zawsze przeprowadzać główną walidację po stronie serwera wywołując metodę [[yii\base\Model::validate()|validate()]],
> Podobnie jak w przypadku danych wejściowych pochodzących od użytkowników, nigdy nie powinieneś ufać walidacji przeprowadanej po stronie klienta.
> Z tego powodu należy zawsze przeprowadzać główną walidację po stronie serwera wywołując metodę [[yii\base\Model::validate()|validate()]],
> tak jak zostało to opisane w poprzednich sekcjach.
### Używanie walidacji po stronie klienta <spanid="using-client-side-validation"></span>
Wiele [podstawowych walidatorów](tutorial-core-validators.md) domyślnie wspiera walidację po stronie klienta. Wszystko, co musisz zrobić, to użyć widżetu
[[yii\widgets\ActiveForm|ActiveForm]] do zbudowania formularza HTML. Dla przykładu, model `LoginForm` poniżej deklaruje dwie zasady: jedną, używającą podstawowego walidatora
[required](tutorial-core-validators.md#required), który wspiera walidację po stronie klienta i serwera, oraz drugą, w której użyto walidatora wbudowanego `validatePassword`,
Wiele [podstawowych walidatorów](tutorial-core-validators.md) domyślnie wspiera walidację po stronie klienta. Wszystko, co musisz zrobić, to użyć widżetu
[[yii\widgets\ActiveForm|ActiveForm]] do zbudowania formularza HTML. Dla przykładu, model `LoginForm` poniżej deklaruje dwie zasady: jedną, używającą podstawowego walidatora
[required](tutorial-core-validators.md#required), który wspiera walidację po stronie klienta i serwera, oraz drugą, w której użyto walidatora wbudowanego `validatePassword`,
który wspiera tylko walidację po stronie serwera.
```php
@ -488,24 +488,24 @@ Jeśli wyślesz formularz bez wpisywania jakichkolwiek danych, otrzymasz komunik
<?php yii\widgets\ActiveForm::end(); ?>
```
"Za kulisami", widżet [[yii\widgets\ActiveForm|ActiveForm]] odczyta wszystkie zasady walidacji zadeklarowane w modelu i wygeneruje odpowiedni kod JavaScript
"Za kulisami", widżet [[yii\widgets\ActiveForm|ActiveForm]] odczyta wszystkie zasady walidacji zadeklarowane w modelu i wygeneruje odpowiedni kod JavaScript
dla walidatorów wspierających walidację po stronie klienta. Kiedy użytkownik zmieni wartość w polu lub spróbuje wysłać formularz, zostanie wywołana walidacja po stronie klienta.
Jeśli chcesz wyłączyć całkowicie walidację po stronie klienta, możesz ustawić właściwość [[yii\widgets\ActiveForm::enableClientValidation|enableClientValidation]] na `false`.
Możesz również wyłączyć ten rodzaj walidacji dla konkretnego pola, przez ustawienie jego właściwości
[[yii\widgets\ActiveField::enableClientValidation|enableClientValidation]] na `false`. Jeśli właściwość `enableClientValidation` zostanie skonfigurowana na poziomie pola
Możesz również wyłączyć ten rodzaj walidacji dla konkretnego pola, przez ustawienie jego właściwości
[[yii\widgets\ActiveField::enableClientValidation|enableClientValidation]] na `false`. Jeśli właściwość `enableClientValidation` zostanie skonfigurowana na poziomie pola
formularza i w samym formularzu jednocześnie, pierwszeństwo będzie miała opcja określona w formularzu.
### Implementacja walidacji po stronie klienta <spanid="implementing-client-side-validation"></span>
Aby utworzyć walidator wspierający walidację po stronie klienta, powinieneś zaimplementować metodę
[[yii\validators\Validator::clientValidateAttribute()|clientValidateAttribute()]], która zwraca kod JavaScript, odpowiedzialny za przeprowadzenie walidacji.
Aby utworzyć walidator wspierający walidację po stronie klienta, powinieneś zaimplementować metodę
[[yii\validators\Validator::clientValidateAttribute()|clientValidateAttribute()]], która zwraca kod JavaScript, odpowiedzialny za przeprowadzenie walidacji.
W kodzie JavaScript możesz użyć następujących predefiniowanych zmiennych:
- `attribute`: nazwa atrybutu podlegającego walidacji.
- `value`: wartość atrybutu podlegająca walidacji.
- `messages`: tablica używana do przechowywania wiadomości błędów dla danego atrybutu.
- `messages`: tablica używana do przechowywania wiadomości błędów dla danego atrybutu.
- `deferred`: tablica, do której można dodać zakolejkowane obiekty (wyjaśnione w późniejszej podsekcji).
W poniższym przykładzie, tworzymy walidator `StatusValidator`, który sprawdza, czy wartość danego atrybutu jest wartością znajdującą się na liście statusów w bazie danych.
@ -556,7 +556,7 @@ JS;
> ]
> ```
> Tip: Jeśli musisz dodać ręcznie walidację po stronie klienta np. podczas dynamicznego dodawania pól formularza lub przeprowadzania specjalnej logiki w obrębie interfejsu
> Tip: Jeśli musisz dodać ręcznie walidację po stronie klienta np. podczas dynamicznego dodawania pól formularza lub przeprowadzania specjalnej logiki w obrębie interfejsu
> użytkownika, zapoznaj się z rozdziałem [Praca z ActiveForm za pomocą JavaScript](https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md)
> w Yii 2.0 Cookbook.
@ -639,10 +639,10 @@ JS;
Niektóre walidacje mogą zostać wykonane tylko po stronie serwera, ponieważ tylko serwer posiada niezbędne informacje do ich przeprowadzenia.
Dla przykładu, aby sprawdzić, czy login został już zajęty, musimy sprawdzić tabelę użytkowników w bazie danych.
W tym właśnie przypadku możesz użyć walidacji AJAX. Wywoła ona żądanie AJAX w tle, aby spradzić to pole.
W tym właśnie przypadku możesz użyć walidacji AJAX. Wywoła ona żądanie AJAX w tle, aby spradzić to pole.
Aby uaktywnić walidację AJAX dla pojedyńczego pola formularza, ustaw właściwość [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] na `true`
oraz zdefiniuj unikalne `id` formularza:
Aby uaktywnić walidację AJAX dla pojedyńczego pola formularza, ustaw właściwość [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] na `true`
oraz zdefiniuj unikalne `id` formularza:
```php
use yii\widgets\ActiveForm;
@ -682,8 +682,8 @@ if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Powyższy kod sprawdzi, czy zapytanie zostało wysłane przy użyciu AJAXa. Jeśli tak, w odpowiedzi zwróci wynik walidacji w formacie JSON.
> Info: Możesz również użyć [walidacji kolejkowej](#deferred-validation) do wykonania walidacji AJAX,
> Info: Możesz również użyć [walidacji kolejkowej](#deferred-validation) do wykonania walidacji AJAX,
> jednakże walidacja AJAXowa opisana w tej sekcji jest bardziej systematyczna i wymaga mniej wysiłku przy kodowaniu.
Kiedy zarówno `enableClientValidation`, jak i `enableAjaxValidation` ustawione są na `true`, walidacja za pomocą AJAX zostanie uruchomiona dopiero po udanej
Kiedy zarówno `enableClientValidation`, jak i `enableAjaxValidation` ustawione są na `true`, walidacja za pomocą AJAX zostanie uruchomiona dopiero po udanej
@ -21,7 +21,7 @@ Você pode configurar a propriedade [[yii\filters\HttpCache::lastModified]] para
/**
* @param Action $action O Objeto da ação que está sendo manipulada no momento
* @param array $params o valor da propriedade "params"
* @return integer uma data(timestamp) UNIX timestamp representando o tempo da
* @return int uma data(timestamp) UNIX timestamp representando o tempo da
* última modificação na página
*/
function ($action, $params)
@ -47,7 +47,7 @@ public function behaviors()
O código acima afirma que o cache HTTP deve ser habilitado apenas para a ação `index`. Este deve
gerar um cabeçalho HTTP `last-modified` baseado na última data de alteração dos*posts*. Quando um
navegador visitar a página `index` pela primeira vez, a página será gerada no servidor e enviada para
navegador visitar a página `index` pela primeira vez, a página será gerada no servidor e enviada para
o navegador; Se o navegador visitar a mesma página novamente e não houver modificação dos *posts* durante este
período, o servidor não irá remontará a página e o navegador usará a versão em cache no cliente.
Como resultado, a renderização do conteúdo na página não será executada no servidor.
@ -91,20 +91,20 @@ public function behaviors()
O código acima afirma que o cache de HTTP deve ser habilitado apenas para a ação `view`. Este deve
gerar um cabeçalho HTTP `ETag` baseado no título e no conteúdo do *post* requisitado. Quando um navegador visitar
a página `view` pela primeira vez, a página será gerada no servidor e enviada para ele; Se o navegador visitar
a página `view` pela primeira vez, a página será gerada no servidor e enviada para ele; Se o navegador visitar
a mesma página novamente e não houver alteração para o título e o conteúdo do *post*, o servidor não remontará
a página e o navegador usará a versão que estiver no cache do cliente. Como resultado, a renderização do
a página e o navegador usará a versão que estiver no cache do cliente. Como resultado, a renderização do
conteúdo na página não será executada no servidor.
ETags permite estratégias mais complexas e/ou mais precisas do que o uso do cabeçalho de `Last-modified`.
Por exemplo, um ETag pode ser invalidado se o site tiver sido alterado para um novo tema.
Gerações muito complexas de ETags podem contrariar o propósito de se usar `HttpCache` e introduzir despesas desnecessárias ao processamento, já que eles precisam ser reavaliados a cada requisição.
Gerações muito complexas de ETags podem contrariar o propósito de se usar `HttpCache` e introduzir despesas desnecessárias ao processamento, já que eles precisam ser reavaliados a cada requisição.
Tente encontrar uma expressão simples que invalida o cache se o conteúdo da página for modificado.
> Observação: Em concordância com a [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4), o
`HttpCache` enviará os cabeçalhos `ETag` e `Last-Modified` se ambos forem assim configurados.
E se o cliente enviar ambos o cabeçalhos `If-None-Match` e `If-Modified-Since`, apenas o primeiro será
E se o cliente enviar ambos o cabeçalhos `If-None-Match` e `If-Modified-Since`, apenas o primeiro será
## Limitador de Cache na Sessão <spanid="session-cache-limiter"></span>
Quando uma página usa sessão, o PHP automaticamente enviará alguns cabeçalhos HTTP relacionados ao cache
como especificado na configuração `session.cache_limiter` do PHP.INI. Estes cabeçalhos podem interferir ou
como especificado na configuração `session.cache_limiter` do PHP.INI. Estes cabeçalhos podem interferir ou
desabilitar o cache que você deseja do `HttpCache`. Para prevenir-se deste problema, por padrão, o `HttpCache`
desabilitará o envio destes cabeçalhos automaticamente. Se você quiser modificar estes comportamentos, deve
configurar a propriedade [[yii\filters\HttpCache::sessionCacheLimiter]]. A propriedade pode receber um valor string, como: `public`, `private`, `private_no_expire` e `nocache`. Por favor, consulte o manual do
configurar a propriedade [[yii\filters\HttpCache::sessionCacheLimiter]]. A propriedade pode receber um valor string, como: `public`, `private`, `private_no_expire` e `nocache`. Por favor, consulte o manual do
PHP sobre [session_cache_limiter()](http://www.php.net/manual/en/function.session-cache-limiter.php)
para mais explicações sobre estes valores.
## Implicações para SEO <spanid="seo-implications"></span>
Os bots do motor de buscas tendem a respeitar cabeçalhos de cache. Já que alguns rastreadores têm um limite sobre a quantidade de páginas por domínio que eles processam em um certo espaço de tempo, introduzir cabeçalhos de cache podem
Os bots do motor de buscas tendem a respeitar cabeçalhos de cache. Já que alguns rastreadores têm um limite sobre a quantidade de páginas por domínio que eles processam em um certo espaço de tempo, introduzir cabeçalhos de cache podem
ajudar na indexação do seu site já que eles reduzem o número de páginas que precisam ser processadas.
Autenticação é o processo de verificação da identidade do usuário. Geralmente é usado um identificador (ex. um nome de usuário ou endereço de e-mail) e um token secreto (ex. uma senha ou um token de acesso) para determinar se o usuário é quem ele diz ser. Autenticação é a base do recurso de login.
O Yii fornece um framework de autenticação com vários componentes que dão suporte ao login. Para usar este framework, você precisará primeiramente fazer o seguinte:
* Configurar o componente [[yii\web\User|user]] da aplicação;
* Criar uma classe que implementa a interface [[yii\web\IdentityInterface]].
@ -14,7 +14,7 @@ O Yii fornece um framework de autenticação com vários componentes que dão su
O componente [[yii\web\User|user]] da aplicação gerencia o status de autenticação dos usuários. Ele requer que você especifique uma [[yii\web\User::identityClass|classe de identidade]] que contém a atual lógia de autenticação.
Na cofiguração abaixo, a [[yii\web\User::identityClass|classe de identidade]] do
[[yii\web\User|user]] é configurada para ser `app\models\User` cuja implementação é explicada na próxima subseção:
```php
return [
'components' => [
@ -57,7 +57,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Localiza uma identidade pelo ID informado
*
* @param string|integer $id o ID a ser localizado
* @param string|int $id o ID a ser localizado
* @return IdentityInterface|null o objeto da identidade que corresponde ao ID informado
*/
public static function findIdentity($id)
@ -94,7 +94,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean se a chave de autenticação do usuário atual for válida
* @return bool se a chave de autenticação do usuário atual for válida
*/
public function validateAuthKey($authKey)
{
@ -110,7 +110,7 @@ e gravá-la na tabela `user`:
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -129,7 +129,7 @@ class User extends ActiveRecord implements IdentityInterface
## Usando o [[yii\web\User]] <spanid="using-user"></span>
Você usa o [[yii\web\User]] principalmente como um componente `user` da aplicação.
Você usa o [[yii\web\User]] principalmente como um componente `user` da aplicação.
É possível detectar a identidade do usuário atual utilizando a expressão `Yii::$app->user->identity`. Ele retorna uma instância da [[yii\web\User::identityClass|classe de identidade]] representando o atual usuário logado, ou `null` se o usuário corrente não estiver autenticado (acessando como convidado). O código a seguir mostra como recuperar outras informações relacionadas à autenticação de [[yii\web\User]]:
@ -151,13 +151,13 @@ Para logar um usuário, você pode usar o seguinte código:
// observe que você pode querer checar a senha se necessário
O método [[yii\web\User::login()]] define a identidade do usuário atual para o [[yii\web\User]]. Se a sessão estiver [[yii\web\User::enableSession|habilitada]], ele vai manter a identidade na sessão para que o status de autenticação do usuário seja mantido durante toda a sessão. Se o login via cookie (ex. login "remember me") estiver [[yii\web\User::enableAutoLogin|habilitada]], ele também guardará a identidade em um cookie para que o estado de autenticação do usuário possa ser recuperado a partir do cookie enquanto o cookie permanece válido.
A fim de permitir login via cookie, você pode configurar [[yii\web\User::enableAutoLogin]] como `true` na configuração da aplicação. Você também precisará fornecer um parâmetro de tempo de duração quando chamar o método [[yii\web\User::login()]].
A fim de permitir login via cookie, você pode configurar [[yii\web\User::enableAutoLogin]] como `true` na configuração da aplicação. Você também precisará fornecer um parâmetro de tempo de duração quando chamar o método [[yii\web\User::login()]].
Para realizar o logout de um usuário, simplesmente chame:
@ -173,12 +173,12 @@ Observe que o logout de um usuário só tem sentido quando a sessão está habil
A classe [[yii\web\User]] dispara alguns eventos durante os processos de login e logout:
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: disparado no início de [[yii\web\User::login()]].
Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de login será cancelado.
Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de login será cancelado.
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: dispara após de um login com sucesso.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: dispara no início de [[yii\web\User::logout()]]. Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de logout será cancelado.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: dispara no início de [[yii\web\User::logout()]]. Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de logout será cancelado.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: dispara após um logout com sucesso.
Você pode responder a estes eventos implementando funcionalidades, tais como auditoria de login, estatísticas de usuários on-line. Por exemplo, no manipulador
Você pode responder a estes eventos implementando funcionalidades, tais como auditoria de login, estatísticas de usuários on-line. Por exemplo, no manipulador
[[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]], você pode registrar o tempo de login e endereço IP na tabela `user`.
* @param Action $action объект действия, которое в настоящее время обрабатывается
* @param array $params значение свойства "params"
* @return integer временная метка UNIX timestamp, возвращающая время последнего изменения страницы
* @return int временная метка UNIX timestamp, возвращающая время последнего изменения страницы
*/
function ($action, $params)
```
@ -43,7 +43,7 @@ public function behaviors()
}
```
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `index`. Он
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `index`. Он
генерирует `Last-Modified` HTTP заголовок на основе времени последнего сообщения. Когда браузер в первый раз посещает страницу `index`, то страница будет сгенерирована на сервере и отправлена в браузер; если браузер снова зайдёт на эту страницу и с тех пор ни один пост не обновится, то сервер не будет пересоздавать страницу и браузер будет использовать закэшированную на стороне клиента версию. В результате, будет пропущено как создание страницы на стороне сервера, так и передача содержания страницы клиенту.
@ -80,13 +80,13 @@ public function behaviors()
}
```
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `view`. Он
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `view`. Он
генерирует `ETag` HTTP заголовок на основе заголовка и содержания последнего сообщения. Когда браузер в первый раз посещает страницу `view`, то страница будет сгенерирована на сервере и отправлена в браузер; если браузер снова зайдёт на эту страницу и с тех пор ни один пост не обновится, то сервер не будет пересоздавать страницу и браузер будет использовать закэшированную на стороне клиента версию. В результате, будет пропущено как создание страницы на стороне сервера, так и передача содержание страницы клиенту.
ETags позволяет применять более сложные и/или более точные стратегии кэширования, чем заголовок `Last-Modified`.
ETags позволяет применять более сложные и/или более точные стратегии кэширования, чем заголовок `Last-Modified`.
Например, ETag станет невалидным (некорректным), если на сайте была включена другая тема
Ресурсоёмкая генерация ETag может противоречить цели использования `HttpCache` и внести излишнюю нагрузку,
Ресурсоёмкая генерация ETag может противоречить цели использования `HttpCache` и внести излишнюю нагрузку,
т.к. он должен пересоздаваться при каждом запросе. Попробуйте найти простое выражение, которое инвалидирует кэш, если содержание страницы было изменено.
> Note: В соответствии с [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4),
Метод [[yii\web\User::login()]] устанавливает `identity` текущего пользователя в [[yii\web\User]]. Если сессии
Метод [[yii\web\User::login()]] устанавливает `identity` текущего пользователя в [[yii\web\User]]. Если сессии
[[yii\web\User::enableSession|включены]], то `identity` будет сохраняться в сессии, так что состояние
статуса аутентификации будет поддерживаться на всём протяжении сессии. Если [[yii\web\User::enableAutoLogin|включен]] вход, основанный на cookie (так называемый "запомни меня" вход), то `identity` также будет сохранена
в `cookie` так, чтобы статус аутентификации пользователя мог быть восстановлен на протяжении всего времени жизни `cookie`.
@ -205,7 +205,7 @@ Yii::$app->user->logout();
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: вызывается после успешного входа.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: вызывается перед вызовом [[yii\web\User::logout()]].
Если обработчик устанавливает свойство [[yii\web\UserEvent::isValid|isValid]] объекта в `false`,
процесс выхода будет прерван.
процесс выхода будет прерван.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: вызывается после успешного выхода.
Вы можете использовать эти события для реализации функции аудита входа, сбора статистики онлайн пользователей. Например,
The [[yii\web\User|user]] application component manages the user authentication status. It requires you to
The [[yii\web\User|user]] application component manages the user authentication status. It requires you to
specify an [[yii\web\User::identityClass|identity class]] which contains the actual authentication logic.
In the following application configuration, the [[yii\web\User::identityClass|identity class]] for
[[yii\web\User|user]] is configured to be `app\models\User` whose implementation is explained in
[[yii\web\User|user]] is configured to be `app\models\User` whose implementation is explained in
the next subsection:
```php
return [
'components' => [
@ -48,11 +48,11 @@ the following methods:
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: it implements the logic for verifying
the cookie-based login key.
If a particular method is not needed, you may implement it with an empty body. For example, if your application
If a particular method is not needed, you may implement it with an empty body. For example, if your application
is a pure stateless RESTful application, you would only need to implement [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]
and [[yii\web\IdentityInterface::getId()|getId()]] while leaving all other methods with an empty body.
In the following example, an [[yii\web\User::identityClass|identity class]] is implemented as
In the following example, an [[yii\web\User::identityClass|identity class]] is implemented as
an [Active Record](db-active-record.md) class associated with the `user` database table.
```php
@ -71,7 +71,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Finds an identity by the given ID.
*
* @param string|integer $id the ID to be looked for
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
@ -108,7 +108,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean if auth key is valid for current user
* @return bool if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{
@ -125,7 +125,7 @@ user and store it in the `user` table:
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -147,7 +147,7 @@ class User extends ActiveRecord implements IdentityInterface
## Using [[yii\web\User]] <spanid="using-user"></span>
You mainly use [[yii\web\User]] in terms of the `user` application component.
You mainly use [[yii\web\User]] in terms of the `user` application component.
You can detect the identity of the current user using the expression `Yii::$app->user->identity`. It returns
an instance of the [[yii\web\User::identityClass|identity class]] representing the currently logged-in user,
@ -172,19 +172,19 @@ To login a user, you may use the following code:
// note that you may want to check the password if needed
`@param`, `@var`, `@property` и `@return` должны описывать типы `boolean`, `integer`, `string`, `array` или `null`. Вы можете использовать и имена классов, например `Model` или `ActiveRecord`. Для типизированных массивов используйте `ClassName[]`.
`@param`, `@var`, `@property` и `@return` должны описывать типы `bool`, `int`, `string`, `array` или `null`. Вы можете использовать и имена классов, например `Model` или `ActiveRecord`. Для типизированных массивов используйте `ClassName[]`.
### 4.5 Конструкторы
@ -199,7 +199,7 @@ $sql = "SELECT *"
. "WHERE `id` = 121 ";
```
### 5.3 Массивы
### 5.3 Массивы
Для массивов мы используем краткий синтаксис, появившийся в PHP 5.4.
`@param`, `@var`, `@property` та `@return` повинні оголошувати типи як `boolean`, `integer`, `string`, `array` чи `null`. Також можна використовувати імена класів, як наприклад: `Model` або `ActiveRecord`. Для типізованих масивів використовуйте `ClassName[]`.
`@param`, `@var`, `@property` та `@return` повинні оголошувати типи як `bool`, `int`, `string`, `array` чи `null`. Також можна використовувати імена класів, як наприклад: `Model` або `ActiveRecord`. Для типізованих масивів використовуйте `ClassName[]`.