itsmeabde/easy-otp

Easy OTP (Onetime Password) for Laravel 7|8

v1.0.0 2021-10-18 11:52 UTC

This package is auto-updated.

Last update: 2024-05-18 17:51:59 UTC


README

Easy OTP is laravel package for create simple onetime password system

Latest Version on Packagist Software License Total Downloads

Support Laravel Version 7|8

Install

Via composer

$ composer require itsmeabde/easy-otp

Finally, you will want to publish the config using the following command:

$ php artisan vendor:publish --tag=otp
$ php artisan migrate

Usage

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Itsmeabde\EasyOtp\Exceptions\OtpException;
use Itsmeabde\EasyOtp\Otp;

class OtpController extends Controller
{
    public $otp;

    public function __construct(Otp $otp)
    {
        $this->otp = $otp;
    }

    public function create(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|min:3|max:100',
            'email' => 'required|email'
        ]);

        $identifier = sha1($request->input('email'));

        [$identifier, $pin, $expiresIn] = $this->otp->generate(
            $identifier,
            function ($identifier, $pin, $expiresIn) {
                // Send notification to users
            });

        return response()->json(
            compact('identifier', 'expiresIn')
        );
    }

    public function verify(Request $request): JsonResponse
    {
        $request->validate([
            'identifier' => 'required|string',
            'pin' => 'required|numeric'
        ]);

        try {
            $this->otp->validate(
                $request->input('identifier'),
                $request->input('pin'),
                function ($identifier) {
                    // Send notification to users
                });
        } catch (OtpException $e) {
            throw ValidationException::withMessages(
                $e->getMessageBag()
            );
        }

        return response()->json([
            'message' => 'Successfully verified.'
        ]);
    }

    public function resend(Request $request): JsonResponse
    {
        $request->validate(['identifier' => 'required|string']);

        try {
            [$identifier, $pin, $expiresIn] = $this->otp->generate(
                $request->input('identifier'),
                function ($identifier, $pin, $expiresIn) {
                    // Resend notification to users
                }, $requestExtraTime = true);
        } catch (OtpException $e) {
            throw ValidationException::withMessages(
                $e->getMessageBag()
            );
        }

        return response()->json([
            'message' => 'Successfully resend.',
        ]);
    }
}

License

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