<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
andrej-griniuk / cakephp-two-factor-auth example snippets
$this->addPlugin('TwoFactorAuth');
class Application extends BaseApplication implements AuthenticationServiceProviderInterface
{
public function bootstrap(): void
{
// Call parent to load bootstrap from files.
parent::bootstrap();
$this->addPlugin('TwoFactorAuth');
$this->addPlugin('Authentication');
}
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
// Various other middlewares for error handling, routing etc. added here.
// Create an authentication middleware object
$authentication = new AuthenticationMiddleware($this);
// Add the middleware to the middleware queue.
// Authentication should be added *after* RoutingMiddleware.
// So that subdirectory information and routes are loaded.
$middlewareQueue->add($authentication);
return $middlewareQueue;
}
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
$service->setConfig([
'unauthenticatedRedirect' => '/users/login',
'queryParam' => 'redirect',
]);
$fields = [
'username' => 'username',
'password' => 'password'
];
// Load the authenticators, you want session first
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('TwoFactorAuth.TwoFactorForm', [
'fields' => $fields,
'loginUrl' => '/users/login'
]);
// Load identifiers
$service->loadIdentifier('Authentication.Password', compact('fields'));
return $service;
}
}
// in src/Controller/AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('Authentication.Authentication');
$this->loadComponent('TwoFactorAuth.TwoFactorAuth');
}
class UsersController extends AppController
{
public function beforeFilter(\Cake\Event\EventInterface $event)
{
parent::beforeFilter($event);
$this->Authentication->allowUnauthenticated(['login', 'verify']);
}
public function login()
{
$result = $this->Authentication->getResult();
if ($result->isValid()) {
// If the user is logged in send them away.
$target = $this->Authentication->getLoginRedirect() ?? '/home';
return $this->redirect($target);
}
if ($this->request->is('post') && !$result->isValid()) {
if ($result->getStatus() == \TwoFactorAuth\Authenticator\Result::TWO_FACTOR_AUTH_FAILED) {
// One time code was entered and it's invalid
$this->Flash->error('Invalid 2FA code');
return $this->redirect(['action' => 'verify']);
} elseif ($result->getStatus() == \TwoFactorAuth\Authenticator\Result::TWO_FACTOR_AUTH_REQUIRED) {
// One time code is