Skip to content
Open
83 changes: 83 additions & 0 deletions src/Maker/Security/AbstractSecurityMaker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

/*
* This file is part of the Symfony MakerBundle package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\MakerBundle\Maker\Security;

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
use Symfony\Bundle\MakerBundle\FileManager;
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
use Symfony\Bundle\MakerBundle\Security\InteractiveSecurityHelper;
use Symfony\Bundle\MakerBundle\Security\SecurityConfigUpdater;
use Symfony\Bundle\MakerBundle\Security\SecurityControllerBuilder;
use Symfony\Bundle\MakerBundle\Util\YamlSourceManipulator;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Yaml\Yaml;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*
* @internal
*/
abstract class AbstractSecurityMaker extends AbstractMaker
{
protected const SECURITY_CONFIG_PATH = 'config/packages/security.yaml';

protected YamlSourceManipulator $ysm;
protected string $securityControllerName;
protected string $firewallToUpdate;
protected string $userClass;
protected string $userNameField;
protected bool $willLogout;

public function __construct(
protected FileManager $fileManager,
protected SecurityConfigUpdater $securityConfigUpdater,
protected SecurityControllerBuilder $securityControllerBuilder,
) {
}

public function configureDependencies(DependencyBuilder $dependencies): void
{
$dependencies->addClassDependency(SecurityBundle::class, 'security');
$dependencies->addClassDependency(Process::class, 'process');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually needed?

$dependencies->addClassDependency(Yaml::class, 'yaml');
$dependencies->addClassDependency(DoctrineBundle::class, 'orm');
}

public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
if (!$this->fileManager->fileExists(self::SECURITY_CONFIG_PATH)) {
throw new RuntimeCommandException(sprintf('The file "%s" does not exist. PHP & XML configuration formats are currently not supported.', self::SECURITY_CONFIG_PATH));
}

$this->securityControllerName = $io->ask(
'Choose a name for the controller class (e.g. <fg=yellow>ApiLoginController</>)',
'ApiLoginController',
[Validator::class, 'validateClassName']
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This question and the suggestion of ApiLoginController are in the abstract security maker?


$this->ysm = new YamlSourceManipulator($this->fileManager->getFileContents(self::SECURITY_CONFIG_PATH));
$securityData = $this->ysm->getData();

$securityHelper = new InteractiveSecurityHelper();
$this->firewallToUpdate = $securityHelper->guessFirewallName($io, $securityData);
$this->userClass = $securityHelper->guessUserClass($io, $securityData['security']['providers']);
$this->userNameField = $securityHelper->guessUserNameField($io, $this->userClass, $securityData['security']['providers']);
$this->willLogout = $io->confirm('Do you want to generate a \'/logout\' URL?');
}
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could probably find more repeated code between make:json & make:form logins if we looked hard enough...

99 changes: 28 additions & 71 deletions src/Maker/Security/MakeFormLogin.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,22 @@

namespace Symfony\Bundle\MakerBundle\Maker\Security;

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
use Symfony\Bundle\MakerBundle\FileManager;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
use Symfony\Bundle\MakerBundle\Security\InteractiveSecurityHelper;
use Symfony\Bundle\MakerBundle\Security\SecurityConfigUpdater;
use Symfony\Bundle\MakerBundle\Security\SecurityControllerBuilder;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Util\ClassSourceManipulator;
use Symfony\Bundle\MakerBundle\Util\UseStatementGenerator;
use Symfony\Bundle\MakerBundle\Util\YamlSourceManipulator;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Yaml\Yaml;

/**
* Generate Form Login Security using SecurityBundle's Authenticator.
Expand All @@ -46,22 +37,8 @@
*
* @internal
*/
final class MakeFormLogin extends AbstractMaker
final class MakeFormLogin extends AbstractSecurityMaker
{
private const SECURITY_CONFIG_PATH = 'config/packages/security.yaml';
private YamlSourceManipulator $ysm;
private string $controllerName;
private string $firewallToUpdate;
private string $userNameField;
private bool $willLogout;

public function __construct(
private FileManager $fileManager,
private SecurityConfigUpdater $securityConfigUpdater,
private SecurityControllerBuilder $securityControllerBuilder,
) {
}

public static function getCommandName(): string
{
return 'make:security:form-login';
Expand All @@ -79,46 +56,20 @@ public static function getCommandDescription(): string

public function configureDependencies(DependencyBuilder $dependencies): void
{
$dependencies->addClassDependency(
SecurityBundle::class,
'security'
);

$dependencies->addClassDependency(TwigBundle::class, 'twig');

// needed to update the YAML files
$dependencies->addClassDependency(
Yaml::class,
'yaml'
);

$dependencies->addClassDependency(DoctrineBundle::class, 'orm');
parent::configureDependencies($dependencies);
}

public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
if (!$this->fileManager->fileExists(self::SECURITY_CONFIG_PATH)) {
throw new RuntimeCommandException(sprintf('The file "%s" does not exist. PHP & XML configuration formats are currently not supported.', self::SECURITY_CONFIG_PATH));
}
parent::interact($input, $io, $command);

$this->ysm = new YamlSourceManipulator($this->fileManager->getFileContents(self::SECURITY_CONFIG_PATH));
$securityData = $this->ysm->getData();

if (!isset($securityData['security']['providers']) || !$securityData['security']['providers']) {
throw new RuntimeCommandException('To generate a form login authentication, you must configure at least one entry under "providers" in "security.yaml".');
}

$this->controllerName = $io->ask(
'Choose a name for the controller class (e.g. <fg=yellow>SecurityController</>)',
'SecurityController',
[Validator::class, 'validateClassName']
);

$securityHelper = new InteractiveSecurityHelper();
$this->firewallToUpdate = $securityHelper->guessFirewallName($io, $securityData);
$userClass = $securityHelper->guessUserClass($io, $securityData['security']['providers']);
$this->userNameField = $securityHelper->guessUserNameField($io, $userClass, $securityData['security']['providers']);
$this->willLogout = $io->confirm('Do you want to generate a \'/logout\' URL?');
}

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
Expand All @@ -130,25 +81,36 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
AuthenticationUtils::class,
]);

$controllerNameDetails = $generator->createClassNameDetails($this->controllerName, 'Controller\\', 'Controller');
$controllerNameDetails = $generator->createClassNameDetails($this->securityControllerName, 'Controller\\', 'Controller');
$templatePath = strtolower($controllerNameDetails->getRelativeNameWithoutSuffix());

$controllerPath = $generator->generateController(
$controllerNameDetails->getFullName(),
'security/formLogin/LoginController.tpl.php',
[
'use_statements' => $useStatements,
'controller_name' => $controllerNameDetails->getShortName(),
'template_path' => $templatePath,
]
);
$controllerPath = $this->fileManager->getRelativePathForFutureClass($controllerNameDetails->getFullName());

if ($this->willLogout) {
$manipulator = new ClassSourceManipulator($generator->getFileContentsForPendingOperation($controllerPath));
$controllerExists = $this->fileManager->fileExists($controllerPath);

if (!$controllerExists) {
$generator->generateController(
$controllerNameDetails->getFullName(),
'EmptyController.tpl.php',
[
'use_statements' => $useStatements,
'controller_name' => $controllerNameDetails->getShortName(),
]
);
}

$controllerSource = $controllerExists ? file_get_contents($controllerPath) : $generator->getFileContentsForPendingOperation($controllerPath);

$manipulator = new ClassSourceManipulator($controllerSource);

$this->securityControllerBuilder->addFormLoginMethod($manipulator, $templatePath);

$securityData = $this->securityConfigUpdater->updateForFormLogin($this->ysm->getContents(), $this->firewallToUpdate, 'app_login', 'app_login');

if ($this->willLogout) {
$this->securityControllerBuilder->addLogoutMethod($manipulator);

$generator->dumpFile($controllerPath, $manipulator->getSourceCode());
$securityData = $this->securityConfigUpdater->updateForLogout($securityData, $this->firewallToUpdate);
}

$generator->generateTemplate(
Expand All @@ -161,13 +123,8 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
]
);

$securityData = $this->securityConfigUpdater->updateForFormLogin($this->ysm->getContents(), $this->firewallToUpdate, 'app_login', 'app_login');

if ($this->willLogout) {
$securityData = $this->securityConfigUpdater->updateForLogout($securityData, $this->firewallToUpdate);
}

$generator->dumpFile(self::SECURITY_CONFIG_PATH, $securityData);
$generator->dumpFile($controllerPath, $manipulator->getSourceCode());

$generator->writeChanges();

Expand Down
111 changes: 111 additions & 0 deletions src/Maker/Security/MakeJsonLogin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

/*
* This file is part of the Symfony MakerBundle package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\MakerBundle\Maker\Security;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Util\ClassNameDetails;
use Symfony\Bundle\MakerBundle\Util\ClassSourceManipulator;
use Symfony\Bundle\MakerBundle\Util\UseStatementGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

/**
* Generate Form Login Security using SecurityBundle's Authenticator.
*
* @see https://symfony.com/doc/current/security.html#form-login
*
* @author Jesse Rushlow <jr@rushlow.dev>
*
* @internal
*/
final class MakeJsonLogin extends AbstractSecurityMaker
{
public static function getCommandName(): string
{
return 'make:security:json-login';
}

public function configureCommand(Command $command, InputConfiguration $inputConfig): void
{
$command->setHelp(file_get_contents(\dirname(__DIR__, 2).'/Resources/help/security/MakeJsonLogin.txt'));
}

public static function getCommandDescription(): string
{
return 'Generate the code needed for the json_login authenticator';
}

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$userClassDetails = new ClassNameDetails($this->userClass, '');

$useStatements = new UseStatementGenerator([
$userClassDetails->getFullName(),
AbstractController::class,
JsonResponse::class,
Response::class,
Route::class,
CurrentUser::class,
]);

$controllerNameDetails = $generator->createClassNameDetails($this->securityControllerName, 'Controller\\', 'Controller');

$controllerPath = $this->fileManager->getRelativePathForFutureClass($controllerNameDetails->getFullName());

$controllerExists = $this->fileManager->fileExists($controllerPath);

if (!$controllerExists) {
$generator->generateController(
$controllerNameDetails->getFullName(),
'EmptyController.tpl.php',
[
'use_statements' => $useStatements,
'controller_name' => $controllerNameDetails->getShortName(),
]
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be a new generateEmptyController() on Generator 🤔

}

$controllerSource = $controllerExists ? file_get_contents($controllerPath) : $generator->getFileContentsForPendingOperation($controllerPath);

$manipulator = new ClassSourceManipulator($controllerSource);

$this->securityControllerBuilder->addJsonLoginMethod($manipulator, $userClassDetails);

$securityData = $this->securityConfigUpdater->updateForJsonLogin($this->ysm->getContents(), $this->firewallToUpdate, 'app_api_login');

if ($this->willLogout) {
$this->securityControllerBuilder->addLogoutMethod($manipulator);

$securityData = $this->securityConfigUpdater->updateForLogout($securityData, $this->firewallToUpdate);
}

$generator->dumpFile(self::SECURITY_CONFIG_PATH, $securityData);
$generator->dumpFile($controllerPath, $manipulator->getSourceCode());

$generator->writeChanges();

$this->writeSuccessMessage($io);

$io->text([
'Next: Make a <info>POST</info> request to <info>/api/login</info> with a <info>username</info> and <info>password</info> to login.',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user also needs to set Content-Type: application/json iirc. This is sometimes a "gotcha", so it would be nice to mention it here.

'Then: The security system intercepts the requests and authenticates the user.',
sprintf('And Finally: The <info>%s::apiLogin</info> method creates and returns a JsonResponse.', $controllerNameDetails->getShortName()),
]);
}
}
7 changes: 7 additions & 0 deletions src/Resources/config/makers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -147,5 +147,12 @@
<argument type="service" id="maker.security_controller_builder" />
<tag name="maker.command" />
</service>

<service id="maker.maker.make_json_login" class="Symfony\Bundle\MakerBundle\Maker\Security\MakeJsonLogin">
<argument type="service" id="maker.file_manager" />
<argument type="service" id="maker.security_config_updater" />
<argument type="service" id="maker.security_controller_builder" />
<tag name="maker.command" />
</service>
</services>
</container>
9 changes: 9 additions & 0 deletions src/Resources/help/security/MakeJsonLogin.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The <info>%command.name%</info> command generates a controller to allow users to
login using the json_login authenticator.

The controller name, and logout ability can be customized by answering the
questions asked when running <info>%command.name%</info>.

This will also update your <info>security.yaml</info> for the new authenticator.

<info>php %command.full_name%</info>
9 changes: 9 additions & 0 deletions src/Resources/skeleton/EmptyController.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?= "<?php\n" ?>

namespace <?= $namespace; ?>;

<?= $use_statements; ?>

class <?= $controller_name ?> extends AbstractController
{
}
Loading