Skip to content

Commit

Permalink
First version of 2FA text interface
Browse files Browse the repository at this point in the history
  • Loading branch information
erkens committed Jun 26, 2020
0 parents commit b05ac7b
Show file tree
Hide file tree
Showing 14 changed files with 445 additions and 0 deletions.
30 changes: 30 additions & 0 deletions DependencyInjection/Compiler/TextCompilerPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\LogicException;

class TextCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('scheb_two_factor.provider_registry')) {
return;
}

if (!$container->hasDefinition('two_factor_text.security.provider')) {
return;
}

if ($container->hasAlias('two_factor_text.security.auth_code_sender')) {
return;
}

$message = 'Sender service for "two_factor_text.security.text.auth_code_sender" is not configured.';
throw new LogicException($message);
}
}
34 changes: 34 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('two_factor_text');
$rootNode = $treeBuilder->getRootNode();

/**
* @psalm-suppress PossiblyNullReference
* @psalm-suppress PossiblyUndefinedMethod
*/
$rootNode
->canBeEnabled()
->children()
->scalarNode('auth_code_sender')->defaultValue('Erkens\Security\TwoFactorTextBundle\TextSender\ExampleTextSender')->end()
->scalarNode('code_generator')->defaultValue('two_factor_text.security.default_code_generator')->end()
->scalarNode('template')->defaultValue('@SchebTwoFactor/Authentication/form.html.twig')->end()
->integerNode('digits')->defaultValue(6)->min(1)->end()
->scalarNode('text')->defaultValue('Use this code to login: %s')->end()
->end()
->end();

return $treeBuilder;
}
}
53 changes: 53 additions & 0 deletions DependencyInjection/TwoFactorTextExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class TwoFactorTextExtension extends Extension implements PrependExtensionInterface
{
public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

// if not enabled, don't load it
if (isset($config['enabled']) && true === $config['enabled']) {
$this->configureTextAuthenticationProvider($container, $config);
}
}

public function getAlias()
{
return 'two_factor_text';
}

private function configureTextAuthenticationProvider(ContainerBuilder $container, array $config): void
{
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('two_factor_provider_text.xml');

$container->setParameter($this->getAlias() . '.enabled', $config['enabled']);
$container->setParameter($this->getAlias() . '.template', $config['template']);
$container->setParameter($this->getAlias() . '.digits', $config['digits']);
$container->setParameter($this->getAlias() . '.text', $config['text']);
$container->setAlias($this->getAlias() . '.security.code_generator', $config['code_generator'])->setPublic(true);
$container->setAlias($this->getAlias() . '.security.auth_code_sender', $config['auth_code_sender']);
}

public function prepend(ContainerBuilder $container)
{
$configs = $container->getExtensionConfig($this->getAlias());
$config = $this->processConfiguration(new Configuration(), $configs);
// Load two-factor modules
if (isset($config['enabled']) && true === $config['enabled']) {
$this->configureTextAuthenticationProvider($container, $config);
}
}
}
63 changes: 63 additions & 0 deletions Generator/CodeGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\Generator;

use Erkens\Security\TwoFactorTextBundle\TextSender\AuthCodeTextInterface;
use Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface;
use Scheb\TwoFactorBundle\Model\PersisterInterface;

class CodeGenerator implements CodeGeneratorInterface
{
/**
* @var PersisterInterface
*/
private $persister;

/**
* @var AuthCodeTextInterface
*/
private $textSender;

/**
* @var int
*/
private $digits;
/**
* @var string
*/
private $text;

public function __construct(
PersisterInterface $persister,
AuthCodeTextInterface $textSender,
int $digits,
string $text
) {
$this->persister = $persister;
$this->textSender = $textSender;
$this->digits = $digits;
$this->text = $text;
}

public function generateAndSend(TwoFactorTextInterface $user): void
{
$min = 10 ** ($this->digits - 1);
$max = 10 ** $this->digits - 1;
$code = $this->generateCode($min, $max);
$user->setTextAuthCode((string)$code);
$this->persister->persist($user);
$this->textSender->sendAuthCode($user, $this->text);
}

public function reSend(TwoFactorTextInterface $user): void
{
$this->textSender->sendAuthCode($user, $this->text);
}

protected function generateCode(int $min, int $max): int
{
return random_int($min, $max);
}
}
15 changes: 15 additions & 0 deletions Generator/CodeGeneratorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\Generator;

use Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface;

interface CodeGeneratorInterface
{
/**
* Generate a new authentication code an send it to the user.
*/
public function generateAndSend(TwoFactorTextInterface $user): void;
}
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2020 Michael Erkens

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 changes: 28 additions & 0 deletions Model/TwoFactorTextInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\Model;

interface TwoFactorTextInterface
{
/**
* Return true if the user should do two-factor authentication.
*/
public function isTextAuthEnabled(): bool;

/**
* Return user text number, please note that the format of this number can vary
*/
public function getTextAuthRecipient(): string;

/**
* Return the authentication code.
*/
public function getTextAuthCode(): string;

/**
* Set the authentication code.
*/
public function setTextAuthCode(string $authCode): void;
}
62 changes: 62 additions & 0 deletions Provider/TextTwoFactorProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\Provider;

use Erkens\Security\TwoFactorTextBundle\Generator\CodeGeneratorInterface;
use Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\AuthenticationContextInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\TwoFactorFormRendererInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\TwoFactorProviderInterface;

class TextTwoFactorProvider implements TwoFactorProviderInterface
{
/**
* @var CodeGeneratorInterface
*/
private $codeGenerator;

/**
* @var TwoFactorFormRendererInterface
*/
private $formRenderer;

public function __construct(CodeGeneratorInterface $codeGenerator, TwoFactorFormRendererInterface $formRenderer)
{
$this->codeGenerator = $codeGenerator;
$this->formRenderer = $formRenderer;
}

public function beginAuthentication(AuthenticationContextInterface $context): bool
{
// Check if user can do text authentication
$user = $context->getUser();

return $user instanceof TwoFactorTextInterface && $user->isTextAuthEnabled();
}

public function prepareAuthentication($user): void
{
if ($user instanceof \Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface) {
$this->codeGenerator->generateAndSend($user);
}
}

public function validateAuthenticationCode($user, string $authenticationCode): bool
{
if (!($user instanceof \Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface)) {
return false;
}

// Strip any user added spaces
$authenticationCode = str_replace(' ', '', $authenticationCode);

return $user->getTextAuthCode() === $authenticationCode;
}

public function getFormRenderer(): TwoFactorFormRendererInterface
{
return $this->formRenderer;
}
}
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
erkens/2fa-text
===============

This package extends [scheb/2fa-bundle](https://github.com/scheb/2fa-bundle) with two-factor authentication via text messages.

It is based on the official [scheb/2fa-email](https://github.com/scheb/2fa-email) package.

Usage
-----
After you have installed and configured [scheb/2fa-bundle](https://github.com/scheb/2fa-bundle) you can install this package:

```
composer require erkens/2fa-text
```

First thing to do is make a new service that implements `Erkens\Security\TwoFactorTextBundle\Generator\CodeGeneratorInterface`
so we can actually send a sms or text message. This service can then be used in the configuration as "auth_code_sender":

```
two_factor_text:
enabled: true
auth_code_sender: Erkens\Security\TwoFactorTextBundle\TextSender\ExampleTextSender
digits: 6
text: 'To login, use this code: %s'
template: '@SchebTwoFactor/Authentication/form.html.twig'
```

License
-------
This software is available under the [MIT license](LICENSE).
25 changes: 25 additions & 0 deletions Resources/config/two_factor_provider_text.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="two_factor_text.security.default_code_generator" class="Erkens\Security\TwoFactorTextBundle\Generator\CodeGenerator" lazy="true">
<argument type="service" id="scheb_two_factor.persister" />
<argument type="service" id="two_factor_text.security.auth_code_sender" />
<argument>%two_factor_text.digits%</argument>
<argument>%two_factor_text.text%</argument>
</service>

<service id="Erkens\Security\TwoFactorTextBundle\Generator\CodeGeneratorInterface" alias="two_factor_text.security.code_generator" public="true" />
<service id="Erkens\Security\TwoFactorTextBundle\TextSender\ExampleTextSender" />

<service id="two_factor_text.security.form_renderer" class="Scheb\TwoFactorBundle\Security\TwoFactor\Provider\DefaultTwoFactorFormRenderer" lazy="true">
<argument type="service" id="twig" />
<argument>%two_factor_text.template%</argument>
</service>

<service id="two_factor_text.security.provider" class="Erkens\Security\TwoFactorTextBundle\Provider\TextTwoFactorProvider">
<tag name="scheb_two_factor.provider" alias="text" />
<argument type="service" id="two_factor_text.security.code_generator" />
<argument type="service" id="two_factor_text.security.form_renderer"/>
</service>
</services>
</container>
17 changes: 17 additions & 0 deletions TextSender/AuthCodeTextInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Erkens\Security\TwoFactorTextBundle\TextSender;

use Erkens\Security\TwoFactorTextBundle\Model\TwoFactorTextInterface;

interface AuthCodeTextInterface
{
/**
* Send the auth code to the user via text
*
* @param TwoFactorTextInterface $user
*/
public function sendAuthCode(TwoFactorTextInterface $user, string $format): void;
}
Loading

0 comments on commit b05ac7b

Please sign in to comment.