<!-- Source: @site/projects/fortify-hardening-for-laravel/docs/03-registration.md -->
<!-- Canonical: https://docs.pushery.com/fortify-hardening-for-laravel/registration/ -->

# Registration

> A taken address and a free one get the same answer, nobody is signed in, and the holder of a taken address learns of the attempt.

Fortify's registration refuses a taken address with a validation error and signs a new account in.
Either outcome tells the caller whether the address has an account. With the package, both read
"We have sent an email to that address. Please check your inbox to continue." The new account
gets its verification mail, and the holder of a taken address gets a mail saying that somebody
tried to register with it.

## On Fortify's route

Nothing needs to be wired. The package puts its controller in place of Fortify's, so a `POST` to
Fortify's registration route goes through these steps:

1. The request is validated by the [form request](#the-form-request), with the same rules for every
   address.
2. The address is looked up through the user provider of Fortify's guard.
3. A free address is created by your `CreatesNewUsers` action, and Laravel's `Registered` event is
   dispatched, which sends the verification mail unless the [mail budget](#the-mail-budget) of the
   address is spent.
4. A taken address gets no second account. Its holder gets the [notice](#the-notice-to-the-holder),
   within the same budget.
5. Either way the caller receives the same [answer](#the-answer), and nobody is signed in.

When `fortify.lowercase_usernames` is on, the address is lowercased before any of this, as Fortify
would do it.

## A username of its own

The neutral registration on Fortify's route assumes that people sign in with their address, so
that `fortify.username` and `fortify.email` name the same field, as in Fortify's own configuration.
Where `fortify.username` names a field of its own, a registration carries two values that can each
be taken. A taken username has to be refused, or the person cannot choose another, and the
package's controller would reach that refusal only for a free address, which tells a free address
from a taken one. In that configuration the package leaves Fortify's registration in place: a
taken address or a taken username is refused with the errors of your `CreatesNewUsers` action, and
a new account is signed in. The password reset and the sign-in stay covered.

To keep the address closed there as well, register from
[a controller of your own](#from-a-controller-of-your-own). Answer for the username before the
address is looked up, the same way whether the address is free or taken, and then hand the address
to the registrar, which looks it up under `fortify.email`.

## The form request

Validation runs before the address is looked up, for a free address and a taken one alike, so a
deliberately invalid field cannot tell them apart. The default form request,
`Pushery\FortifyHardening\Http\Requests\RegistrationRequest`, carries the rules of Fortify's own
`CreateNewUser` stub without the `unique` rule on the address: a `unique` rule would answer the
very question the registration keeps closed. It also refuses a carriage return or a line feed in
the address with a rule of its own. Laravel's `email` rule lets both through before 13.10.0, and
the address goes into the headers of the mails a registration sends.

If your registration takes more fields, extend it and add their rules:

```php
namespace App\Http\Requests;

use Pushery\FortifyHardening\Http\Requests\RegistrationRequest;

class RegisterRequest extends RegistrationRequest
{
    public function rules(): array
    {
        return [
            ...parent::rules(),
            'terms' => ['accepted'],
        ];
    }
}
```

Then name it in `config/fortify-hardening.php`:

```php
'registration' => [
    'request' => App\Http\Requests\RegisterRequest::class,
],
```

Keep these rules the ones your `CreatesNewUsers` action checks. The action runs only for a free
address, so a field it refuses and the form request lets through is refused for a free address
alone.

## Your account creator

Your `CreatesNewUsers` action stays as it is, its own `unique` rule included. Two requests that
race for one new address can both find it free, and the second creation then fails at that rule or
at the database's unique index. The package treats either failure as a taken address: the holder
gets the notice, and the caller gets the same answer as everybody else.

An action that recognizes the race some other way throws
`Pushery\FortifyHardening\Registration\AddressTurnedOutTaken`, with the same result. Any other
failure is passed on as it would be without the package.

## The answer

| Request | Answer |
|---|---|
| a web form | a redirect to the route named in `registration.redirect_route`, `login` by default, with the message flashed as `status`, or to the application's root when no route of that name exists |
| JSON | `202 Accepted` with `{"message": "We have sent an email to that address. Please check your inbox to continue."}` |

The message comes from the package's translations, in seven languages, and can be overridden like
any other translation (see [Configuration](https://docs.pushery.com/fortify-hardening-for-laravel/configuration.md#translations)).

To answer differently, bind your own implementation of
`Pushery\FortifyHardening\Contracts\RegistrationAccepted` in a service provider's `register()`
method. It has to answer every outcome the same way, because any difference tells the caller
whether the address has an account.

```php
use App\Http\Responses\CheckYourInbox;
use Pushery\FortifyHardening\Contracts\RegistrationAccepted;

$this->app->bind(RegistrationAccepted::class, CheckYourInbox::class);
```

## The notice to the holder

The holder of a taken address receives
`Pushery\FortifyHardening\Notifications\AccountAlreadyExistsNotification`: a short mail saying that
somebody tried to create an account with the address, with the application's name in the subject,
a button to the sign-in page and a line about resetting a forgotten password. It is written in the
application's locale, or in the user's own when the user model implements `HasLocalePreference`,
and it loads no image, font or pixel from anywhere. A regional locale such as `pt-BR` reads the
catalog of its language, see [Translations](https://docs.pushery.com/fortify-hardening-for-laravel/configuration.md#translations).

The notice renders through Laravel's notification template and mail components, so what your
application published of them applies to it as well. One name is the exception: Laravel's mail
header shows Laravel's logo from laravel.com in place of an application name that reads exactly
`Laravel`, the `APP_NAME` a new Laravel application starts with. Under that name the notice renders
through a template of the package, `fortify-hardening::mail.notice`, whose header shows the name as
text. It uses the same mail components, and a copy at
`resources/views/vendor/fortify-hardening/mail/notice.blade.php` takes its place.

![The notice in a mail program: from Linen & Co, hello@shop.example, to mira@example.com, with the subject "Someone tried to register at Linen & Co with your email address". It says that somebody tried to create an account with this address and that the holder already has one, offers a Sign in button, and adds that a forgotten password can be reset from the sign-in page and that nothing needs to be done if it was not the holder.](https://docs.pushery.com/assets/images/account-exists-notice-664620db40a6ade1ade7c19c454ee0fc.webp)

| Setting | Default | What it does |
|---|---|---|
| `registration.notification` | `AccountAlreadyExistsNotification::class` | the notification the holder receives |
| `registration.notice_channels` | `['mail']` | the channels it goes out on |
| `registration.sign_in_route` | `'login'` | the route its button leads to, or the application's root when no route of that name exists |
| `registration.notice_mentions_password_reset` | `true` | whether its last line says that a forgotten password can be reset; `false` points at the sign-in page alone, for an application that signs nobody in with a password |

The notice is sent at once, the way Laravel sends the verification mail of a new account. If your
application queues the verification mail, queue the notice as well, so both answers keep taking the
same time:

```php
namespace App\Notifications;

use Illuminate\Contracts\Queue\ShouldQueue;
use Pushery\FortifyHardening\Notifications\AccountAlreadyExistsNotification;

class QueuedAccountAlreadyExistsNotification extends AccountAlreadyExistsNotification implements ShouldQueue {}
```

```php
'registration' => [
    'notification' => App\Notifications\QueuedAccountAlreadyExistsNotification::class,
],
```

### Naming the application and greeting the holder

The subject names the application with `app.name`, and the mail opens with Laravel's own greeting.
Where one installation serves several instances, or where you greet people by name, override
`applicationName()` and `greeting()` in the same kind of subclass. Both receive the notifiable: the
user who holds the address, or an anonymous notifiable routed to it when the account cannot be
notified. A greeting of `null` keeps Laravel's own. The mail is Markdown, so a greeting returned as a
string is set as text: a name typed as a Markdown link reaches the inbox as those characters, and a web
address in it is written so that a mail program does not link it. A greeting returned as an `Htmlable`
is set as it is.

```php
namespace App\Notifications;

use App\Models\User;
use App\Support\CurrentInstance;
use Pushery\FortifyHardening\Notifications\AccountAlreadyExistsNotification;

class InstanceAccountAlreadyExistsNotification extends AccountAlreadyExistsNotification
{
    public function __construct(private CurrentInstance $instance) {}

    protected function applicationName(object $notifiable): string
    {
        return $this->instance->name();
    }

    protected function greeting(object $notifiable): ?string
    {
        return $notifiable instanceof User ? "Hello {$notifiable->name}," : null;
    }
}
```

The package resolves the class from the container, so its constructor can ask for what it needs.

## The mail budget

Every registration mails the address it names, so the form could be used to fill somebody's inbox.
A throttle on the route counts the client, and a sender who changes clients gets through it. The
package therefore also counts the address: by default one mail per address and hour, set with
`registration.max_mails_per_hour`. A mail over the budget is not sent, and the answer stays the
same.

The budget counts the inbox an address reaches, not its spelling, since every spelling registers as
a new address. Case, surrounding whitespace and a `+tag` in the local part make no other address,
and for Gmail neither do the dots in the local part or the domain `googlemail.com`, which Gmail
delivers to the same inbox as `gmail.com`. Under any other domain a dot stays, since there it can
name another inbox. `Pushery\FortifyHardening\Support\Mailbox::of()` gives the key the budget
counts under, so an application that counts mails of its own can count them the same way. Hash
that key with the application key before it goes into a cache key, as the package does, with
`hash_hmac('sha256', Mailbox::of($address), config('app.key'))`: an error tracker or a store's
monitor records cache keys, and a plain hash of an address can be matched against a guessed one.

Both outcomes spend from the budget, the verification mail of a new account included. If only the
notice counted, the second of two quick registrations for a new address would send a notice at
once, and its timing would tell the address apart from one that had been taken all along.

Over the budget neither outcome mails: the holder of a taken address gets no notice, and a new
account is created without its verification mail. `Registered` still goes out, so your other
listeners run, and the package stops the mail itself as it is about to be sent, in the request or
in the queue worker that sends it. It recognizes Laravel's `Illuminate\Auth\Notifications\VerifyEmail`
and every subclass of it, so a verification notification of your own extends that class. Only the
first verification mail after the registration is held back: a link the person asks for again goes
out.

The count is kept in the cache store Laravel's rate limiter uses, `cache.limiter` or else the
default store, under a lock per address in the same store. Where that store cannot lock, the lock
is taken in the default store. The cache key is an HMAC of the address under the application key
rather than the address itself, so a guessed address cannot be looked for among the keys. Use a
cache store that supports locks, such as Redis, DynamoDB or the database store. Where no store can
lock, the budget still counts, but two requests that arrive at the same moment can then both send.

The count also has to outlast its hour, and so does the note that holds back the verification mail
of an account created over the budget, which is kept in the same store. A count the store loses is a
budget that starts again, and the next registration mails the address once more within the same
hour. A note it loses lets that verification mail go out. A store loses either in three ways:

- **It evicts under memory pressure.** Redis does under every `maxmemory-policy` but `noeviction`,
  the `volatile-*` policies included, because every count and every note carries a TTL. Memcached
  evicts by its LRU unless it runs with `-M`.
- **It is flushed.** `php artisan cache:clear` and `optimize:clear` flush the default store, and a
  deploy often runs one of them. A Redis store flushes the whole database of its connection, a
  database store every row of its table.
- **It restarts without persistence.** Redis does without `appendonly yes`, Memcached every time.

So name a store of its own in `cache.limiter`, one that keeps its keys and that no `cache:clear` of
the default store reaches: a database store with a table of its own, the DynamoDB store, or a Redis
connection and database no other store uses, with `maxmemory-policy noeviction` and
`appendonly yes`. Keep that store out of every `cache:clear` a deploy runs. Memcached does not
qualify: without `-M` it evicts, and every restart empties it. A Redis under `noeviction` that has
filled up drops nothing and refuses every write instead, so give it the memory the counts and notes
of one hour need. On a database store, schedule the
[pruning of expired keys](https://docs.pushery.com/fortify-hardening-for-laravel/installation.md#prune-expired-keys-on-a-database-store), or the rows of
past counts stay in its table for good.

## From a controller of your own

An application that registers users in its own controller rather than on Fortify's route uses the
registrar directly. It looks the address up, creates the account or sends the notice, spends the
budget and dispatches `Registered`, exactly as on Fortify's route:

```php
use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Pushery\FortifyHardening\Registration\Registrar;

public function store(RegisterRequest $request, Registrar $registrar): RedirectResponse
{
    $registrar->register(
        $request->string('email')->value(),
        $request->string('password')->value(),
        fn (string $hashedPassword): User => User::create([
            'name' => $request->string('name')->value(),
            'email' => $request->string('email')->value(),
            'password' => $hashedPassword,
        ]),
    );

    return redirect()->route('login')
        ->with('status', __('fortify-hardening::messages.registration.accepted'));
}
```

`register()` hashes the password once, before the address is looked up, and passes the hash to your
closure, so a free address and a taken one pay for the same hash. Store it as it is: a model with
the `hashed` cast leaves an existing hash alone.

When the code that creates the account hashes the password itself, call `registerHashingInside()`
instead. A taken address then pays one hash of the same password with the same hasher:

```php
use App\Actions\Fortify\CreateNewUser;
use App\Models\User;

$email = $request->string('email')->value();
$password = $request->string('password')->value();
$input = $request->all();
$creator = app(CreateNewUser::class); // Fortify's action, which hashes the password itself

$registrar->registerHashingInside($email, $password, fn (): User => $creator->create($input));
```

Validate the request before either call, without a `unique` rule on the address, and give every
caller the same answer afterward. The registrar signs nobody in, and neither should your
controller.

Either call may run inside a transaction of your own. Where one is open on the connection your
accounts live on, the registrar creates the account in a savepoint, as Laravel's `createOrFirst()`
does. A request that loses the race for a new address then takes back only its failed insert: on
PostgreSQL that failure would otherwise abort the whole transaction, and the notice, the
[mail budget](#the-mail-budget) and everything after the registration would fail with it.
