PHP code example of andydefer / laravel-totp
1. Go to this page and download the library: Download andydefer/laravel-totp library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
andydefer / laravel-totp example snippets
'providers' => [
// ...
AndyDefer\LaravelTotp\TotpServiceProvider::class,
],
// ✅ Le modèle User reste propre - AUCUNE RELATION !
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
// AUCUNE méthode totpSecret() ici !
}
use AndyDefer\LaravelTotp\Services\TotpService;
class TwoFactorController extends Controller
{
public function __construct(
private readonly TotpService $totpService,
) {}
public function setup(Request $request)
{
$user = $request->user();
$setup = $this->totpService->setup($user);
return response()->json([
'secret' => $setup['secret'],
'qr_code' => base64_encode($setup['qr_code']),
'qr_code_uri' => $setup['qr_code_uri'],
'recovery_codes' => $setup['recovery_codes'],
]);
}
}
public function enable(Request $request)
{
$user = $request->user();
$request->validate([
'code' => ' code: $request->code,
window: 1, // Tolérance de +/- 1 période (30s)
);
if ($enabled) {
return response()->json([
'message' => 'TOTP enabled successfully',
'verified_at' => now()->toDateTimeString(),
]);
}
return response()->json([
'message' => 'Invalid TOTP code',
], 400);
} catch (TotpException $e) {
return response()->json([
'message' => $e->getMessage(),
], 400);
}
}
public function verifyLogin(Request $request)
{
$user = User::where('email', $request->email)->firstOrFail();
$request->validate([
'code' => ' );
if ($valid) {
auth()->login($user);
return response()->json([
'message' => 'Login successful',
]);
}
return response()->json([
'message' => 'Invalid TOTP code',
], 400);
} catch (TotpException $e) {
return response()->json([
'message' => $e->getMessage(),
], 400);
}
}
public function recover(Request $request)
{
$user = User::where('email', $request->email)->firstOrFail();
$request->validate([
'recovery_code' => ');
if ($valid) {
auth()->login($user);
return response()->json([
'message' => 'Recovery successful',
]);
}
return response()->json([
'message' => 'Invalid recovery code',
], 400);
} catch (TotpException $e) {
return response()->json([
'message' => $e->getMessage(),
], 400);
}
}
public function disable(Request $request)
{
$user = $request->user();
try {
$this->totpService->disable($user);
return response()->json([
'message' => 'TOTP disabled successfully',
]);
} catch (TotpException $e) {
return response()->json([
'message' => $e->getMessage(),
], 400);
}
}
public function regenerateRecoveryCodes(Request $request)
{
$user = $request->user();
try {
$recoveryCodes = $this->totpService->regenerateRecoveryCodes($user);
return response()->json([
'recovery_codes' => $recoveryCodes->toArray(),
]);
} catch (TotpException $e) {
return response()->json([
'message' => $e->getMessage(),
], 400);
}
}
public function status(Request $request)
{
$user = $request->user();
return response()->json([
'enabled' => $this->totpService->isEnabled($user),
'verified' => $this->totpService->isVerified($user),
'remaining_recovery_codes' => count(
$this->totpService->getRemainingRecoveryCodes($user)
),
]);
}
$totpSecret = TotpSecret::find(1);
// Accès sous forme de Value Objects
$secretVO = $totpSecret->getSecret(); // TotpSecretVO
$recoveryCodes = $totpSecret->getRecoveryCodes(); // array<string>
$verifiedAt = $totpSecret->getVerifiedAt(); // DateTimeVO
$createdAt = $totpSecret->getCreatedAt(); // DateTimeVO
$updatedAt = $totpSecret->getUpdatedAt(); // DateTimeVO
$metadata = $totpSecret->getMetadata(); // StrictDataObject
// Méthodes utilitaires
$totpSecret->isEnabled(); // bool
$totpSecret->isVerified(); // bool
$totpSecret->countRecoveryCodes(); // int
$totpSecret->hasRecoveryCodes(); // bool
// Relation polymorphique
$authenticatable = $totpSecret->authenticatable; // User, Admin, etc.
bash
php artisan vendor:publish --tag=Totp-migrations
bash
php artisan migrate
bash
# Vérifier que GD est installé
php -m | grep gd
# Sur Ubuntu/Debian
sudo apt-get install php-gd
# Sur macOS avec Homebrew
brew install php-gd
laravel-totp/
├── src/
│ ├── TotpServiceProvider.php
│ ├── Models/
│ │ └── TotpSecret.php # Seul modèle avec relations polymorphiques
│ ├── Services/
│ │ ├── TotpService.php # Service principal
│ │ ├── TotpGenerator.php # Génération TOTP
│ │ └── QrCodeGenerator.php # Génération QR Code
│ ├── ValueObjects/
│ │ └── TotpSecretVO.php
│ └── Exceptions/
│ └── TotpException.php
├── database/
│ └── migrations/
│ └── create_totp_secrets_table.php
└── tests/
├── Integration/
│ └── Services/
│ └── TotpServiceIntegrationTest.php
├── Fixtures/
└── IntegrationTestCase.php