Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[User - WIP] add the user generator. #41

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions src/Command/MakeUserCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
* This file is part of the Symfony 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\Command;

use Doctrine\ORM\Mapping\Column;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Component\Console\Input\InputArgument;

/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
* @author Ryan Weaver <weaverryan@gmail.com>
* @author Amrouche Hamza <hamza.simperfit@gmail.com>
*/
final class MakeUserCommand extends AbstractCommand
{
protected static $defaultName = 'make:user';

public function configure()
{
$this
->setDescription('Creates a the user doctrine class, the user provider and the user repository')
Copy link
Member

Choose a reason for hiding this comment

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

Obviously, we want to make these commands as simple, and not interactive as possible (i.e. don't ask the user 10 questions). But, I think one question might make sense here:

Do you need to store User details in the database?

This will tell us whether or not they need a User entity, or instead, a User model class. This would also change whether or not we generate a UserProvider (or just tell them to use the built-in entity provider). And finally, it will change what recommendations we give at the end: i.e. the exact changes they'll need to make to their security.yml file.

Copy link
Member

Choose a reason for hiding this comment

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

We may also need to ask a second question... if the first question is "yes" to storing user information:

Will you need to store an encoded password for each User in the database?

This would influence how we handle the getPassword() method and whether or not we have a password field. Sometimes, even when people have a local User entity, they validate their password in a different system (e.g. via a SSO API). This is very confusing to users, so it's a great opportunity to help generate the User class correctly based on this.

->setHelp(file_get_contents(__DIR__.'/../Resources/help/MakeUser.txt'))
;
}

protected function getParameters(): array
{
return [];
}

protected function getFiles(array $params): array
{
return [
__DIR__.'/../Resources/skeleton/user/User.php.txt' => 'src/Entity/User.php',
__DIR__.'/../Resources/skeleton/user/UserRepository.php.txt' => 'src/Repository/UserRepository.php',
__DIR__.'/../Resources/skeleton/user/UserProvider.php.txt' => 'src/Security/UserProvider.php',
];
}

protected function getResultMessage(array $params): string
{
return 'User entity, User provider and user repository has been created successfully.';
}

protected function writeNextStepsMessage(array $params, ConsoleStyle $io)
{
$io->text([
'Next: Add more fields to your entity and start using it.',
'Find the documentation at <fg=yellow>https://symfony.com/doc/current/doctrine.html#creating-an-entity-class</>'
]);
}

protected function configureDependencies(DependencyBuilder $dependencies)
{
$dependencies->addClassDependency(
Column::class,
'orm'
);
$dependencies->addClassDependency(
UserProviderInterface::class,
'security'
);
}
}
5 changes: 5 additions & 0 deletions src/Resources/help/MakeUser.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
The <info>%command.name%</info> command generates the whole suites to create users and to have roles.

<info>php %command.full_name%</info>

If the argument is missing, the command will ask for the entity class name interactively.
72 changes: 72 additions & 0 deletions src/Resources/skeleton/user/User.php.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;

/**
* {@inheritdoc}
*/
public function getRoles()
{
return $this->roles;
}

public function setRoles(array $roles)
{
$this->roles = $roles;

return $this;
}

/**
* {@inheritdoc}
*/
public function eraseCredentials()
{
}

/**
* {@inheritdoc}
*/
public function getUsername(): string
{
return $this->email;
Copy link
Contributor

Choose a reason for hiding this comment

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

where does email come from?

}

/**
* {@inheritdoc}
*/
public function getSalt()
{
return null;
}

/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize([
$this->id,
Copy link
Member

Choose a reason for hiding this comment

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

not serializing the username will cause issues (incompatible with the remember me)

Copy link
Author

Choose a reason for hiding this comment

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

As i'm not using this feature I was not thinking about it, I understand, I will add it.

]);
}

/**
* {@inheritdoc}
*/
public function unserialize($serialized)
{
[$this->id] = unserialize($serialized);
}
}
81 changes: 81 additions & 0 deletions src/Resources/skeleton/user/UserProvider.php.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace App\Security\User;

use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\NoResultException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class UserProvider implements UserProviderInterface
Copy link
Member

Choose a reason for hiding this comment

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

If we know the user wants an "entity" provider, then does it make sense to generate this class? They could just use the built-in entity provider.

{
protected $userRepository;

public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}

/**
* {@inheritdoc}
*/
public function loadUserByUsername($username): User
{
try {
$user = $this->userRepository->findOneByUsername($username);
} catch (NoResultException $exception) {
throw new UsernameNotFoundException(sprintf('The user "%s" does not exist.', $username));
}

return $user;
}

/**
* @throws UsernameNotFoundException if the user is not found
*/
public function loadUserByResourceOwner($resourceOwner, string $provider): UserInterface
Copy link
Member

Choose a reason for hiding this comment

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

does not make any sense in core (this is specific to HWIOAuthBundle AFAICT)

{
try {
$user = $this->userRepository->findOneByResourceOwnerId($resourceOwner->getId(), $provider);
} catch (NoResultException $exception) {
return $this->updateUserWithResourceOwnerId($resourceOwner, $provider);
}

return $user;
}

/**
* @throws UnsupportedUserException
*/
public function refreshUser(UserInterface $user)
{
throw new UnsupportedUserException();
}

/**
* {@inheritdoc}
*/
public function supportsClass($class): bool
{
return User::class === $class;
}

/**
* @throws UsernameNotFoundException
*/
private function updateUserWithResourceOwnerId($resourceOwner, string $provider): UserInterface
{
try {
$user = $this->loadUserByUsername($resourceOwner->getEmail());
} catch (UsernameNotFoundException $exception) {
throw new UsernameNotFoundException(sprintf('The user "%s" does not exist.', $resourceOwner->getId()));
}

$this->userRepository->updateResourceOwnerId($user, $resourceOwner->getId(), $provider);

return $user;
}
}
34 changes: 34 additions & 0 deletions src/Resources/skeleton/user/UserRepository.php.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
public function findOneByUsername(string $username): User
{
return $this->createQueryBuilder('u')
->where('u.email = :username')
->setParameter('username', mb_strtolower($username))
->getQuery()
->getSingleResult();
}

public function findOneByResourceOwnerId(string $resourceOwnerId, string $provider): User
{
return $this->createQueryBuilder('u')
->where('u.'.$provider.'Id = :resourceOwnerId')
->setParameter('resourceOwnerId', $resourceOwnerId)
->getQuery()
->getSingleResult();
}

public function updateResourceOwnerId(User $user, string $resourceOwnerId, string $provider)
{
$user->{'set'.ucfirst($provider).'Id'}($resourceOwnerId);

$this->add($user, true);
}
}