Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Confirmable 2FA #357

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public function up()
$table->text('two_factor_recovery_codes')
->after('two_factor_secret')
->nullable();

$table->boolean('two_factor_confirmed')
->after('two_factor_recovery_codes')
->default(false);
});
}

Expand All @@ -32,7 +36,7 @@ public function up()
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('two_factor_secret', 'two_factor_recovery_codes');
$table->dropColumn('two_factor_secret', 'two_factor_recovery_codes', 'two_factor_confirmed');
});
}
};
5 changes: 5 additions & 0 deletions routes/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\ConfirmablePasswordController;
use Laravel\Fortify\Http\Controllers\ConfirmedPasswordStatusController;
use Laravel\Fortify\Http\Controllers\ConfirmedTwoFactorAuthenticationController;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
use Laravel\Fortify\Http\Controllers\EmailVerificationPromptController;
use Laravel\Fortify\Http\Controllers\NewPasswordController;
Expand Down Expand Up @@ -141,6 +142,10 @@
->middleware($twoFactorMiddleware)
->name('two-factor.enable');

Route::post('/user/confirmed-two-factor-authentication', [ConfirmedTwoFactorAuthenticationController::class, 'store'])
->middleware($twoFactorMiddleware)
->name('two-factor.confirm');

Route::delete('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'destroy'])
->middleware($twoFactorMiddleware)
->name('two-factor.disable');
Expand Down
51 changes: 51 additions & 0 deletions src/Actions/ConfirmTwoFactorAuthentication.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Laravel\Fortify\Actions;

use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
use Laravel\Fortify\Events\TwoFactorAuthenticationConfirmed;

class ConfirmTwoFactorAuthentication
{
/**
* The two factor authentication provider.
*
* @var \Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider
*/
protected $provider;

/**
* Create a new action instance.
*
* @param \Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider $provider
* @return void
*/
public function __construct(TwoFactorAuthenticationProvider $provider)
{
$this->provider = $provider;
}

/**
* Confirm the two factor authentication configuration for the user.
*
* @param mixed $user
* @param string $code
* @return void
*/
public function __invoke($user, $code)
{
if (empty($user->two_factor_secret) ||
! $this->provider->verify(decrypt($user->two_factor_secret), $code)) {
throw ValidationException::withMessages([
'code' => [__('The provided two factor authentication code was invalid.')],
])->errorBag('confirmTwoFactorAuthentication');
}

$user->forceFill([
'two_factor_confirmed' => true,
])->save();

TwoFactorAuthenticationConfirmed::dispatch($user);
}
}
5 changes: 4 additions & 1 deletion src/Actions/DisableTwoFactorAuthentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Laravel\Fortify\Actions;

use Laravel\Fortify\Events\TwoFactorAuthenticationDisabled;
use Laravel\Fortify\Features;

class DisableTwoFactorAuthentication
{
Expand All @@ -17,7 +18,9 @@ public function __invoke($user)
$user->forceFill([
'two_factor_secret' => null,
'two_factor_recovery_codes' => null,
])->save();
] + (Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm') ? [
'two_factor_confirmed' => false,
] : []))->save();

TwoFactorAuthenticationDisabled::dispatch($user);
}
Expand Down
11 changes: 11 additions & 0 deletions src/Actions/RedirectIfTwoFactorAuthenticatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Events\TwoFactorAuthenticationChallenged;
use Laravel\Fortify\Features;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\LoginRateLimiter;
use Laravel\Fortify\TwoFactorAuthenticatable;
Expand Down Expand Up @@ -50,6 +51,16 @@ public function handle($request, $next)
{
$user = $this->validateCredentials($request);

if (Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm')) {
if (optional($user)->two_factor_secret &&
optional($user)->two_factor_confirmed &&
in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user))) {
return $this->twoFactorChallengeResponse($request, $user);
} else {
return $next($request);
taylorotwell marked this conversation as resolved.
Show resolved Hide resolved
}
}

if (optional($user)->two_factor_secret &&
in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user))) {
return $this->twoFactorChallengeResponse($request, $user);
Expand Down
8 changes: 8 additions & 0 deletions src/Events/TwoFactorAuthenticationConfirmed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Laravel\Fortify\Events;

class TwoFactorAuthenticationConfirmed extends TwoFactorAuthenticationEvent
{
//
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Laravel\Fortify\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Laravel\Fortify\Actions\ConfirmTwoFactorAuthentication;

class ConfirmedTwoFactorAuthenticationController extends Controller
{
/**
* Enable two factor authentication for the user.
*
* @param \Illuminate\Http\Request $request
* @param \Laravel\Fortify\Actions\ConfirmTwoFactorAuthentication $confirm
* @return \Symfony\Component\HttpFoundation\Response
*/
public function store(Request $request, ConfirmTwoFactorAuthentication $confirm)
{
$confirm($request->user(), $request->input('code'));

return $request->wantsJson()
? new JsonResponse('', 200)
: back()->with('status', 'two-factor-authentication-confirmed');
}
}
64 changes: 64 additions & 0 deletions tests/AuthenticatedSessionControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,70 @@ public function test_user_is_redirected_to_challenge_when_using_two_factor_authe
Event::assertDispatched(TwoFactorAuthenticationChallenged::class);
}

public function test_user_is_not_redirected_to_challenge_when_using_two_factor_authentication_that_has_not_been_confirmed_and_confirmation_is_enabled()
{
Event::fake();

app('config')->set('auth.providers.users.model', TestTwoFactorAuthenticationSessionUser::class);
app('config')->set('fortify.features', [
Features::registration(),
Features::twoFactorAuthentication(['confirm' => true]),
]);

$this->loadLaravelMigrations(['--database' => 'testbench']);

Schema::table('users', function ($table) {
$table->text('two_factor_secret')->nullable();
});

TestTwoFactorAuthenticationSessionUser::forceCreate([
'name' => 'Taylor Otwell',
'email' => '[email protected]',
'password' => bcrypt('secret'),
'two_factor_secret' => 'test-secret',
]);

$response = $this->withoutExceptionHandling()->post('/login', [
'email' => '[email protected]',
'password' => 'secret',
]);

$response->assertRedirect('/home');
}

public function test_user_is_redirected_to_challenge_when_using_two_factor_authentication_that_has_been_confirmed_and_confirmation_is_enabled()
{
Event::fake();

app('config')->set('auth.providers.users.model', TestTwoFactorAuthenticationSessionUser::class);
app('config')->set('fortify.features', [
Features::registration(),
Features::twoFactorAuthentication(['confirm' => true]),
]);

$this->loadLaravelMigrations(['--database' => 'testbench']);

Schema::table('users', function ($table) {
$table->text('two_factor_secret')->nullable();
$table->boolean('two_factor_confirmed')->default(true);
});

TestTwoFactorAuthenticationSessionUser::forceCreate([
'name' => 'Taylor Otwell',
'email' => '[email protected]',
'password' => bcrypt('secret'),
'two_factor_secret' => 'test-secret',
'two_factor_confirmed' => true,
]);

$response = $this->withoutExceptionHandling()->post('/login', [
'email' => '[email protected]',
'password' => 'secret',
]);

$response->assertRedirect('/two-factor-challenge');
}

public function test_user_can_authenticate_when_two_factor_challenge_is_disabled()
{
app('config')->set('auth.providers.users.model', TestTwoFactorAuthenticationSessionUser::class);
Expand Down
68 changes: 67 additions & 1 deletion tests/TwoFactorAuthenticationControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Event;
use Laravel\Fortify\Events\TwoFactorAuthenticationConfirmed;
use Laravel\Fortify\Events\TwoFactorAuthenticationDisabled;
use Laravel\Fortify\Events\TwoFactorAuthenticationEnabled;
use Laravel\Fortify\FortifyServiceProvider;
use Laravel\Fortify\TwoFactorAuthenticatable;
use PragmaRX\Google2FA\Google2FA;

class TwoFactorAuthenticationControllerTest extends OrchestraTestCase
{
Expand All @@ -32,14 +34,78 @@ public function test_two_factor_authentication_can_be_enabled()

Event::assertDispatched(TwoFactorAuthenticationEnabled::class);

$user->fresh();
$user = $user->fresh();

$this->assertNotNull($user->two_factor_secret);
$this->assertNotNull($user->two_factor_recovery_codes);
$this->assertEquals(0, $user->two_factor_confirmed);
$this->assertIsArray(json_decode(decrypt($user->two_factor_recovery_codes), true));
$this->assertNotNull($user->twoFactorQrCodeSvg());
}

public function test_two_factor_authentication_can_be_confirmed()
{
Event::fake();

$this->loadLaravelMigrations(['--database' => 'testbench']);
$this->artisan('migrate', ['--database' => 'testbench'])->run();

$tfaEngine = app(Google2FA::class);
$userSecret = $tfaEngine->generateSecretKey();
$validOtp = $tfaEngine->getCurrentOtp($userSecret);

$user = TestTwoFactorAuthenticationUser::forceCreate([
'name' => 'Taylor Otwell',
'email' => '[email protected]',
'password' => bcrypt('secret'),
'two_factor_secret' => encrypt($userSecret),
'two_factor_confirmed' => false,
]);

$response = $this->withoutExceptionHandling()->actingAs($user)->postJson(
'/user/confirmed-two-factor-authentication', ['code' => $validOtp],
);

$response->assertStatus(200);

Event::assertDispatched(TwoFactorAuthenticationConfirmed::class);

$user = $user->fresh();

$this->assertEquals(1, $user->two_factor_confirmed);
}

public function test_two_factor_authentication_can_not_be_confirmed_with_invalid_code()
{
Event::fake();

$this->loadLaravelMigrations(['--database' => 'testbench']);
$this->artisan('migrate', ['--database' => 'testbench'])->run();

$tfaEngine = app(Google2FA::class);
$userSecret = $tfaEngine->generateSecretKey();

$user = TestTwoFactorAuthenticationUser::forceCreate([
'name' => 'Taylor Otwell',
'email' => '[email protected]',
'password' => bcrypt('secret'),
'two_factor_secret' => encrypt($userSecret),
'two_factor_confirmed' => false,
]);

$response = $this->withExceptionHandling()->actingAs($user)->postJson(
'/user/confirmed-two-factor-authentication', ['code' => 'invalid-otp'],
);

$response->assertStatus(422);

Event::assertNotDispatched(TwoFactorAuthenticationConfirmed::class);

$user = $user->fresh();

$this->assertEquals(0, $user->two_factor_confirmed);
}

public function test_two_factor_authentication_can_be_disabled()
{
Event::fake();
Expand Down