A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache.

Related tags

Laravel laravel-otp
Overview

Laravel OTP

Latest Version on Packagist Software License Total Downloads

Introduction

A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache. The cache connection same as your laravel cache config and it supported: "apc", "array", "database", "file", "memcached", "redis"

Installation

Install via composer

composer require teckwei1993/laravel-otp

Add Service Provider & Facade

For Laravel 5.5+

Once the package is added, the service provider and facade will be auto discovered.

For Older versions of Laravel

Add the ServiceProvider to the providers array in config/app.php:

Teckwei1993\Otp\OtpServiceProvider::class

Add the Facade to the aliases array in config/app.php:

'Otp' => Teckwei1993\Otp\OtpFacade::class

Configuration

Publish config and language file

php artisan vendor:publish --provider="Teckwei1993\Otp\OtpServiceProvider"

This package publishes an otp.php file inside your applications's config folder which contains the settings for this package. Most of the variables are bound to environment variables, you may add Key-Value pair to the .env file in the Laravel application.

OTP_FORMAT=numeric
OTP_LENGTH=6
OTP_SENSITIVE=false
OTP_EXPIRES_TIME=15
OTP_ATTEMPT_TIMES=5
OTP_REPEATED=true
OTP_DEMO=false

Usage

Generate OTP

Otp::generate(string $identifier)
  • $identifier: The identity that will be tied to the OTP.

Sample

use OTP;

// in controller

$password = Otp::generate('reg:[email protected]');

This will generate a OTP that will be valid for 15 minutes.

Validate OTP

Otp::validate(string $identifier, string $password)
  • $identifier: The identity that is tied to the OTP.
  • $password: The password tied to the identity.

Sample

use OTP;

// in controller

$result = Otp::validate('reg:[email protected]', '123456');

Responses

On Success

{
  "status": true
}

Invalid OTP

{
  "status": false,
  "error": "invalid"
}

Expired

{
  "status": false,
  "error": "expired"
}

Max attempt

{
  "status": false,
  "error": "max_attempt"
}
  • Reached the maximum allowed attempts, default 10 times with each identifier

Validate OTP by Laravel Validation

// in a `FormRequest`

use Teckwei1993\Otp\Rules\OtpValidate;

public function rules()
{
    return [
        'code' => ['required', new OtpValidate('change-email:[email protected]')]
    ];
}

// in a controller

$request->validate([
    'code' => ['required', new OtpValidate('change-email:[email protected]')]
]);

Validate OTP by session id

// Otp class

$result = Otp::validate('123456');

// in a `FormRequest`

use Teckwei1993\Otp\Rules\OtpValidate;

public function rules()
{
    return [
        'code' => ['required', new OtpValidate()]
    ];
}

// in a controller

$request->validate([
    'code' => ['required', new OtpValidate()]
]);
  • The setting without identifier will automatically use the session ID as the default, and the OTP generation and verification will be completed in same session (browser's cookies).

Advanced Usage

Generate OTP with options

$password = Otp::setLength(8)->setFormat('string')->setExpires(60)->setRepeated(false)->generate('identifier-key-here');

// or array option

$password = Otp::generate('identifier-key-here', [
    'length' => 8,
    'format' => 'string',
    'expires' => 60,
    'repeated' => false
]);
  • setLength($length): The length of the password. Default: 6
  • setFormat($format): The format option allows you to decide which generator implementation to be used when generating new passwords. Options: 'string','numeric','numeric-no-zero','customize'. Default: "numeric"
  • setExpires($minutes): The expiry time of the password in minutes. Default: 15
  • setRepeated($boolean): The repeated of the password. The previous password is valid when new password generated until either one password used or itself expired. Default: true

Generate OTP with customize password

$password = Otp::setCustomize('12345678ABC@#$')->generate('identifier-key-here');
  • setCustomize($string): Random letter from the customize string

Validate OTP with specific attempt times

$password = Otp::setAttempts(3)->validate('identifier-key-here', 'password-here');
  • setAttempts($times): The number of incorrect password attempts. Default: 5

Validate OTP with case sensitive

$password = Otp::setSensitive(true)->generate('identifier-key-here');

// validate

$result = Otp::setSensitive(true)->validate('identifier-key-here', 'password-here');

// in controller

use Teckwei1993\Otp\Rules\OtpValidate;

$request->validate([
    'code' => ['required', new OtpValidate('identifier-key-here', ['sensitive' => true])]
]);
  • setSensitive($boolean): Requiring correct input of uppercase and lowercase letters. Default: true

Generate OTP with seperate password

$password = Otp::setLength([4,3,4])->setSeparator(':')->generate('identifier-key-here');

Sample password

3526:126:3697
  • setLength($array): The length of the password, use array to separate each length.
  • setSeparator($string): The separator of the password. Default: "-"

Validate OTP with extra data

$password = Otp::setData(['user_id' => auth()->id()])->generate('login-confirmation');
  • setData($var): Allows you to get the extra data of OTP.
// validate

$result = Otp::setDisposable(false)->validate('login-confirmation', 'password-here');

// in controller

use Teckwei1993\Otp\Rules\OtpValidate;

$request->validate([
    'code' => ['required', new OtpValidate('login-confirmation', ['disposable' => false])]
]);
  • setDisposable($boolean): The disposable of the Otp identifier, the different password is not valid when same identifier password used. Default: true

On Success Response

{
  "status": true,
  "data": [
    "user_id": 10
  ]
}
  • When you set disposable to false, you are able support different password with different extra data for different user in the same identifier key of the OTP.

Validate OTP with skip using

// validate

$result = Otp::setSkip(true)->validate('identifier-key-here', 'password-here');

// in controller

use Teckwei1993\Otp\Rules\OtpValidate;

$request->validate([
    'code' => ['required', new OtpValidate('identifier-key-here', ['skip' => true])]
]);
  • setSkip($boolean): Skip using the password when validate, which means you can reuse the password again. Default: false
  • When there is an error response to the form request, it will skip using the password, but remember to OTP::validate(...) in controller.

Delete OTP

Otp::forget('identifier-key-here');
  • Delete all password with this specific identifier

Delete specific password

Otp::forget('identifier-key-here', 'password-here');

Reset attempt times

Otp::resetAttempt('identifier-key-here');

Demo password

Add the following Key-Value pair to the .env file in the Laravel application.

OTP_DEMO=true
  • Demo mode for development purposes, no need to use real password to validate.
  • Default demo password: "1234", "123456", "12345678"

Contribution

All contributions are welcome! 😄

License

The MIT License (MIT).

You might also like...
Laravel package to create autonumber for Eloquent model

Laravel AutoNumber Laravel package to create autonumber for Eloquent model Installation You can install the package via composer: composer require gid

Websockets for Laravel. Done right.
Websockets for Laravel. Done right.

Bring the power of WebSockets to your Laravel application. Drop-in Pusher replacement, SSL support, Laravel Echo support and a debug dashboard are just some of its features.

This package provides a trait that will generate a unique uuid when saving any Eloquent model.

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique uuid when saving any Eloquent model. $model = new

A kernel designed to run one and only one application in a virtualized environment
A kernel designed to run one and only one application in a virtualized environment

nanos Nanos is a new kernel designed to run one and only one application in a virtualized environment. It has several constraints on it compared to a

Laravel-model-mapper - Map your model attributes to class properties with ease.
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

One-to-one plugin for editing world chat messages.

WorldChat One-to-one plugin for editing world chat messages. Supports English and Turkish language To set a new world chat format /worldchat new "worl

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

A DynamoDB based Eloquent model and Query builder for Laravel.

Laravel DynamoDB A DynamoDB based Eloquent model and Query builder for Laravel. You can find an example implementation in kitar/simplechat. Motivation

Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Releases(v1.0.9)
Owner
Lim Teck Wei
Lim Teck Wei
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

Munaf Aqeel Mahdi 1.7k Jan 5, 2023
This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

Jonas Staudenmeir 5 Jan 6, 2023
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.

Laravel Verify New Email Laravel supports verifying email addresses out of the box. This package adds support for verifying new email addresses. When

Protone Media 300 Dec 30, 2022
Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Rubik 4 May 12, 2022
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023