├── .github └── workflows │ ├── ai.yml │ ├── run-tests.yml │ └── static-analysis.yml ├── .gitignore ├── .styleci.yml ├── Dockerfile ├── LICENSE ├── README.md ├── assets └── header.png ├── changelog.md ├── composer.json ├── config └── otp.php ├── contributing.md ├── docker-compose.yml ├── lang ├── en │ └── otp.php └── fa │ └── otp.php ├── phpstan-baseline.neon ├── phpstan.neon.dist ├── phpunit.xml.dist ├── src ├── Contracts │ ├── MobileValidatorInterface.php │ └── OtpTypeInterface.php ├── Dto │ ├── OtpDto.php │ └── SentOtpDto.php ├── Events │ └── OtpPrepared.php ├── Facade │ └── OtpManager.php ├── Middleware │ └── OtpRateLimiter.php ├── OtpManager.php ├── OtpManagerServiceProvider.php └── Validators │ └── DefaultMobileValidator.php └── tests ├── Enums └── MyOtpEnum.php ├── FacadeOtpManagerTest.php ├── OtpDtoTest.php ├── OtpManagerTest.php ├── OtpRateLimiterTest.php ├── SentOtpDtoTest.php └── TestCase.php /.github/workflows/ai.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | types: [synchronize, reopened, labeled] 4 | 5 | jobs: 6 | describe: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | contents: write 10 | steps: 11 | - name: Checkout repository 12 | uses: actions/checkout@v4 13 | with: 14 | fetch-depth: 0 15 | 16 | - name: PR Auto Describe 17 | uses: salehhashemi1992/pr-auto-describe@main 18 | with: 19 | github-token: ${{ secrets.TOKEN }} 20 | openai-api-key: ${{ secrets.OPENAI_API_KEY }} 21 | openai-model: 'gpt-4' 22 | github-api-base-url: 'https://api.github.com' -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: "Run Tests" 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | os: [ubuntu-latest] 12 | php: [8.1, 8.2, 8.3] 13 | laravel: [9.*, 10.*, 11.*] 14 | dependency-version: [prefer-lowest, prefer-stable] 15 | include: 16 | - laravel: 11.* 17 | testbench: 9.* 18 | phpunit: 11.* 19 | 20 | - laravel: 10.* 21 | testbench: 8.* 22 | phpunit: 11.* 23 | 24 | - laravel: 9.* 25 | testbench: 7.* 26 | phpunit: 10.* 27 | 28 | exclude: 29 | - laravel: 11.* 30 | php: 8.1 31 | 32 | - laravel: 9.* 33 | php: 8.3 34 | 35 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 36 | 37 | steps: 38 | - name: Checkout code 39 | uses: actions/checkout@v4 40 | 41 | - name: Setup PHP 42 | uses: shivammathur/setup-php@v2 43 | with: 44 | php-version: ${{ matrix.php }} 45 | extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv 46 | coverage: xdebug 47 | 48 | - name: Install dependencies 49 | run: | 50 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "nesbot/carbon:>=2.62.1" --no-interaction --no-update 51 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 52 | 53 | - name: Execute tests with Coverage 54 | run: vendor/bin/phpunit --coverage-clover=coverage.xml 55 | 56 | - name: Upload coverage reports to Codecov 57 | uses: codecov/codecov-action@v3 58 | with: 59 | file: ./coverage.xml 60 | env: 61 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 62 | -------------------------------------------------------------------------------- /.github/workflows/static-analysis.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality Checks 2 | 3 | on: [push, pull_request] 4 | 5 | permissions: 6 | contents: read 7 | 8 | jobs: 9 | static-analysis: 10 | name: Static Code Analysis 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v4 15 | 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@v2 18 | with: 19 | php-version: '8.1' 20 | 21 | - name: Install dependencies 22 | run: composer update --prefer-dist --no-progress --no-suggest 23 | 24 | - name: Perform Style Check 25 | run: vendor/bin/pint --test 26 | 27 | - name: Perform PHPStan 28 | run: vendor/bin/phpstan analyse --error-format=github -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /vendor/ 3 | phpunit.xml 4 | .phpunit.result.cache 5 | phpstan.neon 6 | build 7 | composer.lock -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:8.1-fpm 2 | 3 | # Install dependencies 4 | RUN --mount=target=/var/lib/apt/lists,type=cache,sharing=locked \ 5 | --mount=target=/var/cache/apt,type=cache,sharing=locked \ 6 | rm -f /etc/apt/apt.conf.d/docker-clean \ 7 | && echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache \ 8 | && apt-get update \ 9 | && apt-get install -y --no-install-recommends git unzip 10 | 11 | # Install composer 12 | COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Saleh Hashemi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | # Laravel OTP Manager 4 | 5 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/salehhashemi/laravel-otp-manager.svg?style=flat-square)](https://packagist.org/packages/salehhashemi/laravel-otp-manager) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/salehhashemi/laravel-otp-manager.svg?style=flat-square)](https://packagist.org/packages/salehhashemi/laravel-otp-manager) 7 | [![GitHub Actions](https://img.shields.io/github/actions/workflow/status/salehhashemi1992/laravel-otp-manager/run-tests.yml?branch=main&label=tests)](https://github.com/salehhashemi1992/laravel-otp-manager/actions/workflows/run-tests.yml) 8 | [![GitHub Actions](https://img.shields.io/github/actions/workflow/status/salehhashemi1992/laravel-otp-manager/static-analysis.yml?branch=main&label=static-analysis)](https://github.com/salehhashemi1992/laravel-otp-manager/actions/workflows/static-analysis.yml) 9 | [![codecov](https://codecov.io/gh/salehhashemi1992/laravel-otp-manager/graph/badge.svg?token=EJB78FT27M)](https://codecov.io/gh/salehhashemi1992/laravel-otp-manager) 10 | [![PHPStan](https://img.shields.io/badge/PHPStan-level%208-brightgreen.svg?style=flat)](https://phpstan.org/) 11 | 12 | ![Header Image](./assets/header.png) 13 | 14 |
15 | 16 | The `OtpManager` class is responsible for sending and verifying one-time passwords (OTPs). It provides a comprehensive set of methods to generate, send, verify, and manage OTPs. It also integrates with Laravel cache system to throttle OTP sending and provides a layer of security by tracking OTP requests. 17 | 18 | ## Features 19 | * **Main Features** 20 | * Generate OTP codes 21 | * Send OTPs via mobile numbers 22 | * Resend OTPs with built-in throttling 23 | * Verify OTP codes 24 | * Track OTP requests 25 | * **Security** 26 | * Rate limiting of OTP generation attempts (`OtpRateLimiter` middleware) 27 | * Otp Invalidation after multiple failed verifications 28 | * Automatic deletion of OTP codes after successful verification 29 | * **Configuration** 30 | * Customize rate-limiting thresholds, max allowed attempts, and auto-delete 31 | * **Flexibility** 32 | * Supports multiple OTP types using enums 33 | * Customizable mobile number validation 34 | 35 | ## Requirements 36 | 37 | - `PHP: ^8.1` 38 | - `Laravel framework: ^9` 39 | 40 | | Version | L9 | L10 | L11 | 41 | |---------|--------------------|--------------------|--------------------| 42 | | 1.5 | :white_check_mark: | :white_check_mark: | :white_check_mark: | 43 | 44 | ## Installation 45 | To install the package, you can run the following command: 46 | ```bash 47 | composer require salehhashemi/laravel-otp-manager 48 | ``` 49 | ## Usage 50 | 51 | ### Sending OTP 52 | ```php 53 | use Salehhashemi\OtpManager\Facade\OtpManager; 54 | 55 | $sentOtp = OtpManager::send("1234567890"); 56 | ``` 57 | ### Resending OTP 58 | The `sendAndRetryCheck` method will throw a `ValidationException` if you try to resend the OTP before the waiting time expires. 59 | ```php 60 | $sentOtp = OtpManager::sendAndRetryCheck("1234567890"); 61 | ``` 62 | ### Verifying OTP 63 | ```php 64 | $isVerified = OtpManager::verify("1234567890", 123456, "uuid-string"); 65 | ``` 66 | ### Deleting Verification Code 67 | ```php 68 | $isDeleted = OtpManager::deleteVerifyCode("1234567890"); 69 | ``` 70 | 71 | ## Handling and Listening to the `OtpPrepared` Event 72 | The `OtpManager` package emits an `OtpPrepared` event whenever a new OTP is generated. You can listen to this event and execute custom logic, such as sending the OTP via SMS or email. 73 | 74 | Here's how to set up an event listener: 75 | 76 | ### Step 1: Register the Event and Listener 77 | First, you need to register the `OtpPrepared` event and its corresponding listener. Open your `EventServiceProvider` file, usually located at `app/Providers/EventServiceProvider.php`, and add the event and listener to the $listen array. 78 | 79 | ```php 80 | protected $listen = [ 81 | \Salehhashemi\OtpManager\Events\OtpPrepared::class => [ 82 | \App\Listeners\SendOtpNotification::class, 83 | ], 84 | ]; 85 | ``` 86 | 87 | ### Step 2: Create the Listener 88 | If the listener does not exist, you can generate it using the following Artisan command: 89 | 90 | ```bash 91 | php artisan make:listener SendOtpNotification 92 | ``` 93 | 94 | ### Step 3: Implement the Listener 95 | Now open the generated `SendOtpNotification` listener file, typically located at `app/Listeners/`. You'll see a handle method, where you can add your custom logic for sending the OTP. 96 | 97 | Here's a sample implementation: 98 | ```php 99 | use Salehhashemi\OtpManager\Events\OtpPrepared; 100 | 101 | class SendOtpNotification 102 | { 103 | public function handle(OtpPrepared $event) 104 | { 105 | $mobile = $event->mobile; 106 | $otpCode = $event->code; 107 | 108 | // Send the OTP code to the mobile number 109 | // You can use your preferred SMS service here. 110 | } 111 | } 112 | ``` 113 | 114 | ### Step 4: Test the Event Listener 115 | Once you've set up the listener, generate a new OTP through the `OtpManager` package to make sure the `OtpPrepared` event is being caught and the corresponding listener logic is being executed. 116 | 117 | That's it! You've successfully set up an event listener for the `OtpPrepared` event in the `OtpManager` package. 118 | 119 | ## Using Enums for OTP Types 120 | You can take advantage of enums to define your OTP types. Enums provide a more expressive way to manage different categories of OTPs. 121 | 122 | ### How to Define an OTP Enum 123 | ```php 124 | use Salehhashemi\OtpManager\Contracts\OtpTypeInterface; 125 | 126 | enum MyOtpEnum: string implements OtpTypeInterface 127 | { 128 | case SIGNUP = 'signup'; 129 | case RESET_PASSWORD = 'reset_password'; 130 | 131 | public function identifier(): string 132 | { 133 | return $this->value; 134 | } 135 | } 136 | ``` 137 | ### Usage 138 | After defining your enum, you can use it just like any other OTP type: 139 | ```php 140 | OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 141 | OtpManager::verify('1234567890', $otpCode, $trackingCode, MyOtpEnum::SIGNUP); 142 | ``` 143 | 144 | ## Configuration 145 | To publish the config file, run the following command: 146 | ```bash 147 | php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="config" 148 | ``` 149 | To publish the language files, run: 150 | ```bash 151 | php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="lang" 152 | ``` 153 | After publishing, make sure to clear the config cache to apply your changes: 154 | ```bash 155 | php artisan config:clear 156 | ``` 157 | Then, you can adjust the waiting_time, code_min, and code_max in the `config/otp.php` 158 | 159 | ## Middleware Protection 160 | The OtpManager package includes built-in middleware (OtpRateLimiter) to protect your application routes from excessive OTP requests. This helps prevent potential abuse. 161 | 162 | ### To apply the middleware: 163 | 164 | **Register the middleware:** Add `\Salehhashemi\OtpManager\Middleware\OtpRateLimiter::class` to the `middlewareAliases` array in your `app\Http\Kernel.php` file. 165 | 166 | **Assign the middleware to routes:** You can apply it to specific routes or route groups where you want to implement rate limiting. 167 | 168 | Example: 169 | 170 | ```php 171 | Route::middleware('otp-rate-limiter')->group(function () { 172 | // Routes that require OTP rate limiting go here 173 | }); 174 | ``` 175 | 176 | ## Custom Mobile Number Validation 177 | The package comes with a default mobile number validator, but you can easily use your own. 178 | 179 | Here's how you can do it: 180 | 181 | 1. Create a Custom Validator Class 182 | First, create a class that implements `MobileValidatorInterface`. This interface expects you to define a validate method. 183 | ```php 184 | use Salehhashemi\OtpManager\Contracts\MobileValidatorInterface; 185 | 186 | class CustomMobileValidator implements MobileValidatorInterface 187 | { 188 | public function validate(string $mobile): void 189 | { 190 | // Your validation logic here 191 | } 192 | } 193 | ``` 194 | 2. Update Configuration 195 | Next, open your OTP configuration file and update the `mobile_validation_class` option to use your custom validator class: 196 | ```php 197 | 'mobile_validation_class' => CustomMobileValidator::class, 198 | ``` 199 | 200 | ### Exceptions 201 | * `\InvalidArgumentException` will be thrown if the mobile number is empty. 202 | * `\Exception` will be thrown for general exceptions, like OTP generation failures. 203 | * `\Illuminate\Validation\ValidationException` will be thrown for throttle restrictions. 204 | * `\Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException` will be thrown for throttled requests. 205 | 206 | ## Docker Setup 207 | This project uses Docker for local development and testing. Make sure you have Docker and Docker Compose installed on your system before proceeding. 208 | 209 | ### Build the Docker images 210 | ```bash 211 | docker-compose build 212 | ``` 213 | 214 | ### Start the services 215 | ```bash 216 | docker-compose up -d 217 | ``` 218 | To access the PHP container, you can use: 219 | ```bash 220 | docker-compose exec php bash 221 | ``` 222 | 223 | ### Testing 224 | 225 | ```bash 226 | composer test 227 | ``` 228 | 229 | ### Changelog 230 | 231 | Please see [CHANGELOG](changelog.md) for more information what has changed recently. 232 | 233 | ## Contributing 234 | 235 | Please see [CONTRIBUTING](contributing.md) for details. 236 | 237 | ## Credits 238 | 239 | - [Saleh Hashemi](https://github.com/salehhashemi1992) 240 | - [All Contributors](../../contributors) 241 | 242 | ## License 243 | 244 | The MIT License (MIT). Please see [License File](license.md) for more information. 245 | -------------------------------------------------------------------------------- /assets/header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/salehhashemi1992/laravel-otp-manager/e631617a787a97b08dfb1329b93eb6692808bdf8/assets/header.png -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes will be documented in this file. 4 | 5 | ## v1.5.1 6 | - Incorrect OTP retry time calculation by @imahmood in #24 7 | 8 | ## v1.5.0 9 | - Laravel 11.x Support by @imahmood in #22 10 | - add laravel 11 support to the tests by @salehhashemi1992 in #23 11 | 12 | ## v1.4.3 13 | - add prefix for otp rate limiter middleware by @salehhashemi1992 in #19 14 | - otp invalidation after unsuccessful otp verification attempts by @salehhashemi1992 in #20 15 | - auto-delete the OTP code after successful verification by @salehhashemi1992 #21 16 | 17 | ## v1.4.0 18 | - implement otp rate limiter middleware by @salehhashemi1992 in #18 19 | 20 | ## v1.3.1 21 | - nullable type for default null value by @salehhashemi1992 in #17 22 | 23 | ## v1.3.0 24 | - Add pint and phpstan to ci steps by @salehhashemi1992 in #15 25 | - moved resources/lang directory to the root directory by @imahmood in #16 26 | 27 | ## v1.2.0 28 | - add codecov to ci steps by @salehhashemi1992 in #7 29 | - Generate coverage report by @salehhashemi1992 in #8 30 | - Add tests for OtpDto and SentOtpDto by @salehhashemi1992 in #9 31 | - update checkout version to 4 by @salehhashemi1992 in #10 32 | - Add ai pr describe to ci by @salehhashemi1992 in #11 33 | - fix phpstan config by @salehhashemi1992 in #12 34 | - Update phpstan level from 4 to 8 by @salehhashemi1992 in #13 35 | 36 | ## v1.1.3 37 | - add codecov to ci steps by @salehhashemi1992 in #7 38 | - Generate coverage report by @salehhashemi1992 in #8 39 | - Add tests for OtpDto and SentOtpDto by @salehhashemi1992 in #9 40 | - update checkout version to 4 by @salehhashemi1992 in #10 41 | - Add ai pr describe to ci by @salehhashemi1992 in #11 42 | - fix phpstan config by @salehhashemi1992 in #12 43 | 44 | ## v1.1.1 45 | - default 4 digits otp range 46 | 47 | ## v1.1.0 48 | - OtpManager facade implementation 49 | 50 | ## v1.0.0 51 | - make enum type nullable 52 | 53 | ## v0.9.8 54 | - enum type interface 55 | 56 | ## v0.9.5 57 | - mobile custom validator 58 | - bug fix 59 | 60 | ## v0.9.0 61 | - Initial version 62 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "salehhashemi/laravel-otp-manager", 3 | "description": "Laravel OTP manager\n\n", 4 | "license": "MIT", 5 | "authors": [ 6 | { 7 | "name": "Saleh Hashemi", 8 | "email": "salpars2004@gmail.com", 9 | "role": "Developer" 10 | } 11 | ], 12 | "homepage": "https://github.com/salehhashemi1992/laravel-otp-manager", 13 | "keywords": ["Laravel", "OTP", "Authentication", "Two-Factor", "SMS", "Security"], 14 | "type": "library", 15 | "require": { 16 | "php": "^8.1", 17 | "laravel/framework": "^9.0|^10.0|^11.0", 18 | "salehhashemi/laravel-configurable-cache": "^1.1" 19 | }, 20 | "require-dev": { 21 | "laravel/pint": "^1.8", 22 | "phpstan/phpstan": "^1.10", 23 | "phpunit/phpunit": "^9.0|^10.0|^11.0" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "Salehhashemi\\OtpManager\\": "src/" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "psr-4": { 32 | "Salehhashemi\\OtpManager\\Tests\\": "tests/" 33 | } 34 | }, 35 | "scripts": { 36 | "test": "vendor/bin/phpunit", 37 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 38 | "format": "vendor/bin/pint", 39 | "analyse": "vendor/bin/phpstan analyse" 40 | }, 41 | "config": { 42 | "sort-packages": true 43 | }, 44 | "extra": { 45 | "laravel": { 46 | "providers": [ 47 | "Salehhashemi\\OtpManager\\OtpManagerServiceProvider" 48 | ] 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /config/otp.php: -------------------------------------------------------------------------------- 1 | 120, 18 | 19 | /* 20 | |-------------------------------------------------------------------------- 21 | | OTP Code Range 22 | |-------------------------------------------------------------------------- 23 | | 24 | | These options define the minimum and maximum range for the generated 25 | | OTP codes. Adjust these values as per your security requirements. 26 | | 27 | */ 28 | 'code_min' => 1111, 29 | 'code_max' => 9999, 30 | 31 | /* 32 | |-------------------------------------------------------------------------- 33 | | Mobile Validation Class 34 | |-------------------------------------------------------------------------- 35 | | 36 | | This option defines the class responsible for validating mobile numbers. 37 | | If you want to use your own validation logic, you can create your 38 | | own class and replace the class name here. 39 | | 40 | */ 41 | 'mobile_validation_class' => DefaultMobileValidator::class, 42 | 43 | /* 44 | |-------------------------------------------------------------------------- 45 | | Rate Limiting Configurations 46 | |-------------------------------------------------------------------------- 47 | | 48 | | These options define the rate limiting configurations for the OTP 49 | | manager. Adjust these values as per your security requirements. 50 | | 51 | */ 52 | 'rate_limiting' => [ 53 | 'max_attempts' => 5, 54 | 'decay_minutes' => 1, 55 | ], 56 | 57 | /* 58 | |-------------------------------------------------------------------------- 59 | | Verification Attempt and Lockout Configurations 60 | |-------------------------------------------------------------------------- 61 | | 62 | | These options control how many failed verification attempts are allowed 63 | | before otp invalidation. 64 | | 65 | */ 66 | 'max_verify_attempts' => 5, 67 | ]; 68 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | php: 5 | build: ./ 6 | restart: unless-stopped 7 | init: true 8 | volumes: 9 | - .:/var/www/application 10 | working_dir: /var/www/application -------------------------------------------------------------------------------- /lang/en/otp.php: -------------------------------------------------------------------------------- 1 | 'Your verification attempts have exceeded the limit. Please request a new OTP to continue.', 5 | 'throttle' => 'Too many OTP attempts. Please try again in :seconds seconds.', 6 | ]; 7 | -------------------------------------------------------------------------------- /lang/fa/otp.php: -------------------------------------------------------------------------------- 1 | 'شما بیش از حد مجاز تلاش کرده اید. لطفا برای ادامه یک کد جدید درخواست کنید.', 5 | 'throttle' => 'درخواست بیش از حد مجاز! لطفا بعد از :seconds ثانیه دوباره امتحان کنید', 6 | ]; 7 | -------------------------------------------------------------------------------- /phpstan-baseline.neon: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/salehhashemi1992/laravel-otp-manager/e631617a787a97b08dfb1329b93eb6692808bdf8/phpstan-baseline.neon -------------------------------------------------------------------------------- /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - phpstan-baseline.neon 3 | 4 | parameters: 5 | level: 8 6 | paths: 7 | - src 8 | - config -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | ./tests 14 | 15 | 16 | 17 | 18 | 19 | src 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Contracts/MobileValidatorInterface.php: -------------------------------------------------------------------------------- 1 | code = $code; 16 | $this->trackingCode = $trackingCode; 17 | } 18 | 19 | /** 20 | * @return array 21 | */ 22 | public function toArray(): array 23 | { 24 | return [ 25 | 'code' => $this->code, 26 | 'tracking_code' => $this->trackingCode, 27 | ]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Dto/SentOtpDto.php: -------------------------------------------------------------------------------- 1 | code = $code; 18 | $this->waitingTime = $waitingTime; 19 | $this->trackingCode = $trackingCode; 20 | } 21 | 22 | /** 23 | * @return array 24 | */ 25 | public function toArray(): array 26 | { 27 | return [ 28 | 'code' => $this->code, 29 | 'tracking_code' => $this->trackingCode, 30 | 'waiting_time' => $this->waitingTime, 31 | ]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Events/OtpPrepared.php: -------------------------------------------------------------------------------- 1 | $params 18 | */ 19 | public function __construct( 20 | public readonly string $mobile, 21 | public readonly string $code, 22 | public readonly ?OtpTypeInterface $type, 23 | public string $trackingCode, 24 | public readonly array $params, 25 | ) {} 26 | } 27 | -------------------------------------------------------------------------------- /src/Facade/OtpManager.php: -------------------------------------------------------------------------------- 1 | ip().'|'.Str::slug($request->userAgent() ?? 'default', '|'); 17 | } 18 | 19 | $maxAttempts = config('otp.rate_limiting.max_attempts', 5); 20 | $decaySeconds = config('otp.rate_limiting.decay_minutes', 1) * 60; 21 | 22 | if (RateLimiter::tooManyAttempts($key, $maxAttempts)) { 23 | $seconds = RateLimiter::availableIn($key); 24 | 25 | throw new TooManyRequestsHttpException( 26 | $seconds, 27 | "Too Many Attempts. Please try again in $seconds seconds." 28 | ); 29 | } 30 | 31 | RateLimiter::hit($key, $decaySeconds); 32 | 33 | return $next($request); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/OtpManager.php: -------------------------------------------------------------------------------- 1 | waitingTime = config('otp.waiting_time'); 31 | 32 | $mobileValidationClass = config('otp.mobile_validation_class'); 33 | 34 | $this->mobileValidator = app()->make($mobileValidationClass); 35 | } 36 | 37 | /** 38 | * Send a new OTP. 39 | * 40 | * Generates a new OTP code, triggers an event, and returns the sent OTP details. 41 | * 42 | * @param string $mobile The mobile number to which the OTP should be sent. 43 | * @param \Salehhashemi\OtpManager\Contracts\OtpTypeInterface|null $type The type or category of OTP being sent (e.g., 'login', 'reset_password'). 44 | * @param array $params Additional parameters that can be passed to the OTP event. 45 | * @return \Salehhashemi\OtpManager\Dto\SentOtpDto An object containing details of the sent OTP. 46 | * 47 | * @throws \Exception If the OTP generation fails or any other exception occurs. 48 | */ 49 | public function send(string $mobile, ?OtpTypeInterface $type = null, array $params = []): SentOtpDto 50 | { 51 | $this->validateMobile($mobile); 52 | 53 | $this->type = $type; 54 | $this->trackingCode = Str::uuid()->toString(); 55 | 56 | $otp = new SentOtpDto($this->getNewCode($mobile), $this->waitingTime, $this->trackingCode); 57 | 58 | event(new OtpPrepared( 59 | mobile: $mobile, 60 | code: (string) $otp->code, 61 | type: $type, 62 | trackingCode: $otp->trackingCode, 63 | params: $params, 64 | )); 65 | 66 | return $otp; 67 | } 68 | 69 | /** 70 | * Resend OTP based on waiting time. 71 | * 72 | * Checks if the waiting time has passed since the last OTP was sent. 73 | * If so, resends the OTP to the given mobile number; otherwise, throws a ValidationException. 74 | * 75 | * @param string $mobile The mobile number to which the OTP should be resent. 76 | * @param \Salehhashemi\OtpManager\Contracts\OtpTypeInterface|null $type The type or category of OTP being sent (e.g., 'login', 'reset_password'). 77 | * @param array $params Additional parameters that can be passed to the OTP event. 78 | * @return \Salehhashemi\OtpManager\Dto\SentOtpDto An object containing details of the sent OTP. 79 | * 80 | * @throws \Exception If any other exception occurs. 81 | */ 82 | public function sendAndRetryCheck(string $mobile, ?OtpTypeInterface $type = null, array $params = []): SentOtpDto 83 | { 84 | $this->validateMobile($mobile); 85 | 86 | $this->type = $type; 87 | 88 | $created = $this->getSentAt($mobile, $type); 89 | if (! $created) { 90 | return $this->send($mobile, $type, $params); 91 | } 92 | 93 | $retryAfter = $created->addSeconds($this->waitingTime); 94 | if (Carbon::now()->greaterThan($retryAfter)) { 95 | return $this->send($mobile, $type, $params); 96 | } 97 | 98 | $remainingTime = (int) Carbon::now()->diffInSeconds($retryAfter); 99 | 100 | throw ValidationException::withMessages([ 101 | 'otp' => [ 102 | trans('otp-manager::otp.throttle', ['seconds' => $remainingTime]), 103 | ], 104 | ]); 105 | } 106 | 107 | /** 108 | * Verify the OTP code. 109 | * 110 | * Compares the provided OTP code and tracking code with the stored ones 111 | * for the given mobile number and OTP type. Returns true if they match. 112 | * 113 | * @param string $mobile The mobile number associated with the OTP. 114 | * @param int $otp The OTP code to verify. 115 | * @param string $trackingCode The tracking code associated with the OTP. 116 | * @param \Salehhashemi\OtpManager\Contracts\OtpTypeInterface|null $type The type or category of OTP (e.g., 117 | * 'login', 'reset_password'). 118 | * @return bool True if the provided OTP and tracking code match the stored ones, false otherwise. 119 | * 120 | * @throws \InvalidArgumentException If the Mobile string is empty 121 | */ 122 | public function verify(string $mobile, int $otp, string $trackingCode, ?OtpTypeInterface $type = null): bool 123 | { 124 | $this->validateMobile($mobile); 125 | 126 | $this->type = $type; 127 | $this->trackingCode = $trackingCode; 128 | 129 | $otpDto = $this->getVerifyCode($mobile, $type); 130 | 131 | if (! $otpDto || $otp !== $otpDto->code || $trackingCode !== $otpDto->trackingCode) { 132 | $this->handleVerificationAttempt($mobile); // Handle failed verification attempt 133 | 134 | return false; 135 | } 136 | 137 | $this->resetSendAttempts($mobile); // Reset on successful verification 138 | 139 | // Auto-delete the OTP code after successful verification 140 | $this->deleteVerifyCode($mobile, $type); 141 | 142 | return true; 143 | } 144 | 145 | /** 146 | * Handle a verification attempt for a given mobile number. 147 | * 148 | * @param string $mobile The mobile number to handle verification for. 149 | * 150 | * @throws ValidationException When the maximum verification attempts are exceeded. 151 | */ 152 | protected function handleVerificationAttempt(string $mobile): void 153 | { 154 | $attemptsKey = $this->getCacheKey($mobile, 'verify_attempts'); 155 | 156 | $maxAttempts = config('otp.max_verify_attempts', 3); 157 | 158 | $attempts = Cache::get($attemptsKey, 0) + 1; 159 | 160 | if ($attempts > $maxAttempts) { 161 | $this->deleteVerifyCode($mobile, $this->type); 162 | Cache::forget($attemptsKey); 163 | 164 | throw ValidationException::withMessages([ 165 | 'otp' => [__('otp-manager::otp.request_new')], 166 | ]); 167 | } 168 | 169 | Cache::put($attemptsKey, $attempts, $this->waitingTime); 170 | } 171 | 172 | /** 173 | * Resets the send attempts for a given mobile number by clearing the cache entries. 174 | * 175 | * @param string $mobile The mobile number for which send attempts are to be reset. 176 | */ 177 | protected function resetSendAttempts(string $mobile): void 178 | { 179 | $attemptsKey = $this->getCacheKey($mobile, 'verify_attempts'); 180 | 181 | Cache::forget($attemptsKey); 182 | } 183 | 184 | /** 185 | * Fetch the OTP code for verification. 186 | * 187 | * Retrieves the OTP code associated with the given mobile number and OTP type from the cache. 188 | * Returns null if the mobile number is empty or if no OTP code is found. 189 | * 190 | * @param string $mobile The mobile number associated with the OTP. 191 | * @param \Salehhashemi\OtpManager\Contracts\OtpTypeInterface|null $type The type or category of OTP (e.g., 'login', 'reset_password'). 192 | * @return \Salehhashemi\OtpManager\Dto\OtpDto|null An OtpDto object containing the OTP code and tracking code, or null if not found. 193 | */ 194 | public function getVerifyCode(string $mobile, ?OtpTypeInterface $type = null): ?OtpDto 195 | { 196 | $this->validateMobile($mobile); 197 | 198 | $this->type = $type; 199 | 200 | return ConfigurableCache::get($this->getCacheKey($mobile, 'value'), 'otp'); 201 | } 202 | 203 | /** 204 | * Delete the verification code for a mobile number. 205 | * 206 | * @throws \InvalidArgumentException If the Mobile string is empty 207 | */ 208 | public function deleteVerifyCode(string $mobile, ?OtpTypeInterface $type = null): bool 209 | { 210 | $this->validateMobile($mobile); 211 | 212 | $this->type = $type; 213 | 214 | return ConfigurableCache::delete($this->getCacheKey($mobile, 'value'), 'otp'); 215 | } 216 | 217 | /** 218 | * Retrieve the time when the OTP was sent to the user. 219 | * 220 | * @return \Illuminate\Support\Carbon|null A Carbon instance representing the time the OTP was sent, or null if not available. 221 | * 222 | * @throws \InvalidArgumentException If the Mobile string is empty 223 | */ 224 | public function getSentAt(string $mobile, ?OtpTypeInterface $type = null): ?Carbon 225 | { 226 | $this->validateMobile($mobile); 227 | 228 | $this->type = $type; 229 | 230 | if (empty($mobile)) { 231 | return null; 232 | } 233 | 234 | $created = ConfigurableCache::get($this->getCacheKey($mobile, 'created'), 'otp'); 235 | if (! $created) { 236 | return null; 237 | } 238 | 239 | return Carbon::createFromTimestamp($created); 240 | } 241 | 242 | /** 243 | * Check if a verification code has been sent to a specified mobile number. 244 | * 245 | * @return bool True if the verification code has been sent, false otherwise. 246 | * 247 | * @throws \InvalidArgumentException If the Mobile string is empty 248 | */ 249 | public function isVerifyCodeHasBeenSent(string $mobile, ?OtpTypeInterface $type = null): bool 250 | { 251 | $this->validateMobile($mobile); 252 | 253 | $this->type = $type; 254 | 255 | if (empty($mobile)) { 256 | return false; 257 | } 258 | 259 | return ConfigurableCache::get($this->getCacheKey($mobile, 'value'), 'otp') !== null; 260 | } 261 | 262 | /** 263 | * Generate a new OTP code within the configured range and store it in the cache. 264 | * 265 | * @throws \Exception If random number generation fails. 266 | * @throws \InvalidArgumentException If the Mobile string is empty 267 | */ 268 | protected function getNewCode(string $mobile): int 269 | { 270 | $this->validateMobile($mobile); 271 | 272 | $min = config('otp.code_min'); 273 | $max = config('otp.code_max'); 274 | 275 | $otp = random_int($min, $max); 276 | 277 | $otpDto = new OtpDto($otp, $this->trackingCode); 278 | 279 | ConfigurableCache::put($this->getCacheKey($mobile, 'value'), $otpDto, 'otp'); 280 | ConfigurableCache::put($this->getCacheKey($mobile, 'created'), time(), 'otp'); 281 | 282 | return $otp; 283 | } 284 | 285 | /** 286 | * Generate a cache key for storing or retrieving OTP-related information. 287 | * 288 | * This function constructs a cache key by combining the mobile number, 289 | * the intended usage ('for'), and the OTP type. The generated key is 290 | * used for caching OTP values and associated information. 291 | * 292 | * @param string $mobile The mobile number to which the OTP will be sent. 293 | * @param string $for Indicates the intended usage of the cache key (e.g., 'value', 'created'). 294 | * @return string The generated cache key. 295 | * 296 | * @throws \InvalidArgumentException If the Mobile string is empty 297 | */ 298 | protected function getCacheKey(string $mobile, string $for): string 299 | { 300 | return sprintf( 301 | 'otp_%s_%s_%s', 302 | $mobile, 303 | $for, 304 | $this->type?->identifier() 305 | ); 306 | } 307 | 308 | /** 309 | * Validates the provided mobile number. 310 | * 311 | * @throws \InvalidArgumentException 312 | */ 313 | protected function validateMobile(string $mobile): void 314 | { 315 | $this->mobileValidator->validate($mobile); 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /src/OtpManagerServiceProvider.php: -------------------------------------------------------------------------------- 1 | loadTranslationsFrom(__DIR__.'/../lang', 'otp-manager'); 15 | 16 | // Publishing the lang file. 17 | $this->publishes([ 18 | __DIR__.'/../lang' => $this->app->langPath('vendor/otp-manager'), 19 | ], 'lang'); 20 | 21 | // Publishing the configuration file. 22 | $this->publishes([ 23 | __DIR__.'/../config/otp.php' => config_path('otp.php'), 24 | ], 'config'); 25 | } 26 | 27 | /** 28 | * Register any package services. 29 | */ 30 | public function register(): void 31 | { 32 | $this->mergeConfigFrom(__DIR__.'/../config/otp.php', 'otp'); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Validators/DefaultMobileValidator.php: -------------------------------------------------------------------------------- 1 | value; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tests/FacadeOtpManagerTest.php: -------------------------------------------------------------------------------- 1 | assertNotNull($sentOtp); 31 | 32 | Event::assertDispatched(OtpPrepared::class, function ($event) use ($sentOtp) { 33 | return $event->code === (string) $sentOtp->code; 34 | }); 35 | } 36 | 37 | public function test_verify_function_verifies_otp() 38 | { 39 | $sentOtp = OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 40 | 41 | $isVerified = OtpManager::verify('1234567890', $sentOtp->code, $sentOtp->trackingCode, MyOtpEnum::SIGNUP); 42 | 43 | $this->assertTrue($isVerified); 44 | } 45 | 46 | public function test_verify_function_verifies_otp_without_type() 47 | { 48 | $sentOtp = OtpManager::send('1234567890'); 49 | 50 | $isVerified = OtpManager::verify('1234567890', $sentOtp->code, $sentOtp->trackingCode); 51 | 52 | $this->assertTrue($isVerified); 53 | } 54 | 55 | public function test_delete_function_deletes_otp() 56 | { 57 | OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 58 | 59 | OtpManager::deleteVerifyCode('1234567890', MyOtpEnum::SIGNUP); 60 | 61 | $isVerified = OtpManager::verify('1234567890', 123456, '123456', MyOtpEnum::SIGNUP); 62 | 63 | $this->assertFalse($isVerified); 64 | } 65 | 66 | public function test_send_function_fails_for_empty_mobile() 67 | { 68 | $this->expectException(\InvalidArgumentException::class); 69 | $this->expectExceptionMessage('Mobile number cannot be empty.'); 70 | 71 | OtpManager::send('', MyOtpEnum::SIGNUP); 72 | } 73 | 74 | public function test_verify_function_fails_for_wrong_code() 75 | { 76 | $sentOtp = OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 77 | 78 | $isVerified = OtpManager::verify('1234567890', 1, $sentOtp->trackingCode, MyOtpEnum::SIGNUP); 79 | 80 | $this->assertFalse($isVerified); 81 | } 82 | 83 | public function test_verify_function_fails_for_wrong_tracking_code() 84 | { 85 | $sentOtp = OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 86 | 87 | $isVerified = OtpManager::verify('1234567890', $sentOtp->code, 'wrongTrackingCode', MyOtpEnum::SIGNUP); 88 | 89 | $this->assertFalse($isVerified); 90 | } 91 | 92 | public function test_getSentAt_returns_correct_time() 93 | { 94 | OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 95 | 96 | $sentAt = OtpManager::getSentAt('1234567890', MyOtpEnum::SIGNUP); 97 | 98 | $this->assertInstanceOf(Carbon::class, $sentAt); 99 | } 100 | 101 | public function test_isVerifyCodeHasBeenSent_returns_true() 102 | { 103 | OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 104 | 105 | $isSent = OtpManager::isVerifyCodeHasBeenSent('1234567890', MyOtpEnum::SIGNUP); 106 | 107 | $this->assertTrue($isSent); 108 | } 109 | 110 | public function test_sendAndRetryCheck_throws_validation_exception_for_quick_retry() 111 | { 112 | OtpManager::send('1234567890', MyOtpEnum::SIGNUP); 113 | 114 | $this->expectException(ValidationException::class); 115 | 116 | OtpManager::sendAndRetryCheck('1234567890', MyOtpEnum::SIGNUP); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tests/OtpDtoTest.php: -------------------------------------------------------------------------------- 1 | assertSame($code, $otpDto->code); 17 | $this->assertSame($trackingCode, $otpDto->trackingCode); 18 | } 19 | 20 | public function test_toArray_returns_correct_array(): void 21 | { 22 | $code = 123456; 23 | $trackingCode = '550e8400-e29b-41d4-a716-446655440000'; 24 | 25 | $otpDto = new OtpDto($code, $trackingCode); 26 | 27 | $expectedArray = [ 28 | 'code' => $code, 29 | 'tracking_code' => $trackingCode, 30 | ]; 31 | 32 | $this->assertSame($expectedArray, $otpDto->toArray()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/OtpManagerTest.php: -------------------------------------------------------------------------------- 1 | send('1234567890', MyOtpEnum::SIGNUP); 30 | 31 | $this->assertNotNull($sentOtp); 32 | 33 | Event::assertDispatched(OtpPrepared::class, function ($event) use ($sentOtp) { 34 | return $event->code === (string) $sentOtp->code; 35 | }); 36 | } 37 | 38 | public function test_verify_function_verifies_otp() 39 | { 40 | $otpManager = new OtpManager; 41 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 42 | 43 | $isVerified = $otpManager->verify('1234567890', $sentOtp->code, $sentOtp->trackingCode, MyOtpEnum::SIGNUP); 44 | 45 | $this->assertTrue($isVerified); 46 | } 47 | 48 | public function test_verify_function_verifies_otp_without_type() 49 | { 50 | $otpManager = new OtpManager; 51 | $sentOtp = $otpManager->send('1234567890'); 52 | 53 | $isVerified = $otpManager->verify('1234567890', $sentOtp->code, $sentOtp->trackingCode); 54 | 55 | $this->assertTrue($isVerified); 56 | } 57 | 58 | public function test_delete_function_deletes_otp() 59 | { 60 | $otpManager = new OtpManager; 61 | $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 62 | 63 | $otpManager->deleteVerifyCode('1234567890', MyOtpEnum::SIGNUP); 64 | 65 | $isVerified = $otpManager->verify('1234567890', 123456, '123456', MyOtpEnum::SIGNUP); 66 | 67 | $this->assertFalse($isVerified); 68 | } 69 | 70 | public function test_send_function_fails_for_empty_mobile() 71 | { 72 | $this->expectException(\InvalidArgumentException::class); 73 | $this->expectExceptionMessage('Mobile number cannot be empty.'); 74 | 75 | $otpManager = new OtpManager; 76 | $otpManager->send('', MyOtpEnum::SIGNUP); 77 | } 78 | 79 | public function test_verify_function_fails_for_wrong_code() 80 | { 81 | $otpManager = new OtpManager; 82 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 83 | 84 | $isVerified = $otpManager->verify('1234567890', 1, $sentOtp->trackingCode, MyOtpEnum::SIGNUP); 85 | 86 | $this->assertFalse($isVerified); 87 | } 88 | 89 | public function test_verify_function_fails_for_wrong_tracking_code() 90 | { 91 | $otpManager = new OtpManager; 92 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 93 | 94 | $isVerified = $otpManager->verify('1234567890', $sentOtp->code, 'wrongTrackingCode', MyOtpEnum::SIGNUP); 95 | 96 | $this->assertFalse($isVerified); 97 | } 98 | 99 | public function test_getSentAt_returns_correct_time() 100 | { 101 | $otpManager = new OtpManager; 102 | $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 103 | 104 | $sentAt = $otpManager->getSentAt('1234567890', MyOtpEnum::SIGNUP); 105 | 106 | $this->assertInstanceOf(Carbon::class, $sentAt); 107 | } 108 | 109 | public function test_isVerifyCodeHasBeenSent_returns_true() 110 | { 111 | $otpManager = new OtpManager; 112 | $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 113 | 114 | $isSent = $otpManager->isVerifyCodeHasBeenSent('1234567890', MyOtpEnum::SIGNUP); 115 | 116 | $this->assertTrue($isSent); 117 | } 118 | 119 | public function test_sendAndRetryCheck_throws_validation_exception_for_quick_retry() 120 | { 121 | $otpManager = new OtpManager; 122 | $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 123 | 124 | $this->expectException(ValidationException::class); 125 | 126 | $otpManager->sendAndRetryCheck('1234567890', MyOtpEnum::SIGNUP); 127 | } 128 | 129 | public function test_verify_function_fails_after_exceeding_max_attempts_and_advises_new_otp_request() 130 | { 131 | $otpManager = new OtpManager; 132 | 133 | // Adjust the configuration for maximum verification attempts to 1 for the test. 134 | config(['otp.max_verify_attempts' => 1]); 135 | 136 | // Send OTP 137 | $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 138 | 139 | // First failed attempt 140 | $otpManager->verify('1234567890', 0, 'incorrect', MyOtpEnum::SIGNUP); 141 | 142 | // Second attempt should fail and advise for new OTP request 143 | try { 144 | $otpManager->verify('1234567890', 0, 'incorrectAgain', MyOtpEnum::SIGNUP); 145 | $this->fail('Expected ValidationException for exceeding max verification attempts was not thrown.'); 146 | } catch (ValidationException $e) { 147 | $this->assertSame(__('otp-manager::otp.request_new'), $e->getMessage()); 148 | } 149 | 150 | // Ensure that a new OTP can be requested immediately after exceeding attempts 151 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 152 | $this->assertNotNull($sentOtp, 'Failed to send a new OTP after exceeding maximum verification attempts.'); 153 | 154 | try { 155 | $otpManager->sendAndRetryCheck('1234567890', MyOtpEnum::SIGNUP); 156 | $this->fail('Expected ValidationException for throttle.'); 157 | } catch (ValidationException) { 158 | // true 159 | } 160 | } 161 | 162 | public function test_attempts_reset_after_successful_verification() 163 | { 164 | $otpManager = new OtpManager; 165 | config(['otp.max_verify_attempts' => 2]); 166 | 167 | // Send and verify OTP successfully 168 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 169 | $isVerified = $otpManager->verify('1234567890', $sentOtp->code, $sentOtp->trackingCode, MyOtpEnum::SIGNUP); 170 | 171 | $this->assertTrue($isVerified); 172 | 173 | // Ensure that after successful verification, we can attempt to verify again without instant failure 174 | $sentOtp = $otpManager->send('1234567890', MyOtpEnum::SIGNUP); 175 | $isVerifiedAgain = $otpManager->verify('1234567890', $sentOtp->code, 'incorrectCode', MyOtpEnum::SIGNUP); 176 | 177 | $this->assertFalse($isVerifiedAgain); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /tests/OtpRateLimiterTest.php: -------------------------------------------------------------------------------- 1 | 3]); 24 | 25 | $request = Request::create('/', 'GET', ['REMOTE_ADDR' => '127.0.0.1']); 26 | 27 | $middleware = new OtpRateLimiter; 28 | 29 | $this->expectException(TooManyRequestsHttpException::class); 30 | 31 | // Trigger middleware multiple times to exceed the limit 32 | for ($i = 0; $i < 5; $i++) { 33 | $response = $middleware->handle($request, function () {}); 34 | } 35 | } 36 | 37 | public function test_middleware_does_not_block_requests_below_limit() 38 | { 39 | config(['otp.rate_limiting.max_attempts' => 3]); 40 | 41 | $request = Request::create('/', 'GET', ['REMOTE_ADDR' => '127.0.0.1']); 42 | 43 | $middleware = new OtpRateLimiter; 44 | 45 | for ($i = 0; $i < 2; $i++) { 46 | $response = $middleware->handle($request, function () { 47 | return response('Passed', 200); 48 | }); 49 | } 50 | 51 | // Assert that the last response has the correct status code 52 | $this->assertEquals(200, $response->status()); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tests/SentOtpDtoTest.php: -------------------------------------------------------------------------------- 1 | getProperty('code'); 20 | $codeProperty->setAccessible(true); 21 | 22 | $waitingTimeProperty = $reflectionClass->getProperty('waitingTime'); 23 | $waitingTimeProperty->setAccessible(true); 24 | 25 | $trackingCodeProperty = $reflectionClass->getProperty('trackingCode'); 26 | $trackingCodeProperty->setAccessible(true); 27 | 28 | $this->assertSame($code, $codeProperty->getValue($sentOtpDto)); 29 | $this->assertSame($waitingTime, $waitingTimeProperty->getValue($sentOtpDto)); 30 | $this->assertSame($trackingCode, $trackingCodeProperty->getValue($sentOtpDto)); 31 | } 32 | 33 | public function test_toArray_returns_correct_array(): void 34 | { 35 | $code = 123456; 36 | $waitingTime = 60; 37 | $trackingCode = '550e8400-e29b-41d4-a716-446655440000'; 38 | 39 | $sentOtpDto = new SentOtpDto($code, $waitingTime, $trackingCode); 40 | 41 | $expectedArray = [ 42 | 'code' => $code, 43 | 'tracking_code' => $trackingCode, 44 | 'waiting_time' => $waitingTime, 45 | ]; 46 | 47 | $this->assertSame($expectedArray, $sentOtpDto->toArray()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 |