Search by

anjan011 / 2fa-support

anjan011

A Laravel package for TOTP-based 2FA with QR image and backup codes.

v1.0.1 2026-11-16 07:38 UTC

This package is auto-updated.

Last update: 2026-11-16 07:39:05 UTC


README

A Laravel package for TOTP-based 2FA with QR image and backup codes support.

Installation

You can install the package via composer:

composer require anjan011/2fa-support

The package will automatically register itself.

Configuration

You can publish the config file with:

php artisan vendor:publish --tag="2fa-support-config"

The config file will be located at config/anjan011/2fa-support.php.

Available options:

  • enable_totp_2fa: Enable or disable the 2FA system globally.
  • route_prefix: The prefix for the package API routes.
  • backup_codes_count: The number of backup codes to generate.
  • google_authenticator_app_text: The text that will appear on the Google Authenticator app when scanning the QR code (default: 2FA Support).
  • middlewares: The middlewares to apply to the package API routes (default: ['api', 'auth:sanctum']).

Setup

The package uses a separate polymorphic table two_fa_data to store 2FA settings. This means it can be used with any model (e.g., User, Supplier, etc.).

Using the Trait (Optional)

You can add the HasTwoFASupport trait to your model to easily access the relationship:

use Anjan011\TwoFASupport\Traits\HasTwoFASupport;

class User extends Authenticatable
{
    use HasTwoFASupport;
}

This will provide a twoFaData relationship.

Using the Manager

All 2FA related features are provided through the TwoFactorSupportManager class.

use Anjan011\TwoFASupport\TwoFactorSupportManager;

public function __construct(protected TwoFactorSupportManager $twoFactorSupportManager) {}

// Example: check if 2FA is enabled for a user
$isEnabled = $this->twoFactorSupportManager->isEnabledFor($user);

Run the migrations:

php artisan migrate

Supporting Multiple Entities (e.g., Admins)

The package is designed to support multiple models simultaneously (e.g., User and Admin) using polymorphic relationships.

1. Model Setup

Apply the HasTwoFASupport trait to your additional models:

namespace App\Models;

use Anjan011\TwoFASupport\Traits\HasTwoFASupport;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use HasTwoFASupport;
}

2. Laravel Auth Configuration

Configure a provider and guard for your new model in config/auth.php:

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

3. Package Middleware Configuration

Update config/anjan011/2fa-support.php to include your new guard. Laravel will allow the request if either guard succeeds:

'middlewares' => ['api', 'auth:sanctum,admin'],

4. Implementation Example (Programmatic)

If you are building a custom admin panel and want to use the TwoFactorSupportManager directly for an Admin model:

use Anjan011\TwoFASupport\TwoFactorSupportManager;
use App\Models\Admin;

class Admin2FAController extends Controller
{
    public function __construct(protected TwoFactorSupportManager $twoFaManager) {}

    /**
     * Step 1: Prepare 2FA Setup
     */
    public function setup(Admin $admin)
    {
        $secret = $this->twoFaManager->generateSecret();
        $qrCodeSvg = $this->twoFaManager->getQrCodeSvg(
            $this->twoFaManager->getIssuerName(),
            $admin->email,
            $secret
        );

        return view('admin.2fa.setup', compact('secret', 'qrCodeSvg'));
    }

    /**
     * Step 2: Enable 2FA
     */
    public function enable(Admin $admin, Request $request)
    {
        $secret = $request->input('secret');
        $code = $request->input('code');

        // Use the Google2FA Facade to verify the code against the secret
        // before officially enabling it in the database.
        if (\PragmaRX\Google2FALaravel\Facade::verifyKey($secret, $code)) {
            $backupCodes = $this->twoFaManager->generateBackupCodes();
            $this->twoFaManager->enableFor($admin, $secret, $backupCodes);

            return back()->with('backup_codes', $backupCodes);
        }

        return back()->withErrors(['code' => 'Invalid TOTP code']);
    }

    /**
     * Step 3: Validate TOTP or Backup Code
     */
    public function validate(Admin $admin, string $code)
    {
        // verifyCode automatically checks both TOTP and Backup Codes
        $isValid = $this->twoFaManager->verifyCode($admin, $code);
        
        return $isValid ? 'Success' : 'Invalid Code';
    }

    /**
     * Step 4: Disable 2FA
     */
    public function disable(Admin $admin)
    {
        $this->twoFaManager->disableFor($admin);
        
        return back()->with('status', '2FA Disabled');
    }
}

API Endpoints

General Requirements

  • Authentication: All endpoints require an authenticated user. The middleware used is configurable via the middlewares option in the config file (defaults to ['api', 'auth:sanctum']).
  • Data Format: All requests and responses use JSON format.
  • Headers:
    • Accept: application/json: Required for all requests.
    • Content-Type: application/json: Required for POST requests.
    • X-CSRF-TOKEN: Required if using session-based authentication (Web).
    • Authorization: Bearer <token>: Required if using token-based authentication (API).
  • Rate Limiting: By default, the package routes use the api middleware group which includes Laravel's default rate limiting (e.g., throttle:api). You can customize this by changing the middlewares in the configuration.

1. Setup 2FA

Used to initiate the 2FA setup process. It generates a temporary secret and a QR code.

  • URL: GET /anjan011/2fa-support/setup
  • Response: 200 OK
    {
      "secret": "JBSWY3DPEHPK3PXP",
      "qr_code_svg": "<svg>...</svg>"
    }

2. Enable 2FA

Used to confirm and enable 2FA for the user. Requires the secret generated in the setup step and a valid TOTP code from the authenticator app.

  • URL: POST /anjan011/2fa-support/enable
  • Body:
    {
      "secret": "JBSWY3DPEHPK3PXP",
      "code": "123456"
    }
  • Response: 200 OK
    {
      "message": "2FA enabled successfully.",
      "backup_codes": ["code1", "code2", ...]
    }
  • Errors:
    • 422 Unprocessable Entity: Invalid TOTP code or missing parameters.
    • 403 Forbidden: 2FA is disabled globally.

3. Disable 2FA

Used to disable 2FA for the authenticated user.

  • URL: POST /anjan011/2fa-support/disable
  • Response: 200 OK
    {
      "message": "2FA disabled successfully."
    }

4. Regenerate Backup Codes

Used to regenerate a new set of backup codes. This will invalidate all previous backup codes.

  • URL: GET /anjan011/2fa-support/backup-codes
  • Response: 200 OK
    {
      "backup_codes": ["newcode1", "newcode2", ...]
    }
  • Errors:
    • 403 Forbidden: 2FA is not enabled for the user.

5. Validate TOTP/Backup Code

Used to validate a code (TOTP or Backup Code) for the authenticated user.

  • URL: POST /anjan011/2fa-support/validate
  • Body:
    {
      "code": "123456"
    }
  • Response: 200 OK
    {
      "valid": true
    }
  • Errors:
    • 422 Unprocessable Entity: Invalid code.
      {
        "valid": false,
        "message": "Invalid code."
      }
    • 403 Forbidden: 2FA is not enabled for the user.

Testing

The package includes a comprehensive test suite covering unit tests for the manager and trait, as well as feature tests for all API endpoints and polymorphic support.

You can run the tests using the provided Artisan command:

php artisan anjan011-2fa-support:test

This command will execute all package tests and display each test case name for clear visibility of what is being verified.

Manual Testing

If you want to run the tests using PHPUnit directly, you can use:

vendor/bin/phpunit tests/Feature/TwoFATest.php
vendor/bin/phpunit tests/Unit/TwoFactorSupportManagerTest.php