# Events

Source: https://keyringauth.com/docs/0.x/rust/events

## Introduction

Every event is in `laravel_keyring::events`, dispatched through laravel-rust's event system where the PHP package dispatches them, so you listen for them as for any event. Those about a user are generic over your user type, so a listener names it:

```rust
use laravel::event::Event;
use laravel_keyring::events::Authenticated;

async fn note_sign_in(event: Event<Authenticated<User>>) -> laravel::Result<()> {
    // event.user, event.attempt, event.device
    Ok(())
}

laravel::Application::configure().with_events(|events, _| {
    events.listen(note_sign_in);
});
```

The provider registers its own listeners, for the security log and the security emails, ahead of yours, so you don't need your own copies. Keyring fires events whether or not a feature that uses them is on.

A listener of yours that fails fails the request with its error, once the change behind the event is done, as in the PHP package. A listener for `RegisteredSessionEnded` that fails is reported and stops nothing, as the announcement is retried (see [Hearing About Ended Sessions](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#hearing-about-ended-sessions)).

Events carry plain values where the PHP package's carry models, and never the request: what Keyring read from the request is on the event instead.

## Queued Listeners

laravel-rust has no queued listeners: a listener runs in the request, after the transaction it was dispatched in commits, unless you register it with `listen_at_dispatch`, which runs it at once. To do slow work, dispatch a job of your own from the listener.

No event carries a password, code or token, but for the registry ID in the `session` of `SessionResumed`, `RememberMeReused` and `SessionContested`, and the state, nonce and code verifier in `ProviderIdentityAccepted`'s `identity.request`. Don't log or keep those: `Identity::without_secrets()` gives the identity without them.

## Signing In and Confirming

| Event | When | Fields |
|---|---|---|
| `Attempting` | A factor is about to be checked. | `factor`, `purpose` |
| `FactorChallenged<U>` | The challenge page showed a factor. | `user`, `attempt`, `authenticator` |
| `FactorVerified<U>` | A factor's proof was right. | `user`, `attempt`, `authenticator`, `verification` |
| `ProviderIdentityAccepted<U>` | An [identity provider](https://keyringauth.com/docs/0.x/rust/sso#hearing-about-accepted-identities) account was accepted as the user's link. | `user`, `authenticator`, `identity`, `purpose` |
| `FactorFailed<U>` | A factor's proof was wrong, or the user wasn't found. | `user` (when found), `attempt`, `authenticator`, `factor`, and `username`, what was typed |
| `Lockout` | A rate limit refused a request. It fires for every refused request. | `factor`, `retry_after` |
| `AccountLocked<U>` | Failed attempts got a sign-in factor refused until a reset or `unlock()`. | `user`, `factor` |
| `Authenticated<U>` | A sign in completed. | `user`, `attempt`, `device` |
| `Confirmed<U>` | A [step-up](https://keyringauth.com/docs/0.x/rust/step-up) completed. | `user`, `attempt` |
| `LoggedOut<U>` | The user signed out. | `user` |

`purpose` is `events::Purpose`: `Login` or `Confirm`. An `attempt` is an `events::Attempt`, with its purpose and verifications, and an `authenticator` an `events::Authenticator`, with its ID, factor and name. `FactorFailed`, `RecoveryCodeUsed` and `CloneSuspected` carry the `user` the PHP package gets with `authenticator->user()`.

When each fires is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/events#signing-in-and-confirming) describes, with one difference: `FactorFailed` fires after the failure is counted, so a listener that fails can't keep it from counting, where the PHP package dispatches it before. `CloneSuspected` and the quiet refusal's `Lockout` likewise. The password checked for adding or removing a factor, and a proof for a frozen account, also dispatch `Attempting` and `FactorVerified`.

## Sessions and Devices

| Event | Fields |
|---|---|
| `NewDeviceSignedIn<U>` | `user`, `device`, and `revoke_url(days)`, the ["this wasn't me" link](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#the-this-wasnt-me-link), which takes an `Option<u32>` and returns a `Result` |
| `UnrecordedDeviceSignedIn<U>` | `user`, `handle`, `device` |
| `DeviceRevoked<U>` | `user`, `device` (its ID and name), `reported` |
| `SessionsRevoked<U>` | `user`, `count` |
| `SessionEnded<U>` | `user`, `reason` |
| `RegisteredSessionEnded` | `handle`, `handles`, `user_id`, `user_type`, `guard`, `device_id`, `ended_at`, `reason` |
| `EveryoneSignedOut` | `at` |
| `SessionResumed<U>` | `user`, `session`, `handle` |
| `ImpersonationStarted<U>` | `impersonator`, `user`, `handle` |
| `ImpersonationEnded<U>` | `impersonator`, `user`, `reason`, `returned`, `handle` |
| `RememberMeReused<U>` | `user`, `session`, `handle` |
| `SessionContested<U>` | `user`, `session`, `handle` |

When each fires is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/events#sessions-and-devices) describes. `events::RegisteredSession` is the session these carry, and isn't the `RegisteredSession` that `Sessions` returns.

### Why a Registered Session Ended

`RegisteredSessionEnded` fires for every registered session that ends, in any request, with plain values. Its `reason` is a `SessionEndReason`, with the PHP package's reasons: `logged_out`, `signed_out_everywhere`, `revoked`, `signed_in_again`, `device_revoked`, `device_reported`, `device_limit`, `session_limit`, `account_deleted`, `password_changed`, `password_reset`, `email_changed`, `email_change_undone`, `risk`, `idle`, `expired`, `other_user`, `reused`, `contested`, `not_allowed` and `impersonation_ended`. When each is given is in the [PHP table](https://keyringauth.com/docs/0.x/events#why-a-registered-session-ended).

Two differences: your own `auth.logout()` always gives `logged_out`, as there's no `Sessions::because()`, and `Sessions::sign_out_everywhere()` gives `revoked`. With [the sweep](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#sweeping-ended-sessions) on, the event is at least once.

## Authenticators

`AuthenticatorAdded<U>`, `AuthenticatorRemoved<U>`, `RecoveryCodesGenerated<U>` (`user`, `authenticator`), `RecoveryCodeUsed<U>` (`user`, `authenticator`, `remaining`) and `CloneSuspected<U>` (`user`, `authenticator`), as in the PHP package. A password reset's unlinking of identity providers dispatches `AuthenticatorRemoved` for each. See [Managing Authenticators](https://keyringauth.com/docs/0.x/rust/authenticators#events).

## Account Changes

| Event | Fields |
|---|---|
| `EmailChangeRequested<U>` | `user`, `change` |
| `EmailChanged<U>` | `user`, `change` |
| `EmailChangeReverted<U>` | `user`, `change` |
| `PasswordChanged<U>` | `user` |
| `PasswordReset<U>` | `user` |
| `PasswordChangeRequired<U>` | `user`, `reason` |
| `ProtectionBypassed<U>` | `user` (the actor who made the change, if any), `reason` |

`change` is an `events::EmailChange`, the PHP package's `PendingChange` without its tokens. `ProtectionBypassed`'s `user` is the actor you passed to `without_protection()`, which the PHP package's listener reads from the guard. See [Protected Changes](https://keyringauth.com/docs/0.x/rust/protected-changes#events).

## Risk

`RiskAssessed<U>` fires when an assessment's action did something, with `user`, the `Risk`, the `Action` and the `Checkpoint`. See [Risk](https://keyringauth.com/docs/0.x/rust/risk#events-and-logging).

## Refusals

| Event | When |
|---|---|
| `AccessRefused<U>` | A session handle, device or authenticator that isn't the user's, or a verification link that's someone else's. |
| `RateLimited<U>` | The `keyring-login-options`, `keyring-session-changes`, `keyring` or `keyring-pages` limiter refused a request. |
| `EnrollmentRefused<U>` | A sign-in method wasn't added: `invalid`, `not_allowed`, `frozen` or `password`. |
| `AuthenticatorRemovalRefused<U>` | A sign-in method was kept: `last_factor` or `frozen`. |
| `LinkRefused<U>` | An emailed link was refused: a reset link's token, a verification or "this wasn't me" link's signature, an email change's link (`token`, `ended` or `unknown`), or a sign-in link Keyring didn't make (`sign_in_link`, `token`). |
| `VerificationRefused<U>` | A verification was refused at the end, because a mandatory step hadn't run. It carries the `user` beside the attempt, and the skipped steps' short names. |

None of these changes what the refused person sees, as in the PHP package. Keyring keeps no metrics of its own, so count from these events with a listener:

```rust
use laravel::event::Event;
use laravel_keyring::events::{FactorFailed, Lockout};

async fn count_failures(event: Event<FactorFailed<User>>) -> laravel::Result<()> {
    metrics::increment("auth.failed", &event.factor);
    Ok(())
}

async fn count_lockouts(event: Event<Lockout>) -> laravel::Result<()> {
    metrics::increment("auth.locked_out", &event.factor);
    Ok(())
}
```

`metrics` stands for whatever your application reports to.

## Laravel's Auth Events

Not available: laravel-rust has no `Login`, `Logout`, `Registered`, `Verified`, `Failed`, `Lockout` or `PasswordReset` events, so Keyring dispatches its own alone. Listen for `Authenticated`, `LoggedOut`, `FactorFailed`, `Lockout` and `PasswordReset` from `laravel_keyring::events` instead. There's no event for a registration, or for a verified address.

## How It Works

An event's fields are its values: anything that reads them sees them all, including a `Debug` print. Keep the registry IDs of `SessionResumed`, `RememberMeReused` and `SessionContested`, and `ProviderIdentityAccepted`'s identity, out of your logs, as the [PHP docs](https://keyringauth.com/docs/0.x/events#how-it-works) say.
