Search by

Auth is a frontend agnostic authentication backend for Laravel. It includes sign-in, registration, password resets, email verification, email changes, passkeys, two-factor authentication, SMS codes, device management and sign-in alerts.

v0.1 2026-11-29 20:19 UTC

This package is auto-updated.

Last update: 2026-11-29 20:24:54 UTC


README

Auth is a frontend agnostic authentication backend for Laravel. It includes sign-in, registration, password resets, email verification, email changes, passkeys, two-factor authentication, SMS codes, device management and sign-in alerts.

You build the pages. Auth does the rest:

$result = $signIn->attemptPassword($email, $password, $remember, $request);

if ($result === SignInResult::TwoFactorRequired) {
    return Redirect::route('two-factor.challenge');
}

return Redirect::to($redirects->destination());

Every sign-in is rate limited, takes the same time whether or not the email has an account, and sends a security email when it comes from a new device. Codes only work once, even when two requests send one at the same moment.

Installation

You can install the package via Composer. It needs PHP 8.5 with the intl extension, and Laravel 13.

composer require haztakki-yritys/auth

The package will automatically register itself.

Publish the config file:

php artisan vendor:publish --tag="haztakki-auth-config"

Then publish and run the migrations:

php artisan vendor:publish --tag="haztakki-auth-migrations"
php artisan migrate

They include the passkeys table, so don't publish laravel/passkeys' own migration. An app that already has that table keeps it, and it gains the column the package needs.

Finally, have your user model extend the one from the package:

use Haztakki\Auth\Models\User as Authenticatable;

class User extends Authenticatable
{
}

Note: the migrations add the columns the package needs to your existing users table, and give existing users a UUID. Columns you already have are left alone. Your model can keep its own #[Fillable], #[Hidden] and casts(), because the package adds its own to them. Email addresses are stored in lowercase.

Usage

Auth registers no routes of its own. You define your routes and pages, then call the package from each one. Actions for a signed-in person are methods on the user. Signing in, registering and resetting a password go through a service, because there's no user yet.

Signing in

use Haztakki\Auth\Services\SignInService;

$signIn->attemptPassword($email, $password, $remember, $request);

$signIn->sendPhoneCode($phone);
$signIn->attemptPhoneCode($phone, $code, $remember, $request);

$signIn->signOut();

A wrong password or code throws a ValidationException. When the account has two-factor authentication, the attempt returns SignInResult::TwoFactorRequired. Finish signing in with a code from the authenticator app or a recovery code:

$user = $signIn->challengedUser();

if ($user === null) {
    return Redirect::route('login');
}

if ($user->verifyTwoFactorCode($code) || $user->verifyTwoFactorRecoveryCode($code)) {
    $signIn->completeChallenge($user, $request);
}

The challenge lasts ten minutes. Use SignInRedirectService::destination() to send people on, either to the page they were going to or to your home.

Registering

use Haztakki\Auth\Services\RegistrationService;

$user = $registration->register($request->validated(), $request);

The new user is signed in. Laravel's Registered event is fired, and the verification email goes out.

Passwords

use Haztakki\Auth\Services\PasswordService;

$user->changePassword($password);

$passwords->sendResetLink($email, $request);
$passwords->reset($credentials, $request);

Changing or resetting a password signs every other device out and sends an email. reset() returns a SignInResult, because an account with two-factor authentication is asked for a code first. Show the same message after sendResetLink() whether or not the address has an account.

Profile

$user->updateProfile([
    'name' => $name,
    'email' => $email,
    'phone' => $phone,
]);

$user->verifyPhone($code);
$user->resendPhoneVerification();
$user->cancelPhoneChange();

$user->resendEmailChangeConfirmation();
$user->cancelEmailChange();
$user->resendEmailVerification();

A new email address is only applied once it's confirmed from a link sent to the current address. A new phone number is only applied once it's confirmed with an SMS code.

Once an email change is applied, the old address gets a link to take the account back for seven days. It puts the old address back, replaces the password, removes the phone number, two-factor authentication and passkeys, and signs the account out everywhere. Then it sends the person to choose a new password.

Two-factor authentication

$user->enableTwoFactor();
$user->twoFactorQrCodeSvg();
$user->twoFactorRecoveryCodes();
$user->confirmTwoFactor($code);

$user->hasTwoFactorEnabled();
$user->regenerateTwoFactorRecoveryCodes();
$user->disableTwoFactor();

Two-factor authentication isn't on until confirmTwoFactor() gets a valid code. twoFactorQrCodeUrl() and twoFactorSecret() are there for apps that draw their own QR code.

Devices

Add the middleware to your web group:

use Haztakki\Auth\Http\Middleware\HandleRemoteSignOut;
use Haztakki\Auth\Http\Middleware\TrackDeviceSession;

$middleware->web(append: [
    HandleRemoteSignOut::class,
    TrackDeviceSession::class,
]);

Then list the signed-in devices and sign them out:

$user->activeDevices();
$user->signOutDevice($device->identifier(), note: 'Lost phone');
$user->signOutOtherDevices();

The device being used is never signed out from here. Its session ends straight away, and on its next request the browser is sent to your login page with ?signed_out= and the reason, plus ?note= when there's a note. SignOutNoticeService::findNote($token) reads the note.

To sign the other browser out without waiting for its next request, listen for the broadcast. The person's open pages hear sessions.signed-out on the private users.{identifier} channel. Authorise it in routes/channels.php:

Broadcast::channel('users.{identifier}', fn (User $user, string $identifier): bool => $user->identifier() === $identifier);

The event lists the identifiers of the devices that were signed out. Give each page its own device's identifier from $user->currentDevice()?->identifier(), and reload only when it's in the list, for example with Laravel Echo:

Echo.private(`users.${userIdentifier}`)
    .listen('.sessions.signed-out', (event) => {
        if (event.devices.includes(currentDevice)) {
            window.location.reload();
        }
    });

The reload lands the signed-out browser on your login page, and every other page carries on. The event never contains session IDs. Without broadcasting set up, the browser is signed out on its next request instead.

Device sessions need a session driver other than cookie.

Passkeys

Passkeys use laravel/passkeys. Its routes are registered when the feature is on, and its JavaScript does the browser side. Adding or removing a passkey sends a security email.

Routes

Auth needs a few routes in your app, named as in the routes config:

use Haztakki\Auth\Http\Controllers\ConfirmEmailChangeController;
use Haztakki\Auth\Http\Controllers\SignOutController;
use Haztakki\Auth\Http\Controllers\UndoEmailChangeController;
use Haztakki\Auth\Http\Controllers\VerifyEmailController;

Route::post('/logout', SignOutController::class)->name('logout');

Route::middleware(['auth', 'signed'])->group(function () {
    Route::get('/email/verify/{user}/{hash}', VerifyEmailController::class)->name('verification.verify');
    Route::get('/email/change/{user}', ConfirmEmailChangeController::class)->name('email.change.confirm');
});

Route::middleware('signed')->group(function () {
    Route::get('/email/undo/{user}', ShowUndoEmailChange::class)->name('email.change.undo');
    Route::post('/email/undo/{user}', UndoEmailChangeController::class);
});

ShowUndoEmailChange is your page with a button that posts to the same URL, query string included. Nothing changes when the link is only opened, so a mail scanner that opens it does nothing. Each controller checks the signature itself too.

The routes config also names your login, profile, security, password.request and password.reset pages, which emails and redirects link to. After an email change, the profile page gets ?email_changed=1 or ?email_change_failed=1. After taking an account back, the reset page gets ?email_change_undone=1, or the login page gets ?email_change_undo_failed=1.

People land on the home page after signing in, profile.edit by default. When it depends on the person, set home to a class instead:

use Haztakki\Auth\Contracts\Home;

class ProfileHome implements Home
{
    public function url(User $user): string
    {
        return URL::route('users.show', $user);
    }
}

Emails

Each security change sends a short, queued email: email, password, phone, two-factor and passkey changes, and sign-ins from a new device or country. Laravel's verify and reset emails are restyled to match. Publish the views with --tag="haztakki-auth-views", or swap any email for your own notification class in the notifications config.

Sign-in alerts look the country up on countries.dev, which is sent the sign-in's IP address. Set countries.url to null to stop that, or switch sign_in_alerts off.

SMS

Codes are texted from the queue through 46elks by default:

FORTY_SIX_ELKS_USERNAME=
FORTY_SIX_ELKS_PASSWORD=
FORTY_SIX_ELKS_FROM=

To use another provider, implement Haztakki\Auth\Contracts\SmsTransport and set it as sms.transport.

Features

Each optional feature can be switched off in the config:

'features' => [
    'passkeys' => true,
    'two_factor' => true,
    'phone' => true,
    'device_sessions' => true,
    'sign_in_alerts' => true,
],

A switched-off feature registers nothing, and its methods throw a FeatureDisabledException. Its tables and columns are still migrated, so you can switch it on later. Switching two_factor off signs people in without a code, even if they had set it up.

Identifiers

Users, signed-in devices and passkeys appear in links, routes and broadcast channels by the identifier you choose in the config: their id, uuid or sqid. The numeric key always stays the internal key.

'identifier' => 'sqid',

Use $model->identifier() wherever you show one, and User::findByIdentifier($value) to look one up. A value that can't be an identifier finds nothing.

Rate limits

Sign-in, codes, links and texts are rate limited inside the package, so an app can't forget a limit. Each limit can be changed in the throttle config, and throttle.enabled switches them all off for apps that limit these themselves. Going over a limit throws a ValidationException with the seconds to wait.

Events and rules

  • DeviceSessionsEnding is dispatched just before device sessions are deleted, so you can tidy up anything tied to them.
  • SessionsSignedOut is the broadcast described under Devices.
  • RedirectIfEmailVerified sends verified people away from your "verify your email" page.
  • The validation rules DefaultPassword, InternationalPhone and NotTakenByAnotherUser are in Haztakki\Auth\Rules. Pass NotTakenByAnotherUser confirmed columns only, such as email and phone.

Customising

Every model, table, route name, email, limit and lifetime can be changed in the config. Nothing in the package is final, so you can extend any class and bind your own:

$this->app->bind(SignInService::class, MySignInService::class);

The methods on the user go through the same services, so a class you bind changes them too.

Testing

composer test

Security

If you discover a security vulnerability, please email security@haztakki.solutions instead of opening an issue. Include what you found, the steps to reproduce it and the version you tested. We'll confirm we've received it within a few working days, keep you updated while we fix it, and credit you in the release notes if you'd like.

License

The MIT License (MIT). Please see License File for more information.