### Install Laravel One-Time Passwords Package Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Installs the spatie/laravel-one-time-passwords package using Composer. This is the initial step for integrating one-time password functionality into your Laravel application. ```bash composer require spatie/laravel-one-time-passwords ``` -------------------------------- ### Publish One-Time Passwords Configuration File Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Publishes the configuration file for the spatie/laravel-one-time-passwords package. This allows you to customize settings like password expiration, origin enforcement, and more. ```bash php artisan vendor:publish --tag="one-time-passwords-config" ``` -------------------------------- ### Database Migrations for One-Time Passwords Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Publishes and runs the database migrations to create the necessary table for storing one-time passwords. This ensures your database is set up to handle the package's data. ```bash php artisan vendor:publish --tag="one-time-passwords-migrations" php artisan migrate ``` -------------------------------- ### Prepare User Model with HasOneTimePasswords Trait Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Applies the HasOneTimePasswords trait to your User model. This trait provides the necessary methods and logic for generating and managing one-time passwords for users. ```php namespace App\Models; use Spatie\OneTimePasswords\Models\Concerns\HasOneTimePasswords; class User { use HasOneTimePasswords; // ... } ``` -------------------------------- ### Laravel One-Time Passwords Configuration Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Provides the default configuration options for the spatie/laravel-one-time-passwords package. This includes settings for password expiration, uniqueness, origin enforcement, password generation, rate limiting, and model/notification classes. ```php return [ /* * One time passwords should be consumed within this number of minutes */ 'default_expires_in_minutes' => 2, /* * When this setting is active, we'll delete all previous one-time passwords for * a user when generating a new one */ 'only_one_active_one_time_password_per_user' => true, /* * When this option is active, we'll try to ensure that the one-time password can only * be consumed on the platform where it was requested on */ 'enforce_same_origin' => true, /* * This class is responsible to enforce that the one-time password can only be consumed on * the platform it was requested on. * * If you do not wish to enforce this, set this value to * Spatie\OneTimePasswords\Support\OriginInspector\DoNotEnforceOrigin */ 'origin_enforcer' => Spatie\OneTimePasswords\Support\OriginInspector\DefaultOriginEnforcer::class, /* * This class generates a random password */ 'password_generator' => Spatie\OneTimePasswords\Support\PasswordGenerators\NumericOneTimePasswordGenerator::class, /* * By default, the password generator will create a password with * this number of digits */ 'password_length' => 6, 'redirect_successful_authentication_to' => '/dashboard', /* * These values are used to rate limit the number of attempts * that may be made to consume a one-time password. */ 'rate_limit_attempts' => [ 'max_attempts_per_user' => 5, 'time_window_in_seconds' => 60, ], /* * The model uses to store one-time passwords */ 'model' => Spatie\OneTimePasswords\Models\OneTimePassword::class, /* * The notification used to send a one-time password to a user */ 'notification' => Spatie\OneTimePasswords\Notifications\OneTimePasswordNotification::class, /* * These class are responsible for performing core tasks regarding one-time passwords. * You can customize them by creating a class that extends the default, and * by specifying your custom class name here. */ 'actions' => [ 'create_one_time_password' => Spatie\OneTimePasswords\Actions\CreateOneTimePasswordAction::class, 'consume_one_time_password' => Spatie\OneTimePasswords\Actions\ConsumeOneTimePasswordAction::class, ], ]; ``` -------------------------------- ### Schedule Deletion of Expired One-Time Passwords Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/installation-setup.md Configures the Laravel scheduler to periodically prune (delete) expired one-time passwords. This uses Laravel's MassPrunable trait and requires adding the model:prune command to your schedule. ```php use Spatie\OneTimePasswords\Models\OneTimePassword; Schedule::command('model:prune', [ '--model' => [OneTimePassword::class], ])->daily(); ``` -------------------------------- ### Override Create One-Time Password Action Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/avanced-usage/customizing-actions.md This snippet demonstrates how to extend the default `CreateOneTimePasswordAction` class to include custom logic. The example shows adding custom actions after the one-time password has been stored by calling the parent method and then executing custom code. It also includes returning the generated one-time password. ```php namespace App\Actions; use Spatie\OneTimePasswords\Actions\CreateOneTimePasswordAction; use Illuminate\Contracts\Auth\Authenticatable; use Spatie\OneTimePasswords\OneTimePassword; use Illuminate\Http\Request; class CustomCreateOneTimePasswordAction extends CreateOneTimePasswordAction { public function execute( Authenticatable $user, ?int $expiresInMinutes = null, ?Request $request = null ): OneTimePassword { // Call the parent method to store the one-time password $oneTimePassword = parent::execute($user, $expiresInMinutes, $request); // Add your custom logic here // Don't forget to return the one-time password return $oneTimePassword; } } ``` -------------------------------- ### Run Tests Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/README.md This command is used to execute the test suite for the package, ensuring its functionality and stability. ```bash composer test ``` -------------------------------- ### Publish Package Views Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/using-the-livewire-component.md Publishes the package's view assets using the Artisan command, allowing for customization of the component's styling. ```bash php artisan vendor:publish --tag=one-time-passwords-views ``` -------------------------------- ### Livewire Component Basic Usage Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/using-the-livewire-component.md Renders a Livewire component that handles the creation and consumption of one-time passwords. It prompts for an email, sends a password, and then verifies the entered code. ```html ``` -------------------------------- ### Send One-Time Password via Email Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/README.md This snippet demonstrates how to send a one-time password to a user, typically via an email notification. The package handles the generation and delivery of the OTP. ```php // send a mail containing a one-time password $user->sendOneTimePassword(); ``` -------------------------------- ### Publish One-Time Password Views Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/configuring-notifications.md This Bash command publishes the mail notification views for the one-time password package. After running this command, you can customize the appearance of the email notifications by editing the `resources/views/vendor/one-time-passwords/mail.blade.php` file. ```bash php artisan vendor:publish --tag=one-time-passwords-views ``` -------------------------------- ### Livewire Component Consume Only Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/using-the-livewire-component.md Configures the Livewire component to only handle the consumption of a one-time password, skipping the email input by providing the 'email' prop. ```html ``` -------------------------------- ### Create Custom One-Time Password Model Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/avanced-usage/using-your-own-model.md This PHP code snippet demonstrates how to create a custom model that extends the base `OneTimePassword` model provided by the spatie/laravel-one-time-passwords package. You can add custom properties or methods to this model. ```php namespace App\Models; use Spatie\OneTimePasswords\Models\OneTimePassword as BaseOneTimePassword; class CustomOneTimePassword extends BaseOneTimePassword { // Add any custom properties or methods here } ``` -------------------------------- ### Create and Send One-Time Password (PHP) Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/creating-one-time-passwords.md This method generates a one-time password and sends it to the user's email address using the `OneTimePasswordNotification`. It ensures a password is created and delivered. ```php $user->sendOneTimePassword(); ``` -------------------------------- ### Livewire Component Custom Redirect Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/using-the-livewire-component.md Allows customization of the redirect URL after successful authentication by passing the 'redirect-to' prop to the Livewire component. ```html ``` -------------------------------- ### Send One-Time Password via Email Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/introduction.md Sends a one-time password to a user, typically delivered via an email notification. This is a core function for initiating the one-time password authentication flow. ```php // send a mail containing a one-time password $user->sendOneTimePassword(); ``` -------------------------------- ### Create One-Time Password Only (PHP) Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/creating-one-time-passwords.md This method creates a one-time password without sending it to the user. It returns an instance of the newly created `OneTimePassword` model, allowing for further manipulation or storage. ```php $oneTimePasswordModel = $user->createOneTimePassword(); ``` -------------------------------- ### Extend OneTimePasswordNotification for SMS Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/configuring-notifications.md This PHP code demonstrates how to extend the `OneTimePasswordNotification` class to send one-time passwords via SMS using Vonage. It customizes the `via` method to include the 'vonage' channel and implements `toVonage` to format the SMS message content, including the one-time password. ```php namespace App\Notifications; use Spatie\OneTimePasswords\Notifications\OneTimePasswordNotification; class CustomOneTimePasswordNotification extends OneTimePasswordNotification { public function via($notifiable): string|array { return ['vonage']; } public function toVonage(object $notifiable): VonageMessage { // $this->oneTimePassword is an instance of the Spatie\OneTimePasswords\OneTimePassword model return (new VonageMessage) ->content("Your one-time login code is: {$this->oneTimePassword->password}"); } } ``` -------------------------------- ### APIDOC: ConsumeOneTimePasswordResult Enum Cases Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/consuming-one-time-passwords.md Documentation for the `ConsumeOneTimePasswordResult` enum, which is returned by both `attemptLoginUsingOneTimePassword` and `consumeOneTimePassword` methods. This enum provides distinct cases to indicate the outcome of a one-time password consumption attempt. ```APIDOC ConsumeOneTimePasswordResult Enum: - Ok: The one-time password was correct. - NoOneTimePasswordsFound: The user has no one-time passwords. - IncorrectOneTimePassword: The one-time password was incorrect. - DifferentOrigin: The one-time password was created from a different origin. - OneTimePasswordExpired: The one-time password has expired. - RateLimitExceeded: The user has exceeded the rate limit for one-time passwords. ``` -------------------------------- ### Attempt Login with One-Time Password Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/README.md This code attempts to log in a user using a provided one-time password. It checks the validity of the OTP and handles session regeneration upon successful login. Errors are returned with a validation message. ```php use Spatie\OneTimePasswords\Enums\ConsumeOneTimePasswordResult; $result = $user->attemptLoginUsingOneTimePassword($oneTimePassword); if ($result->isOk()) { // it is best practice to regenerate the session id after a login $request->session()->regenerate(); return redirect()->intended('dashboard'); } return back()->withErrors([ 'one_time_password' => $result->validationMessage(), ])->onlyInput('one_time_password'); ``` -------------------------------- ### Configure Custom Model in Laravel Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/avanced-usage/using-your-own-model.md This PHP code snippet shows how to update the `config/one-time-passwords.php` configuration file in a Laravel project to use a custom model for one-time passwords. This allows for customization of the package's behavior. ```php // config/one-time-passwords.php return [ // ... 'models' => [ // The model used to store one-time passwords 'model' => App\Models\CustomOneTimePassword::class, ], ]; ``` -------------------------------- ### Attempt Login with One-Time Password Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/introduction.md Attempts to log in a user using a provided one-time password. It checks the validity of the password against the user's session, considering factors like IP address and user agent. Upon successful login, it regenerates the session ID and redirects the user. ```php use Spatie\OneTimePasswords\Enums\ConsumeOneTimePasswordResult; $result = $user->attemptLoginUsingOneTimePassword($oneTimePassword); if ($result->isOk()) { // it is best practice to regenerate the session id after a login $request->session()->regenerate(); return redirect()->intended('dashboard'); } return back()->withErrors([ 'one_time_password' => $result->validationMessage(), ])->onlyInput('one_time_password'); ``` -------------------------------- ### Route Notification for Vonage Channel Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/configuring-notifications.md This PHP code snippet shows how to implement the `routeNotificationForVonage` method in a Laravel `User` model. This method is crucial for routing notifications to the Vonage channel by returning the user's phone number, enabling SMS delivery. ```php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; class User extends Authenticatable { use Notifiable; /** * Route notifications for the Vonage channel. */ public function routeNotificationForVonage(Notification $notification): string { return $this->phone_number; } } ``` -------------------------------- ### Create Custom Alphanumeric Password Generator Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/configuring-security/configuring-password-format.md This PHP code defines a custom password generator class that extends the base `OneTimePasswordGenerator` from the spatie/laravel-one-time-passwords package. It generates a 6-character alphanumeric password using the `fake()->text()` method. This allows for greater flexibility in password complexity. ```php namespace App\Support; use Spatie\OneTimePasswords\Support\PasswordGenerators\OneTimePasswordGenerator; class AlphanumericPasswordGenerator implements OneTimePasswordGenerator { public function generate(): string { return fake()->text($this->numberOfCharacters) } } ``` -------------------------------- ### Attempt Login with One-Time Password Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/consuming-one-time-passwords.md Verifies a one-time password and logs in the user if correct. It returns a `ConsumeOneTimePasswordResult` enum. If successful, it regenerates the session and redirects. If incorrect, it shows a validation error. ```php use Spatie\OneTimePasswords\Enums\ConsumeOneTimePasswordResult; // $result is an instance of the ConsumeOneTimePasswordResult enum. $result = $user->attemptLoginUsingOneTimePassword($oneTimePassword, remember: false); if ($result->isOk()) { // it is best practice to regenerate the session id after a login $request->session()->regenerate(); return redirect()->intended('dashboard'); } return back()->withErrors([ 'one_time_password' => $result->validationMessage(), ])->onlyInput('one_time_password'); ``` -------------------------------- ### OriginEnforcer Interface Definition Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/configuring-security/enforcing-origin.md Defines the interface for custom origin enforcement. Implement this to create your own logic for verifying request origins. It requires methods to gather request properties and verify them against stored one-time password properties. ```php use Illuminate\Http\Request; use Spatie\OneTimePasswords\Models\OneTimePassword; interface OriginEnforcer { /** @return array */ public function gatherProperties(Request $request): array; public function verifyProperties(OneTimePassword $oneTimePassword, Request $request): bool; } ``` -------------------------------- ### Register Custom Create One-Time Password Action Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/avanced-usage/customizing-actions.md This snippet shows how to register a custom action class in the `config/one-time-passwords.php` configuration file. By updating the 'actions' array with the fully qualified class name of your custom action, you can override the default behavior for creating one-time passwords. ```php // config/one-time-passwords.php return [ // ... 'actions' => [ 'create_one_time_password' => App\Actions\CustomCreateOneTimePasswordAction::class, ], ]; ``` -------------------------------- ### Configure Custom Password Generator in Laravel Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/configuring-security/configuring-password-format.md This PHP configuration snippet shows how to register a custom password generator class within the Laravel application's configuration. By setting the `password_generator` key in the `config/one-time-passwords.php` file to the fully qualified class name of your custom generator, the package will use it for generating one-time passwords. ```php // config/one-time-passwords.php return [ // ... 'password_generator' => App\Support\AlphanumericPasswordGenerator::class, ]; ``` -------------------------------- ### Configure Custom Notification Class Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/configuring-notifications.md This PHP configuration snippet updates the `config/one-time-passwords.php` file to specify a custom notification class. By setting the 'notification' key to `App\Notifications\CustomOneTimePasswordNotification::class`, the package will use your extended notification for sending one-time passwords. ```php // config/one-time passwords.php return [ // ... 'notification' => => App\Notifications\CustomOneTimePasswordNotification::class ]; ``` -------------------------------- ### Enable Multiple Passwords Configuration Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/configuring-security/allowing-multiple-passwords.md This configuration snippet demonstrates how to enable the functionality for users to have multiple one-time passwords. It involves modifying the package's configuration file to set the `allow_multiple_passwords` option to `true`. This change prevents the automatic deletion of previously generated one-time passwords when a new one is created. ```PHP config(['one-time-passwords.allow_multiple_passwords' => true]); ``` -------------------------------- ### Disable Origin Enforcement Configuration Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/configuring-security/enforcing-origin.md Shows how to disable origin enforcement by setting the 'origin_enforcer' configuration option to a class that does not enforce any origin checks. This is done in the `config/one-time-passwords.php` file. ```php // config/one-time-passwords.php return [ // ... 'origin_enforcer' => Spatie\OneTimePasswords\Support\OriginInspector\DoNotEnforceOrigin::class, ]; ``` -------------------------------- ### Consume One-Time Password Source: https://github.com/spatie/laravel-one-time-passwords/blob/main/docs/basic-usage/consuming-one-time-passwords.md Verifies a one-time password without logging the user in. It returns a `ConsumeOneTimePasswordResult` enum indicating success or failure reasons like incorrect password, expired, or rate limit exceeded. ```php $result = $user->consumeOneTimePassword($oneTimePassword); ```