Dieses Blog durchsuchen

Sonntag, 10. Juli 2016

Symfony 3.1 Add a encrypted passwordfield to your entity, controller and Form

If you have a passwordfield in your database you have to encrypt the passwordbefpre you can save it.

this task is pretty straight forward in symfony 3.1

Once you have created your entity (f. i BlogBundle\Entity\Users)
You have to implement the core security user  interface  to make the entity compatible to the encoder class. See my class to understand the mechanism:
<?php
namespace BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Users
*
* @ORM\Table(name="users")
* @ORM\Entity
*/
class Users implements \Symfony\Component\Security\Core\User\UserInterface
{
/**
* @var string
*
* @ORM\Column(name="firstname", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* @var string
*
* @ORM\Column(name="lastame", type="string", length=255, nullable=true)
*/
private $lastame;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=50, nullable=true)
*/
private $username;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255, nullable=true)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255, nullable=true)
*/
private $password;
/**
* @var \DateTime
*
* @ORM\Column(name="created", type="datetime", nullable=true)
*/
private $created;
/**
* @var \DateTime
*
* @ORM\Column(name="updated", type="datetime", nullable=true)
*/
private $updated;
/**
* @var integer
*
* @ORM\Column(name="isDeleted", type="integer", nullable=true)
*/
private $isdeleted;
/**
* @var integer
*
* @ORM\Column(name="isActive", type="integer", nullable=true)
*/
private $isactive;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* Set firstname
*
* @param string $firstname
*
* @return Users
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastame
*
* @param string $lastame
*
* @return Users
*/
public function setLastame($lastame)
{
$this->lastame = $lastame;
return $this;
}
/**
* Get lastame
*
* @return string
*/
public function getLastame()
{
return $this->lastame;
}
/**
* Set username
*
* @param string $username
*
* @return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set email
*
* @param string $email
*
* @return Users
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* @param string $password
*
* @return Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set created
*
* @param \DateTime $created
*
* @return Users
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* @param \DateTime $updated
*
* @return Users
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set isdeleted
*
* @param integer $isdeleted
*
* @return Users
*/
public function setIsdeleted($isdeleted)
{
$this->isdeleted = $isdeleted;
return $this;
}
/**
* Get isdeleted
*
* @return integer
*/
public function getIsdeleted()
{
return $this->isdeleted;
}
/**
* Set isactive
*
* @param integer $isactive
*
* @return Users
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* @return integer
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* @return (Role|string)[] The user roles
*/
public function getRoles()
{
return array('ROLE_USER');
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


Implement interfacemethods
You have to implement the last 2 methods (see class above) to fullfill the contract.

Modify security:
open app/config/security and add encoder like this:

# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
encoders:
Blogbundle\Entity\Users:
algorithm: bcrypt
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
in_memory:
memory: ~
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
# activate different ways to authenticate
# http_basic: ~
# http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate
# form_login: ~
# http://symfony.com/doc/current/cookbook/security/form_login_setup.html
view raw gistfile1.txt hosted with ❤ by GitHub
clear cache after that

Add encoder to your user-controller
/**
* Displays a form to edit an existing Users entity.
*
* @Route("/{id}/edit", name="users_edit")
* @Method({"GET", "POST"})
*/
public function editAction(Request $request, Users $user)
{
$deleteForm = $this->createDeleteForm($user);
$editForm = $this->createForm('BlogBundle\Form\UsersType', $user);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
// 3) Encode the password (you could also do this via Doctrine listener)
$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Edited Successfully!');
return $this->redirectToRoute('users_edit', array('id' => $user->getId()));
}
return $this->render('users/edit.html.twig', array(
'user' => $user,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
view raw gistfile1.txt hosted with ❤ by GitHub


Add password and password confirmation field to your crud form
<?php
namespace BlogBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class UsersType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname')
->add('lastame')
->add('username')
->add('email', EmailType::class)
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password')))
->add('created')
->add('updated')
->add('isdeleted')
->add('isactive')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BlogBundle\Entity\Users'
));
}
public function getBlockPrefix()
{
return 'blogbundle_users';
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


thats it

Keine Kommentare:

Kommentar veröffentlichen