Writing your own actions | laravel-suspicious-login | Spatie       

 SPATIE  

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

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-suspicious-login](https://spatie.be/docs/laravel-suspicious-login/v1)  Responding-to-suspicious-logins  Writing your own actions

 Version   v1      

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

  Writing your own actions    
- [ Introduction ](https://spatie.be/docs/laravel-suspicious-login/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-suspicious-login/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-suspicious-login/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-suspicious-login/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-suspicious-login/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-suspicious-login/v1/changelog)
- [ About us ](https://spatie.be/docs/laravel-suspicious-login/v1/about-us)

Basic usage
-----------

- [ Getting started ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/getting-started)
- [ How a login is scored ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/how-a-login-is-scored)
- [ Choosing a preset ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/choosing-a-preset)
- [ Customizing presets ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/customizing-presets)
- [ Working with login attempts ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/working-with-login-attempts)
- [ Adding custom properties ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/adding-custom-properties)
- [ Recording logins manually ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/recording-logins-manually)

Available checks
----------------

- [ Overview ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/overview)
- [ New device ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-device)
- [ New IP address ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-ip)
- [ New country ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-country)
- [ Impossible travel ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/impossible-travel)
- [ Allowed and blocked countries ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/country)
- [ Failed attempts ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/failed-attempts)
- [ Credential stuffing ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/credential-stuffing)
- [ Unusual time ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/unusual-time)
- [ Suspicious user agent ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/suspicious-user-agent)
- [ IP reputation ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/ip-reputation)
- [ Multiple countries ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/multiple-countries)

Responding to suspicious logins
-------------------------------

- [ Notifying users ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/notifying-users)
- [ Blocking logins ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/blocking-logins)
- [ Writing your own actions ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/writing-your-own-actions)
- [ Using events ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/using-events)

Advanced usage
--------------

- [ Creating custom checks ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/creating-custom-checks)
- [ Geolocation drivers ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/geolocation-drivers)
- [ IP reputation drivers ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/ip-reputation-drivers)
- [ Device fingerprints ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/device-fingerprints)
- [ Using your own model ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/using-your-own-model)

 Writing your own actions
========================

###  On this page 

1. [ Sending a webhook ](#content-sending-a-webhook)
2. [ Asking for a second factor ](#content-asking-for-a-second-factor)
3. [ Actions or events? ](#content-actions-or-events)

An action is anything that should happen when a login is suspicious. Notifying the user and blocking the login are built in. For anything else, write your own action: alert your security team, ask for a second factor, or end other sessions.

An action extends `Spatie\SuspiciousLogin\Actions\Action` and implements `execute`. It receives the `LoginAttempt`, with its user, score, risk level and reasons:

```
namespace App\SuspiciousLogin\Actions;

use Illuminate\Support\Facades\Log;
use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Models\LoginAttempt;

class LogToSecurityChannelAction extends Action
{
    public function execute(LoginAttempt $attempt): void
    {
        Log::channel('security')->warning('Suspicious login', [
            'user_id' => $attempt->authenticatable_id,
            'ip' => $attempt->ip_address,
            'risk_score' => $attempt->risk_score,
            'reasons' => collect($attempt->reasons)->pluck('reason')->all(),
        ]);
    }
}
```

Use it in your preset like any other action:

```
use App\SuspiciousLogin\Actions\LogToSecurityChannelAction;
use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Actions\NotifyUserAction;

public function onMediumRisk(): Action|array
{
    return NotifyUserAction::new();
}

public function onHighRisk(): Action|array
{
    return [NotifyUserAction::new(), LogToSecurityChannelAction::new()];
}
```

These methods belong in your [preset](/docs/laravel-suspicious-login/v1/basic-usage/customizing-presets). Configure a `security` log channel in `config/logging.php`, or change the action to use an existing channel.

Actions are resolved from the container by `new()`, so you can inject dependencies in the constructor. Add your own fluent methods to configure them, the way `BlockLoginAction` has `message()`.

Sending a webhook
-----------------------------------------------------------------------------------------------------------

To send suspicious logins to an external service, create an action that queues a webhook. Queue the delivery so a slow or unavailable endpoint does not hold up the login or prevent later actions from running:

```
namespace App\SuspiciousLogin\Actions;

use Illuminate\Support\Facades\Http;
use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Models\LoginAttempt;

class SendWebhookAction extends Action
{
    public function execute(LoginAttempt $attempt): void
    {
        $payload = [
            'event' => 'suspicious_login',
            'login_attempt_id' => $attempt->getKey(),
            'risk_score' => $attempt->risk_score,
            'risk_level' => $attempt->risk_level->value,
            'reasons' => $attempt->reasons,
        ];

        dispatch(function () use ($payload): void {
            Http::timeout(5)
                ->withToken(config('services.security_webhook.token'))
                ->post(config('services.security_webhook.url'), $payload)
                ->throw();
        })->afterCommit();
    }
}
```

Configure an HTTPS endpoint and its bearer token in `config/services.php`:

```
'security_webhook' => [
    'url' => 'https://security.example.com/webhooks/suspicious-login',
    'token' => env('SECURITY_WEBHOOK_TOKEN'),
],
```

Replace the example URL with your endpoint. Keep the token in your deployment's secrets or `.env` file, not in source control.

Then add your action to the preset:

```
use App\SuspiciousLogin\Actions\SendWebhookAction;
use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Actions\BlockLoginAction;

public function onHighRisk(): Action|array
{
    return [SendWebhookAction::new(), BlockLoginAction::new()];
}
```

Use an asynchronous queue connection, such as `database` or `redis`, and run a queue worker. With `sync`, the HTTP request runs during the login instead. The HTTP client throws on unsuccessful responses so the queue worker can handle failed deliveries. Configure worker retries for your needs, and let the receiver use `login_attempt_id` to deduplicate deliveries.

The payload captures the assessment before the remaining actions run; it does not confirm whether the login was subsequently blocked. Only send data the receiving service needs. Reasons from custom checks may contain personal data.

Asking for a second factor
--------------------------------------------------------------------------------------------------------------------------------------

Actions run during the login request, after Laravel has logged the user in. That means an action can still change what happens next. Here's an action that flags the session, so a middleware in your app can send the user to a verification page before they continue:

```
namespace App\SuspiciousLogin\Actions;

use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Models\LoginAttempt;

class RequireVerificationAction extends Action
{
    public function execute(LoginAttempt $attempt): void
    {
        session()->put('login_needs_verification', $attempt->id);
    }
}
```

The middleware, the verification page and the email with the code are up to your app.

Actions or events?
------------------------------------------------------------------------------------------------------------

Actions belong to a preset and depend on the risk level, so they're the right place for the response to a suspicious login. If you want to react to every login, or to something that happens regardless of the preset, [listen for an event](/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/using-events) instead.

 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)
