graxmonzo/laravel-one-time-password

One time password (OTP) generation trait for Laravel

1.1.1 2021-01-19 15:15 UTC

This package is auto-updated.

Last update: 2024-04-21 10:18:45 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Laravel implementation of Rails's active_model_otp package.

Simple OTP generation.

$code = $user->otp(); // => "324650"
$user->verify($code); // => true
$user->verify($code); // => false

Installation

You can install the package via composer:

composer require graxmonzo/laravel-one-time-password

Usage

Your Eloquent models should use the GraxMonzo\OneTimePassWord\HasOTP trait and the GraxMonzo\OneTimePassWord\OTPOptions class.

The trait contains an abstract method otpOptions() that you must implement yourself.

Your models' migrations should have a fields to save the OTP secret and counter to.

Here's an example of how to implement the trait:

namespace App;

use GraxMonzo\OneTimePassword\HasOTP;
use GraxMonzo\OneTimePassword\OTPOptions;
use Illuminate\Database\Eloquent\Model;

class YourEloquentModel extends Model
{
    use HasOTP;

    /**
     * Get the options for generating OTP.
     */
    public function otpOptions() : OTPOptions
    {
        return OTPOptions::create()
            ->saveToFields('otp_secret', 'otp_counter')
            ->digitsCount(6); // optional
    }
}

With its migration:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateYourEloquentModelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('your_eloquent_models', function (Blueprint $table) {
            $table->increments('id');
            $table->string('otp_secret');
            $table->integer('otp_counter');
            $table->timestamps();
        });
    }
}

Get code

$model = new YourEloquentModel();

$model->otp(); # => "186522"
$code = $model->otp(); # => "850738"

Verify code

$model->verify($code); # => true
$model->verify($code); # => false

Verify code with counter adjust

$model->verify($code); # => true
$model->otp_counter -= 1;
$model->verify($code); # => true

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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