Skip to content

Instantly share code, notes, and snippets.

@lahirulhr
Created June 25, 2023 05:28
Show Gist options
  • Save lahirulhr/7295bb38991d784d0ddb8ad437dd8a08 to your computer and use it in GitHub Desktop.
Save lahirulhr/7295bb38991d784d0ddb8ad437dd8a08 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Laravel\Nova\Nova;
class TwoFactorRequired
{
private function exceptUrl()
{
return [
'nova-vendor/*',
'nova-api/*',
Nova::url('nova-two-factor'),
Nova::url('logout'),
];
}
public function handle(Request $request, Closure $next)
{
// exclude any except routes or non auth requests
if ($this->inExceptArray($request) || !auth()->check()) {
return $next($request);
}
// check user has any twofa / disabled twofa
if (!auth()->user()->twoFa || !auth()->user()->twoFa->google2fa_enabled) {
return redirect()->to(Nova::url('nova-two-factor'));
}
return $next($request);
}
private function inExceptArray($request)
{
foreach ($this->exceptUrl() as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->fullUrlIs($except) || $request->is($except)) {
return true;
}
}
return false;
}
}
@ArtDepartmentMJ
Copy link

Thanks for this

Line 29 should read:

if (!auth()->user()->twoFa || !auth()->user()->twoFa->google2fa_enable) {

@mateusz-peczkowski
Copy link

mateusz-peczkowski commented Sep 26, 2024

Looks great. But I found another thing that can be added to that. Line 23 after opening bracket:

// check if two factor is enabled
if (!config('nova-two-factor.enabled'))
return $next($request);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment