Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 34 additions & 17 deletions en/extending-modx/plugins/system-events/onweblogin.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,61 @@ _old_uri: "2.x/developing-in-modx/basic-development/plugins/system-events/onwebl

## Event: OnWebLogin

Fired anytime a user logs into a non-mgr context after performing any autentification checks successfully. Doesn't affect the autentification process.
Fires after a user passes authentication for a non-`mgr` context and session contexts are added. Plugins cannot change whether the login succeeds.

- Service: 3 - Web Access Events
- Group: None

## Event Parameters

| Name | Description |
| ------------ | -------------------------------------------------------------------------------- |
| user | A reference to the modUser object. |
| attributes | An array of: - rememberme - Boolean set if user wants password to be remembered. |
| lifetime | The session cookie lifetime for this login. |
| loginContext | The context key this login is occurring in. |
| addContexts | Additional contexts in which the login is also occuring in. |
| Name | Description |
| ---------- | --------------------------------------------------------------------------- |
| user | The `modUser` that just logged in. |
| attributes | An array with: |
| | - rememberme — whether the user asked to remember the login |
| | - lifetime — session cookie lifetime for this login |
| | - loginContext — context key for this login |
| | - addContexts — extra contexts that also received a session |

## `$modx->getUser()` during OnWebLogin

The login processor adds session contexts **before** it invokes `OnWebLogin`. The user is logged in at the session level.

For web contexts it does **not** refresh `$modx->user` before the event. `$modx->getUser()` often still returns the previous user object from the request (anonymous / id `0`, or whatever was already cached). That is why `$modx->getUser()` looks “wrong” here even though login succeeded.

Use the event `$user` parameter (or `$scriptProperties['user']`) for the authenticated user. If you need `$modx->getUser()` to match, clear and reload after the session exists:

```php
$modx->user = null;
$modx->getUser($attributes['loginContext'], true);
```

On manager login the processor does refresh `$modx->user` before [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin). That refresh does not run for web/`OnWebLogin`.

## Event Login Workflow

1. _[_OnBeforeWebLogin_](extending-modx/plugins/system-events/onbeforeweblogin)_ || _[OnBeforeManagerLogin](extending-modx/plugins/system-events/onbeforemanagerlogin)_ - Inside this event the developer can check for erroneous parameters which will **disallow** further logging in process. If plugins executed by this event return something except true, the logging in will be aborted with the specified error.
2. _[OnUserNotFound](extending-modx/plugins/system-events/onusernotfound)_ - This event is executed only if the provided username is not found inside MODX database. The developer can provide it's own modUser object in the event output to continue the login process.
3. _[OnWebAuthentication](extending-modx/plugins/system-events/onwebauthentication)_ || _[OnManagerAuthentication](extending-modx/plugins/system-events/onmanagerauthentication)_ - Inside this event the developer can check for parameters which will **override the default checking by password** and **allow** further logging in process. If one of the plugins executed from this event return true, the user is considered verified and logged in.
4. **_OnWebLogin_** || _[OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin)_ - This event is fired after the logging in process has finished and the user is considered logged in. It **doesn't change** the logging in process **behaviour**.
1. [OnBeforeWebLogin](extending-modx/plugins/system-events/onbeforeweblogin) || [OnBeforeManagerLogin](extending-modx/plugins/system-events/onbeforemanagerlogin) — plugins can abort login by returning a value other than `true`.
2. [OnUserNotFound](extending-modx/plugins/system-events/onusernotfound) — runs only when the username is missing from the MODX database. A plugin may supply its own `modUser` to continue.
3. [OnWebAuthentication](extending-modx/plugins/system-events/onwebauthentication) || [OnManagerAuthentication](extending-modx/plugins/system-events/onmanagerauthentication) — plugins can override the default password check. Returning `true` marks the user as authenticated.
4. **OnWebLogin** || [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin) — runs after session contexts are added. Does not change login success or failure. On web, prefer the `$user` event parameter over `$modx->getUser()` (see above).

## Example

Such a plugin will display in the Error Log "who logged in and where:
Log who logged in and with which attributes:

```php
<?php
$eventName = $modx->event->name;
switch($eventName) {
switch ($eventName) {
case 'OnWebLogin':
$name = $user->get('username');
$modx->log(modX::LOG_LEVEL_ERROR, 'User logged in '.$name.print_r($attributes));
$modx->log(modX::LOG_LEVEL_ERROR, 'User logged in: ' . $name . ' ' . print_r($attributes, true));
break;
}
```

## See Also

- [System Events](extending-modx/plugins/system-events "System Events")
- [Plugins](extending-modx/plugins "Plugins")
- [System Events](extending-modx/plugins/system-events)
- [Plugins](extending-modx/plugins)
- [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin)
59 changes: 38 additions & 21 deletions ru/extending-modx/plugins/system-events/onweblogin.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,44 +5,61 @@ translation: "extending-modx/plugins/system-events/onweblogin"

## Событие: OnWebLogin

Запускается каждый раз, когда пользователь успешно входит в не в mgr после успешного выполнения любой операции проверки. Событие не влияет на процесс авторизации.
Вызывается после успешной аутентификации пользователя во фронтенд-контексте (не `mgr`) и после добавления session contexts. Плагины не меняют результат входа.

Служба: 3 - Web Access Service Events
Группа: Нет
- Служба: 3 - Web Access Events
- Группа: Нет

## Параметры события

| Имя | Описание |
| ------------ | -------------------------------------------------------------------------------------------- |
| user | Ссылка на объект modUser. |
| attributes | Массив: - rememberme - Булево множество, если пользователь хочет, чтобы пароль был запомнен. |
| lifetime | The session cookie lifetime for this login. |
| loginContext | Ключ контекста, в котором происходит вход в систему. |
| addContexts | Дополнительные контексты, в которых вход в систему также происходит. |
| Имя | Описание |
| ---------- | --------------------------------------------------------------------------- |
| user | Объект `modUser`, который только что вошёл. |
| attributes | Массив: |
| | - rememberme — запоминать ли вход |
| | - lifetime — время жизни session cookie для этого входа |
| | - loginContext — ключ контекста входа |
| | - addContexts — дополнительные контексты, куда тоже записали сессию |

## Рабочий процесс входа в систему
## `$modx->getUser()` во время OnWebLogin

1. _[_OnBeforeWebLogin_](extending-modx/plugins/system-events/onbeforeweblogin)_ || _[OnBeforeManagerLogin](extending-modx/plugins/system-events/onbeforemanagerlogin)_ - Внутри этого события разработчик может проверить наличие ошибочных параметров, которые **будут запрещать** дальнейшую регистрацию в процессе. Если плагины, выполненные этим событием, возвращают что-то, кроме true, вход в систему будет прерван с указанной ошибкой.
2. _[OnUserNotFound](extending-modx/plugins/system-events/onusernotfound)_ - Это событие выполняется, только если указанное имя пользователя не найдено в базе данных MODX. Разработчик может предоставить свой собственный объект modUser в выходных данных события, чтобы продолжить процесс входа в систему.
3. _[OnWebAuthentication](extending-modx/plugins/system-events/onwebauthentication)_ || _[OnManagerAuthentication](hextending-modx/plugins/system-events/onmanagerauthentication)_ - Внутри этого события разработчик может проверить параметры, которые **отменят проверку по умолчанию паролем** и **позволят** продолжить вход в систему. Если один из плагинов, выполненных из этого события, возвращает true, пользователь считается проверенным и вошел в систему.
4. **_OnWebLogin_** || _[OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin)_ - Это событие вызывается после завершения процесса входа в систему и считается, что пользователь вошел в систему. Оно **не меняет **процесс входа в систему **поведение**.
Процессор входа добавляет session contexts **до** вызова `OnWebLogin`. На уровне сессии пользователь уже вошёл.

Для web-контекстов процессор **не** обновляет `$modx->user` перед событием. `$modx->getUser()` часто возвращает прежний объект из запроса (аноним / id `0` или другой уже закэшированный пользователь). Поэтому `$modx->getUser()` «врёт», хотя вход уже прошёл.

Берите пользователя из параметра события `$user` (или `$scriptProperties['user']`). Если нужен именно `$modx->getUser()`, сбросьте и перезагрузите после появления сессии:

```php
$modx->user = null;
$modx->getUser($attributes['loginContext'], true);
```

При входе в manager процессор обновляет `$modx->user` до [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin). Для web / `OnWebLogin` этого шага нет.

## Рабочий процесс входа

1. [OnBeforeWebLogin](extending-modx/plugins/system-events/onbeforeweblogin) || [OnBeforeManagerLogin](extending-modx/plugins/system-events/onbeforemanagerlogin) — плагин может прервать вход, вернув значение, отличное от `true`.
2. [OnUserNotFound](extending-modx/plugins/system-events/onusernotfound) — только если имени пользователя нет в БД MODX. Плагин может отдать свой `modUser` и продолжить вход.
3. [OnWebAuthentication](extending-modx/plugins/system-events/onwebauthentication) || [OnManagerAuthentication](extending-modx/plugins/system-events/onmanagerauthentication) — плагин может обойти проверку пароля по умолчанию. Возврат `true` считает пользователя аутентифицированным.
4. **OnWebLogin** || [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin) — после добавления session contexts. Не меняет успех или отказ входа. На web берите `$user` из события, а не `$modx->getUser()` (см. выше).

## Пример

Такой плагин выведет в Журнал ошибок" кто и где авторизовался:
Записать в журнал ошибок, кто вошёл и с какими атрибутами:

```php
<?php
$eventName = $modx->event->name;
switch($eventName) {
switch ($eventName) {
case 'OnWebLogin':
$name = $user->get('username');
$modx->log(modX::LOG_LEVEL_ERROR, 'Авторизовался пользователь '.$name.print_r($attributes));
$modx->log(modX::LOG_LEVEL_ERROR, 'Авторизовался пользователь ' . $name . ' ' . print_r($attributes, true));
break;
}
```

## Смотри также
## Смотрите также

- [Системные события](extending-modx/plugins/system-events "Системные события")
- [Плагины](extending-modx/plugins "Плагины")
- [Системные события](extending-modx/plugins/system-events)
- [Плагины](extending-modx/plugins)
- [OnManagerLogin](extending-modx/plugins/system-events/onmanagerlogin)
Loading