Usage | laravel-suspicious-login-rust | Spatie       

 SPATIE  

laravel-suspicious-login-rust
=============================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-suspicious-login-rust](https://spatie.be/docs/laravel-suspicious-login-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-suspicious-login-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/usage)
- [ Detection ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/detection)
- [ Testing ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/changelog)
- [ Customization ](https://spatie.be/docs/laravel-suspicious-login-rust/v1/customization)

 Usage
=====

###  On this page 

1. [ Monitor authentication ](#content-monitor-authentication)
2. [ Record an observation ](#content-record-an-observation)
3. [ Handle events and actions ](#content-handle-events-and-actions)
4. [ Delivery and errors ](#content-delivery-and-errors)
5. [ Daily cleanup ](#content-daily-cleanup)

Monitor authentication
--------------------------------------------------------------------------------------------------------------------------

- Implement `LoginUser::suspicious_login_email` on your native `Authenticatable` account. Return an application-approved email address, or `None` to skip warnings.
- Inject the monitor in every login handler. Pass validated, bounded identifiers and keep application rate limiting enabled.
- Use the helper's last argument for remember-me. The framework guard still validates credentials, rotates sessions and manages remember cookies.

```
use laravel::{auth::Auth, container::Inject, hash::Password, http::Request};
use spatie_suspicious_login::{LoginUser, SuspiciousLogin};

async fn authenticate<U: LoginUser>(
    monitor: Inject<SuspiciousLogin>,
    auth: Auth<U>,
    request: Request,
    identifier: &str,
    password: &Password,
) -> laravel::Result<U> {
    monitor.attempt(&auth, &request, identifier, password, false).await
}
```

- For verified social/passwordless identities, call `monitor.login(&auth, &request, &user, remember).await?`. Never pass an unverified form identity.
- Rejected credentials retain the framework validation response. The guard does not expose the rejected account, so helper failures contain the identifier but no user ID.
- Passwords never enter observation or event payloads.
- Direct guard calls, API/request guards and session/remember restoration are not observed automatically.

Record an observation
-----------------------------------------------------------------------------------------------------------------------

- `record_success(&user, &request, LoginOptions::default()).await?` assesses, persists and runs actions.
- `record_failed::<User>(known_user, &request, options).await?` records without checks, lookups, policy resolution or warnings. Supply a known account when your authentication provider exposes it.
- `LoginOptions` accepts guard labels, non-secret identifiers and JSON properties. Explicit properties override `Config::properties`.
- These methods remain available when `Config::enabled` is false; that flag bypasses only the login helpers.
- Manual recording does not own authentication. Check the returned `blocked` flag and terminate a blocked session yourself.
- `assess(&mut attempt).await?` fills scores and reasons without persistence, events, geolocation or actions. Reputation checks can still use their configured backend.
- `attempts_for::<User>(&user_id).await?` returns account history, oldest first. Timestamp ties use attempt ID ordering. Unknown-user failures cannot be returned by account ID.

Handle events and actions
-----------------------------------------------------------------------------------------------------------------------------------

Native events run in this order:

1. `LoginAttemptRecorded`, after persistence, for successes and failures.
2. `SuspiciousLoginDetected`, for medium/high successes, before actions.
3. `SuspiciousLoginBlocked`, after blocked status is saved, before helper logout.

- Register normal `Event<T>` listeners in `with_events`. Listeners can inject native services.
- Payloads own snapshots. Recorded/detected snapshots precede any later blocking.
- The helper logs out blocked sessions even if a blocked-event listener fails.
- `Action::Block` stops later actions. Put notifications first to send them before blocking, or put blocking first when logout must precede potentially failing work.

Delivery and errors
-----------------------------------------------------------------------------------------------------------------

- Warning actions queue the selected native mailable. Configure a framework queue connection and worker for asynchronous delivery; a sync connection runs immediately.
- The default plain-text message contains the application name, time, IP, location, browser and reasons. Escape untrusted values in custom HTML messages.
- Database, event and queue errors propagate. Persistence happens before events and delivery; earlier actions are not rolled back.
- A delivery failure does not undo a successful guard login unless a block action has completed. Do not retry the whole login after delivery failure. There is no outbox or exactly-once guarantee.
- Setup returns typed `spatie_suspicious_login::Error` variants. Framework operations retain their original error types.

Daily cleanup
-----------------------------------------------------------------------------------------------

- Retention defaults to 365 days. The cutoff is inclusive.
- Schedule pruning in the application:

```
use laravel::container::Inject;
use spatie_suspicious_login::SuspiciousLogin;

laravel::Application::configure().with_schedule(|schedule, _| {
    schedule.call(|monitor: Inject<SuspiciousLogin>| async move {
        monitor.prune().await?;
        Ok::<_, laravel::Error>(())
    }).name("suspicious-login:prune").daily();
});
```

- Run `schedule:run` through the application's scheduler process.
- Pruning deletes only selected-model history, not users or sessions. Deleted observations no longer inform assessments.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
