Coder Social home page Coder Social logo

laravel-otp's Introduction

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 Laravel 5.2 / 5.3 / 5.4

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).

If you enjoy this, please consider supporting me:

Buy Me A Coffee

laravel-otp's People

Contributors

teckwei1993 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

laravel-otp's Issues

Support for laravel 10

Is your feature request related to a problem? Please describe.
When i try to upgrade to laravel 10 composer complaints about illuminate/support

Describe the solution you'd like

This should fix the issue

"illuminate/support": "^5.2|^6.0|^7.0|^8.0|^9.0|^10.0"

Cache expires too early

I'm using the latest Laravel release (10.45.1) and the latests version of this package.

I received complaints from my users that the otp code is not valid even when they enter the exact code that they received.
After investigating, I found that the otp request data can't be found in the cache after 45 seconds. Without data, the code is invalid.

By default, the cache is valid for 15 minutes but when the otp data are stored in the cache, the data are only stored for 45 seconds because app()->version() >= "5.8" is not true anymore.

private function writeData(string $key, $value)
    {
        $expires = $this->expires;
        if(app()->version() >= "5.8"){
            $expires *= 60;
        }
        return Cache::put($this->prefix.$key, $value, $expires*3);
    }

This was introduced 3 years ago in version 1.0.5 to support older version of Laravel.
I think that now, it is safe to remove support for those version and come back to

private function writeData(string $key, $value)
    {
        return Cache::put($this->prefix.$key, $value, $this->expires*60*3);
    }

or use the opposite logic to support older version ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.