Skip to content

Commit

Permalink
Add password field to User entity
Browse files Browse the repository at this point in the history
  • Loading branch information
bocharsky-bw committed Jul 20, 2016
1 parent 22eb564 commit 2074dde
Show file tree
Hide file tree
Showing 12 changed files with 156 additions and 5 deletions.
2 changes: 2 additions & 0 deletions app/DoctrineMigrations/Version20160720094920.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public function up(Schema $schema)
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

$this->addSql('RENAME TABLE `user` TO `user_table`');
$this->addSql('ALTER TABLE user_table RENAME INDEX uniq_8d93d649f85e0677 TO UNIQ_14EB741EF85E0677');
}

/**
Expand All @@ -30,5 +31,6 @@ public function down(Schema $schema)
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

$this->addSql('RENAME TABLE `user_table` TO `user`');
$this->addSql('ALTER TABLE user_table RENAME INDEX UNIQ_14EB741EF85E0677 TO uniq_8d93d649f85e0677');
}
}
34 changes: 34 additions & 0 deletions app/DoctrineMigrations/Version20160720100543.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160720100543 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

$this->addSql('ALTER TABLE user_table ADD password VARCHAR(255) NOT NULL');
}

/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

$this->addSql('ALTER TABLE user_table DROP password');
}
}
17 changes: 17 additions & 0 deletions app/Resources/views/base.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@
</div>
<div class="container">
<div class="col-xs-12">
{% if app.session.started and app.session.flashBag.peekAll is not empty %}
<div class="messages">
{% for type, messages in app.session.flashBag.all %}
{% for message in messages %}
{# Bootstrap alert, see http://getbootstrap.com/components/#alerts #}
<div class="alert alert-dismissible alert-{{ type }}" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>

{{ message|trans }}
</div>
{% endfor %}
{% endfor %}
</div>
{% endif %}

{% block content %}
{% endblock %}
</div>
Expand Down
2 changes: 2 additions & 0 deletions app/config/security.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
encoders:
AppBundle\Entity\User: bcrypt

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
Expand Down
8 changes: 7 additions & 1 deletion app/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,10 @@ services:

app.form_login_authenticator:
class: AppBundle\Security\FormLoginAuthenticator
arguments: ['@doctrine.orm.entity_manager']
arguments: ['@doctrine.orm.entity_manager', '@security.password_encoder', '@router']

app.user_password_listener:
class: AppBundle\Doctrine\UserPasswordListener
arguments: ['@security.password_encoder']
tags:
- { name: doctrine.event_listener, event: prePersist }
2 changes: 2 additions & 0 deletions src/AppBundle/Controller/Admin/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public function updateBlogPostAction(Request $request, $id)
if ($form->isValid()) {
$this->getDoctrine()->getManager()->flush();

$this->addFlash('success', 'Blog post successfully saved!');

return $this->redirectToRoute('admin_blog_show');
}

Expand Down
4 changes: 4 additions & 0 deletions src/AppBundle/Controller/SecurityController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class SecurityController extends Controller
*/
public function loginAction()
{
if ($this->getUser()) {
$this->addFlash('warning', 'You\'re already logged in.');
}

$form = $this->createForm(UserLoginType::class, null, [
'action' => $this->generateUrl('security_check'),
]);
Expand Down
1 change: 1 addition & 0 deletions src/AppBundle/DataFixtures/ORM/LoadUserData.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public function load(ObjectManager $manager)
{
$user = new User();
$user->setUsername('victor');
$user->setPlainPassword('victorpass');

$manager->persist($user);
$manager->flush();
Expand Down
30 changes: 30 additions & 0 deletions src/AppBundle/Doctrine/UserPasswordListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace AppBundle\Doctrine;

use AppBundle\Entity\User;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;

class UserPasswordListener
{
private $encoder;

public function __construct(UserPasswordEncoder $encoder)
{
$this->encoder = $encoder;
}

public function prePersist(LifecycleEventArgs $event)
{
$user = $event->getEntity();
if (!$user instanceof User) {
return null;
}
if ($user->getPlainPassword()) {
// encode password
$encodedPassword = $this->encoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encodedPassword);
}
}
}
41 changes: 40 additions & 1 deletion src/AppBundle/Entity/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ class User implements UserInterface
*/
private $username;

/**
* @var string
*
* @ORM\Column(type="string")
*/
private $password;

/**
* @var string
*/
private $plainPassword;

/**
* @return int
*/
Expand All @@ -53,9 +65,36 @@ public function getRoles()
return ['ROLE_USER'];
}

/**
* @param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}

/**
* @return string
*/
public function getPassword()
{
// TODO: Implement getPassword() method.
return $this->password;
}

/**
* @return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}

/**
* @param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
}

public function getSalt()
Expand Down
4 changes: 4 additions & 0 deletions src/AppBundle/Form/UserLoginType.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

Expand All @@ -13,6 +14,9 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('plain_password', PasswordType::class, [
'label' => 'Password',
])
;
}

Expand Down
16 changes: 13 additions & 3 deletions src/AppBundle/Security/FormLoginAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

use AppBundle\Entity\User;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
Expand All @@ -14,10 +17,14 @@
class FormLoginAuthenticator extends AbstractGuardAuthenticator
{
private $em;
private $encoder;
private $router;

public function __construct(EntityManager $em)
public function __construct(EntityManager $em, UserPasswordEncoder $encoder, RouterInterface $router)
{
$this->em = $em;
$this->encoder = $encoder;
$this->router = $router;
}

public function getCredentials(Request $request)
Expand All @@ -26,6 +33,7 @@ public function getCredentials(Request $request)
if ($request->request->has('username')) {
return [
'username' => $request->request->get('username'),
'password' => $request->request->get('plain_password'),
];
}
}
Expand All @@ -42,7 +50,7 @@ public function getUser($credentials, UserProviderInterface $userProvider)

public function checkCredentials($credentials, UserInterface $user)
{
return true;
return $this->encoder->isPasswordValid($user, $credentials['password']);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
Expand All @@ -52,7 +60,9 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
$url = $this->router->generate('admin_blog_show');

return new RedirectResponse($url);
}

public function supportsRememberMe()
Expand Down

0 comments on commit 2074dde

Please sign in to comment.