Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat: add conditional auth actions by memleakd · Pull Request #1328 · codeigniter4/shield · GitHub
Skip to content
Merged
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
50 changes: 49 additions & 1 deletion docs/references/authentication/auth_actions.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,4 +86,52 @@ and provides feedback. In the `Email2FA` class, it verifies the code against wha
database and either sends them back to the previous form to try again or redirects the user to the
page that a `login` task would have redirected them to anyway.

All methods should return either a `Response` or a view string (e.g. using the `view()` function).
All methods should return either a `Response` or a view string (e.g. using the `view()` function).

## Conditional Actions

Some applications only need an action for certain users. For example, you may
want email-based 2FA for administrators, but not for every user.

To make an action conditional, implement `ConditionalActionInterface`:

```php
<?php

namespace App\Authentication\Actions;

use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Entities\User;

final class AdminEmail2FA extends Email2FA implements ConditionalActionInterface
{
public function appliesTo(User $user): bool
{
return $user->inGroup('admin', 'superadmin');
}
}
```

Then register your conditional action in **app/Config/Auth.php**:

```php
public array $actions = [
'register' => null,
'login' => \App\Authentication\Actions\AdminEmail2FA::class,
];
```

When `appliesTo()` returns `true`, Shield starts the action as usual and
discovers any stored identity for that action. When it returns `false`, Shield
does not start the action and ignores stored identities for that action while
the condition remains false. The exception is activation: if a user is already
inactive and has a stored activation identity, Shield continues to require that
activation before login can complete.

The `appliesTo()` method may be called more than once while Shield checks for
actions, so keep it deterministic, free of side effects, and fail closed when
the condition cannot be determined. It is not a replacement for authorization.

Once an action is already pending in the session, Shield continues that pending
action instead of rechecking the condition.
1 change: 1 addition & 0 deletions docs/references/authorization.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -256,6 +256,7 @@ if ($user->isActivated()) {
!!! note

If no activator is specified in the `Auth` config file, `actions['register']` property, then this will always return `true`.
If a conditional activator does not apply during registration, the newly registered user is activated immediately.

You can check if a user has not been activated yet via the `isNotActivated()` method.

Expand Down
30 changes: 30 additions & 0 deletions src/Authentication/Actions/ConditionalActionInterface.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Authentication\Actions;

use CodeIgniter\Shield\Entities\User;

/**
* Allows an authentication action to decide if it applies to a user.
*/
interface ConditionalActionInterface
{
/**
* Determines if this action applies to the given user.
*
* This method may be called while Shield starts or discovers pending actions.
* It should be deterministic and free of side effects.
*/
public function appliesTo(User $user): bool;
}
44 changes: 37 additions & 7 deletions src/Authentication/Authenticators/Session.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
use CodeIgniter\HTTP\Response;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Passwords;
Expand DownExpand Up@@ -185,11 +186,11 @@ public function attempt(array $credentials): Result
}

/**
* If an action has been defined, start it up.
* If an action has been defined and applies to the user, start it up.
*
* @param string $type 'register', 'login'
*
* @return bool If the action has been defined or not.
* @return bool If the action was started or not.
*/
public function startUpAction(string $type, User $user): bool
{
Expand All@@ -202,6 +203,10 @@ public function startUpAction(string $type, User $user): bool
/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (! $this->actionAppliesToUser($action, $user)) {
return false;
}

// Create identity for the action.
$action->createIdentity($user);

Expand DownExpand Up@@ -472,14 +477,21 @@ private function setAuthAction(): bool

$authActions = setting('Auth.actions');

foreach ($authActions as $actionClass) {
foreach ($authActions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $this->user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $this->user)
) {
continue;
}

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity instanceof UserIdentity) {
Expand All@@ -504,31 +516,49 @@ private function getIdentitiesForAction(User $user): array
{
return $this->userIdentityModel->getIdentitiesByTypes(
$user,
$this->getActionTypes(),
$this->getActionTypes($user),
);
}

/**
* @return list<string>
*/
private function getActionTypes(): array
private function getActionTypes(User $user): array
{
$actions = setting('Auth.actions');
$types = [];

foreach ($actions as $actionClass) {
foreach ($actions as $type => $actionClass) {
if ($actionClass === null || $actionClass === '') {
continue;
}

/** @var ActionInterface $action */
$action = Factories::actions($actionClass); // @phpstan-ignore-line
$action = Factories::actions($actionClass); // @phpstan-ignore-line

if (
! $this->actionAppliesToUser($action, $user)
&& ! $this->inactiveUserNeedsRegisterAction($type, $user)
) {
continue;
}

$types[] = $action->getType();
}

return $types;
}

private function actionAppliesToUser(ActionInterface $action, User $user): bool
{
return ! $action instanceof ConditionalActionInterface || $action->appliesTo($user);
}

private function inactiveUserNeedsRegisterAction(int|string $type, User $user): bool
{
return $type === 'register' && ! $user->active;
}

/**
* Checks if the user is currently in pending login state.
* They need to do an auth action.
Expand Down
1 change: 1 addition & 0 deletions src/Config/Auth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,6 +98,7 @@ class Auth extends BaseConfig
* Custom Actions and Requirements:
*
* - All actions must implement \CodeIgniter\Shield\Authentication\Actions\ActionInterface.
* - Actions may implement \CodeIgniter\Shield\Authentication\Actions\ConditionalActionInterface to apply only to certain users.
* - Custom actions for "register" must have a class name that ends with the suffix "Activator" (e.g., `CustomSmsActivator`) ensure proper functionality.
*
* @var array<string, class-string<ActionInterface>|null>
Expand Down
5 changes: 5 additions & 0 deletions src/Filters/SessionAuth.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,11 @@ public function before(RequestInterface $request, $arguments = null)
return redirect()->route('auth-action-show')
->with('error', lang('Auth.activationBlocked'));
}

$authenticator->logout();

return redirect()->to(config('Auth')->logoutRedirect())
->with('error', lang('Auth.activationBlocked'));
}

return;
Expand Down
44 changes: 44 additions & 0 deletions tests/Authentication/Filters/SessionFilterTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,9 +14,12 @@
namespace Tests\Authentication\Filters;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Test\DatabaseTestTrait;
use Tests\Support\AdminEmailActivator;

/**
* @internal
Expand DownExpand Up@@ -94,6 +97,47 @@ public function testBlocksInactiveUsersAndRedirectsToAuthAction(): void
setting('Auth.actions', ['register' => null]);
}

public function testBlocksInactiveUsersWhenConditionalActivatorDoesNotApply(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

$result = $this->actingAs($user)
->get('protected-route');

$result->assertRedirectTo(config('Auth')->logoutRedirect());
$result->assertSessionHas('error', lang('Auth.activationBlocked'));
$this->assertNull(auth('session')->id());

setting('Auth.actions', ['register' => null]);
}

public function testRedirectsInactiveUsersToStoredConditionalActivationAction(): void
{
$user = fake(UserModel::class, ['active' => false]);

setting('Auth.actions', ['register' => AdminEmailActivator::class]);

model(UserIdentityModel::class)->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_ACTIVATE,
'secret' => '123456',
'name' => 'register',
'extra' => lang('Auth.needVerification'),
]);

/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$this->assertTrue($authenticator->hasAction($user->id));

$result = $this->get('protected-route');

$result->assertRedirectTo('/auth/a/show');

setting('Auth.actions', ['register' => null]);
}

public function testStoreRedirectsToEntraceUrlIntoSession(): void
{
$result = $this->call('get', 'protected-route');
Expand Down
89 changes: 89 additions & 0 deletions tests/Controllers/LoginTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,12 @@
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\TestResponse;
use Config\Services;
use Config\Validation;
use Tests\Support\AdminEmail2FA;
use Tests\Support\DatabaseTestCase;
use Tests\Support\FakeUser;

Expand DownExpand Up@@ -256,4 +259,90 @@ public function testLoginRedirectsToActionIfDefined(): void
$result->assertSessionMissing('errors');
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginRedirectsToConditionalActionWhenItApplies(): void
{
$this->enableAdminEmail2FA();

$this->user->addGroup('admin');
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

public function testLoginSkipsConditionalActionWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginIgnoresStoredConditionalActionIdentityWhenItDoesNotApply(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

model(UserIdentityModel::class)->insert([
'user_id' => $this->user->id,
'type' => 'email_2fa',
'name' => 'login',
'secret' => '123456',
'extra' => lang('Auth.need2FA'),
]);

$result = $this->loginUser();

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url(), $result->getRedirectUrl());
}

public function testLoginKeepsExistingPendingConditionalActionInSession(): void
{
$this->enableAdminEmail2FA();
$this->createUserEmailIdentity();

$result = $this->withSession([
'user' => [
'id' => $this->user->id,
'auth_action' => AdminEmail2FA::class,
],
])->get('/login');

$result->assertStatus(302);
$result->assertRedirect();
$this->assertSame(site_url('auth/a/show'), $result->getRedirectUrl());
}

private function enableAdminEmail2FA(): void
{
$config = config('Auth');
$config->actions['login'] = AdminEmail2FA::class;
Factories::injectMock('config', 'Auth', $config);
}

private function createUserEmailIdentity(): void
{
$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}

private function loginUser(): TestResponse
{
return $this->post('/login', [
'email' => 'foo@example.com',
'password' => 'secret123',
]);
}
}
Loading
Loading