Sign in

A sign-in screen with no password: the reader gives an email address, gets a six-digit code, and types it in. One view draws both steps in a centred card, with the wrong-code, expired-code and too-many-attempts states and a Resend that waits.

Sign in: the code step, light and dark

Sign in on a phone, light and dark

A block, not a component: copy the view below into your app. It assumes the base layout, which loads Alpine and the package's script.

What it shows

  • The email step, autofocused, with autocomplete="email". A malformed address comes back with the message under the field and the address still in it.
  • The code step: "We sent a six-digit code to m…@example.com", the OTP input (which asks the browser for the code from the message with autocomplete="one-time-code"), Verify, Send a new code and Use a different email.
  • Wrong code and expired code: the message under the boxes, every box marked invalid and described by it.
  • Too many attempts: a danger alert above the boxes, which are disabled, as are Verify and Send a new code.
  • Resend waits: Send a new code is disabled while $resendIn is above zero, with the wait written under it by the server ("You can ask for another in 45 seconds"). Nothing ticks: the line is right when the page is drawn and the next page brings a fresh one.

Built from

  • Panel: the card, body="plain"
  • Input: the email field
  • OTP input: the code
  • Button: Continue, Verify, Send a new code
  • Link: Create an account, Use a different email, Terms and Privacy
  • Divider: between the form and what follows it
  • Alert: too many attempts
  • Icon: the brand mark

The markup

resources/views/auth/sign-in.blade.php

{{--
    Both steps of signing in with an emailed code. The controller passes
    $email (masked) once a code has been sent, and $resendIn, the seconds
    before another may be asked for. $locked is true after too many wrong codes.
--}}
<x-layouts.base :title="isset($email) ? 'Enter your code' : 'Sign in'">
    <div class="flex min-h-dvh flex-col items-center px-4 py-10 sm:py-16">
        <header class="mb-8 flex items-center gap-2.5">
            <span class="flex size-9 items-center justify-center rounded-control bg-surface-inverse text-on-inverse">
                <x-ds::icon name="cube-transparent" size="5" />
            </span>
            <span class="text-title text-fg">Pebblework</span>
        </header>

        <main class="w-full max-w-sm">
            <x-ds::panel body="plain">
                @isset($email)
                    <h1 class="text-heading text-fg">Check your email</h1>
                    <p class="mt-1 text-body text-fg-muted">
                        We sent a six-digit code to <strong class="font-medium text-fg">{{ $email }}</strong>.
                        It works for 10 minutes.
                    </p>

                    @if ($locked ?? false)
                        <x-ds::alert tone="danger" title="Too many attempts" class="mt-5">
                            For your security, codes for this address are paused for 15 minutes.
                        </x-ds::alert>
                    @endif

                    <form method="POST" action="{{ route('sign-in.verify') }}" class="mt-6 flex flex-col gap-5">
                        @csrf
                        <x-ds::otp-input
                            name="code"
                            label="Code"
                            :error="$errors->first('code')"
                            :disabled="$locked ?? false"
                            :autofocus="! ($locked ?? false)"
                            @complete="$el.form.requestSubmit()"
                        />
                        <x-ds::button type="submit" class="w-full" :disabled="$locked ?? false">Verify</x-ds::button>
                    </form>

                    <x-ds::divider class="mt-6 mb-5" />

                    <form method="POST" action="{{ route('sign-in.resend') }}">
                        @csrf
                        <x-ds::button type="submit" variant="secondary" size="sm" :disabled="$resendIn > 0" aria-describedby="resend-wait">
                            Send a new code
                        </x-ds::button>
                        <p id="resend-wait" class="mt-2 text-meta text-fg-muted">
                            @if ($resendIn > 0)
                                Didn't arrive? You can ask for another in {{ \Carbon\CarbonInterval::seconds($resendIn)->cascade()->forHumans() }}.
                            @else
                                Didn't arrive? Check your spam folder, or ask for another.
                            @endif
                        </p>
                    </form>

                    <p class="mt-4 text-meta">
                        <x-ds::link :href="route('sign-in')" variant="muted">Use a different email</x-ds::link>
                    </p>
                @else
                    <h1 class="text-heading text-fg">Sign in to Pebblework</h1>
                    <p class="mt-1 text-body text-fg-muted">We'll email you a code. There's no password to remember.</p>

                    <form method="POST" action="{{ route('sign-in.send') }}" class="mt-6 flex flex-col gap-5" novalidate>
                        @csrf
                        <x-ds::input
                            type="email"
                            name="email"
                            label="Email address"
                            autocomplete="email"
                            required
                            autofocus
                            :value="old('email')"
                            :error="$errors->first('email')"
                        />
                        <x-ds::button type="submit" class="w-full">Continue</x-ds::button>
                    </form>

                    <x-ds::divider class="mt-6 mb-5" />

                    <p class="text-body text-fg-muted">
                        New to Pebblework?
                        <x-ds::link :href="route('sign-up')">Create an account</x-ds::link>
                    </p>
                @endisset
            </x-ds::panel>
        </main>

        <footer class="mt-8">
            <nav aria-label="Legal" class="flex gap-4">
                <x-ds::link :href="route('terms')" variant="muted" size="sm">Terms</x-ds::link>
                <x-ds::link :href="route('privacy')" variant="muted" size="sm">Privacy</x-ds::link>
            </nav>
        </footer>
    </div>
</x-layouts.base>

Wire it up

Five routes, one controller. The code lives in your cache, hashed, for ten minutes; it is in the email and nowhere else, never in the page or the session.

// routes/web.php
use App\Http\Controllers\Auth\EmailCodeController;

Route::middleware('guest')->controller(EmailCodeController::class)->group(function () {
    Route::get('/sign-in', 'create')->name('sign-in');
    Route::post('/sign-in', 'send')->name('sign-in.send')->middleware('throttle:6,1');
    Route::get('/sign-in/code', 'code')->name('sign-in.code');
    Route::post('/sign-in/code', 'verify')->name('sign-in.verify');
    Route::post('/sign-in/code/resend', 'resend')->name('sign-in.resend');
});
// app/Http/Controllers/Auth/EmailCodeController.php
namespace App\Http\Controllers\Auth;

use App\Mail\SignInCode;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class EmailCodeController
{
    public function create()
    {
        return view('auth.sign-in');
    }

    public function send(Request $request)
    {
        $email = Str::lower($request->validate([
            'email' => ['required', 'email'],
        ], [
            'email.email' => 'Enter an email address like [email protected].',
        ])['email']);

        $request->session()->put('sign-in.email', $email);
        $this->sendCode($email);

        return to_route('sign-in.code');
    }

    public function code(Request $request)
    {
        $email = $request->session()->get('sign-in.email');

        if (! $email) {
            return to_route('sign-in');
        }

        $locked = RateLimiter::tooManyAttempts("sign-in-verify:{$email}", 5);

        return view('auth.sign-in', [
            'email' => Str::substr($email, 0, 1).'…@'.Str::after($email, '@'),
            'locked' => $locked,
            'resendIn' => $locked
                ? RateLimiter::availableIn("sign-in-verify:{$email}")
                : (RateLimiter::tooManyAttempts("sign-in-resend:{$email}", 1) ? RateLimiter::availableIn("sign-in-resend:{$email}") : 0),
        ]);
    }

    public function verify(Request $request)
    {
        $email = $request->session()->get('sign-in.email');
        $request->validate(['code' => ['required', 'digits:6']], [
            'code.*' => 'Enter the six digits from the email.',
        ]);

        if (! $email || RateLimiter::tooManyAttempts("sign-in-verify:{$email}", 5)) {
            return to_route($email ? 'sign-in.code' : 'sign-in');
        }

        $hash = Cache::get("sign-in-code:{$email}");

        if (! $hash) {
            return back()->withErrors(['code' => 'That code has expired. Send a new one below.']);
        }

        if (! Hash::check($request->input('code'), $hash)) {
            RateLimiter::hit("sign-in-verify:{$email}", 15 * 60);

            return back()->withErrors(['code' => "That code isn't right. Check the latest email and try again."]);
        }

        Cache::forget("sign-in-code:{$email}");
        RateLimiter::clear("sign-in-verify:{$email}");
        $request->session()->forget('sign-in.email');

        Auth::login(User::where('email', $email)->firstOrFail(), remember: true);
        $request->session()->regenerate();

        return redirect()->intended('/');
    }

    public function resend(Request $request)
    {
        $email = $request->session()->get('sign-in.email');

        if ($email && ! RateLimiter::tooManyAttempts("sign-in-resend:{$email}", 1)) {
            $this->sendCode($email);
        }

        return to_route($email ? 'sign-in.code' : 'sign-in');
    }

    private function sendCode(string $email): void
    {
        RateLimiter::hit("sign-in-resend:{$email}", 45);

        // Only an account that exists gets a code; the page says the same
        // either way, so it does not tell anyone who has an account.
        if (! User::where('email', $email)->exists()) {
            return;
        }

        $code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        Cache::put("sign-in-code:{$email}", Hash::make($code), now()->addMinutes(10));
        Mail::to($email)->send(new SignInCode($code));
    }
}

SignInCode is an ordinary mailable (php artisan make:mail SignInCode) whose view prints the code. Put the code alone on its own line, so the phone's one-time-code suggestion can find it.

Rate limits, three of them. throttle:6,1 on the email step stops one address or IP asking for codes in a loop; sign-in-resend:{email} holds Send a new code back for 45 seconds after each email; sign-in-verify:{email} locks the code step for 15 minutes after five wrong codes, which is what draws the alert. The lock is per address, not per session, so starting over in a private window does not reset it.

With Livewire, the same view is one component: make $email, $code and $resendIn public properties, swap each form's method/action for wire:submit="send" and wire:submit="verify", bind the fields with wire:model="email" and wire:model="code", and call $wire.verify() from the OTP input's @complete instead of submitting the form. The controller's methods become the component's, returning nothing instead of redirecting. Pass :value="$code" to the OTP input so the boxes are right on every render.

Phone, keyboard, no script

  • On a phone the card fills the width with a 16px margin; the OTP boxes narrow to fit six across at 320px rather than wrap.
  • Keyboard: the field (or the first box) has focus when the page opens. Tab goes field, Continue, Create an account, then the footer links; on the code step the boxes take arrow keys, Backspace and paste (see OTP input), and a complete code submits itself.
  • No script: the email step is a plain form and works. The code boxes need the script: without it, digits typed into them are not posted. A sign-in that must work with JavaScript off should use an input with inputmode="numeric" and autocomplete="one-time-code" for the code instead.
  • Submitting: the buttons do not show the spinner while the request is in flight; Button's loading is drawn by the server, so in a plain form there is nothing to turn it on. With Livewire add wire:loading.attr="disabled" to Verify to stop a second press.

From the package repo: edit this page on GitHub.

Was this page helpful?