Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP][SYMFONY2] Rejestracja użytkowników
Forum PHP.pl > Forum > Przedszkole
kosmos
Skorzystałem z MANUALA i rejestruję użytkowników w taki sposób:

Account Controller
  1. <?php
  2. // src/Acme/LogowanieBundle/Controller/AccountController.php;
  3. namespace Acme\LogowanieBundle\Controller;
  4.  
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Acme\LogowanieBundle\Form\Type\RegistrationType;
  7. use Acme\LogowanieBundle\Form\Model\Registration;
  8. use Symfony\Component\HttpFoundation\Request;
  9.  
  10.  
  11. class AccountController extends Controller
  12. {
  13. public function registerAction()
  14. {
  15. $registration = new Registration();
  16. $form = $this->createForm(new RegistrationType(), $registration, array(
  17. 'action' => $this->generateUrl('account_create'),
  18. ));
  19.  
  20. return $this->render(
  21. 'AcmeLogowanieBundle:Account:register.html.twig',
  22. array('form' => $form->createView())
  23. );
  24. }
  25.  
  26. public function createAction(Request $request)
  27. {
  28. $em = $this->getDoctrine()->getManager();
  29.  
  30. $form = $this->createForm(new RegistrationType(), new Registration());
  31.  
  32. $form->handleRequest($request);
  33.  
  34. if ($form->isValid()) {
  35. $registration = $form->getData();
  36.  
  37. $em->persist($registration->getUser());
  38. $em->flush();
  39.  
  40. // return $this->redirect('');
  41. }
  42.  
  43. return $this->render(
  44. 'AcmeLogowanieBundle:Account:register.html.twig',
  45. array('form' => $form->createView())
  46. );
  47. }
  48.  
  49. }


Registration.php
  1. <?php
  2. // src/Acme/LogowanieBundle/Controller/AccountController.php;
  3. namespace Acme\LogowanieBundle\Controller;
  4.  
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Acme\LogowanieBundle\Form\Type\RegistrationType;
  7. use Acme\LogowanieBundle\Form\Model\Registration;
  8. use Symfony\Component\HttpFoundation\Request;
  9.  
  10.  
  11. class AccountController extends Controller
  12. {
  13. public function registerAction()
  14. {
  15. $registration = new Registration();
  16. $form = $this->createForm(new RegistrationType(), $registration, array(
  17. 'action' => $this->generateUrl('account_create'),
  18. ));
  19.  
  20. return $this->render(
  21. 'AcmeLogowanieBundle:Account:register.html.twig',
  22. array('form' => $form->createView())
  23. );
  24. }
  25.  
  26. public function createAction(Request $request)
  27. {
  28. $em = $this->getDoctrine()->getManager();
  29.  
  30. $form = $this->createForm(new RegistrationType(), new Registration());
  31.  
  32. $form->handleRequest($request);
  33.  
  34. if ($form->isValid()) {
  35. $registration = $form->getData();
  36.  
  37. $em->persist($registration->getUser());
  38. $em->flush();
  39.  
  40. // return $this->redirect('');
  41. }
  42.  
  43. return $this->render(
  44. 'AcmeLogowanieBundle:Account:register.html.twig',
  45. array('form' => $form->createView())
  46. );
  47. }
  48.  
  49. }


RegistrationType.php
  1. <?php
  2. // src/Acme/LogowanieBundle/Controller/AccountController.php;
  3. namespace Acme\LogowanieBundle\Controller;
  4.  
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Acme\LogowanieBundle\Form\Type\RegistrationType;
  7. use Acme\LogowanieBundle\Form\Model\Registration;
  8. use Symfony\Component\HttpFoundation\Request;
  9.  
  10.  
  11. class AccountController extends Controller
  12. {
  13. public function registerAction()
  14. {
  15. $registration = new Registration();
  16. $form = $this->createForm(new RegistrationType(), $registration, array(
  17. 'action' => $this->generateUrl('account_create'),
  18. ));
  19.  
  20. return $this->render(
  21. 'AcmeLogowanieBundle:Account:register.html.twig',
  22. array('form' => $form->createView())
  23. );
  24. }
  25.  
  26. public function createAction(Request $request)
  27. {
  28. $em = $this->getDoctrine()->getManager();
  29.  
  30. $form = $this->createForm(new RegistrationType(), new Registration());
  31.  
  32. $form->handleRequest($request);
  33.  
  34. if ($form->isValid()) {
  35. $registration = $form->getData();
  36.  
  37. $em->persist($registration->getUser());
  38. $em->flush();
  39.  
  40. // return $this->redirect('');
  41. }
  42.  
  43. return $this->render(
  44. 'AcmeLogowanieBundle:Account:register.html.twig',
  45. array('form' => $form->createView())
  46. );
  47. }
  48.  
  49. }


UserType.php
  1. <?php
  2.  
  3. // src/Acme/LogowanieBundle/Form/Type/UserType.php
  4. namespace Acme\LogowanieBundle\Form\Type;
  5.  
  6. use Symfony\Component\Form\AbstractType;
  7. use Symfony\Component\Form\FormBuilderInterface;
  8. use Symfony\Component\OptionsResolver\OptionsResolverInterface;
  9.  
  10. class UserType extends AbstractType
  11. {
  12. public function buildForm(FormBuilderInterface $builder, array $options)
  13. {
  14. $builder->add('username','text');
  15. $builder->add('email_address', 'email');
  16. $builder->add('role','text');
  17. $builder->add('Password', 'repeated', array(
  18. 'first_name' => 'password',
  19. 'second_name' => 'confirm',
  20. 'type' => 'password',
  21. ));
  22. }
  23.  
  24.  
  25.  
  26. public function setDefaultOptions(OptionsResolverInterface $resolver)
  27. {
  28. $resolver->setDefaults(array(
  29. 'data_class' => 'Acme\LogowanieBundle\Entity\User'
  30. ));
  31. }
  32.  
  33. public function getName()
  34. {
  35. return 'user';
  36. }
  37. }


User.php
  1. <?php
  2.  
  3. namespace Acme\LogowanieBundle\Entity;
  4.  
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. use Doctrine\ORM\Mapping as ORM;
  7.  
  8. /**
  9.   * Users
  10.   *
  11.   * @ORM\Table(name="user")
  12.   * @ORM\Entity
  13.   */
  14. class User implements UserInterface
  15. {
  16. /**
  17.   * @var integer
  18.   *
  19.   * @ORM\Column(name="id_user", type="integer")
  20.   * @ORM\id
  21.   * @ORM\GeneratedValue(strategy="AUTO")
  22.   */
  23. private $id_user;
  24.  
  25. /**
  26.   * @var string
  27.   *
  28.   * @ORM\Column(name="username", type="string", length=25)
  29.   */
  30. private $username;
  31.  
  32. /**
  33.   * @var string
  34.   *
  35.   * @ORM\Column(name="salt", type="string", length=32)
  36.   */
  37. private $salt;
  38.  
  39. /**
  40.   * @var string
  41.   *
  42.   * @ORM\Column(name="password", type="string", length=40)
  43.   */
  44. private $password;
  45.  
  46. /**
  47.   * @var string
  48.   *
  49.   * @ORM\Column(name="email_address", type="string", length=60)
  50.   */
  51. private $emailAddress;
  52.  
  53. /**
  54.   * @var string
  55.   *
  56.   * @ORM\Column(name="role", type="string", length=20)
  57.   */
  58. public $role;
  59.  
  60.  
  61.  
  62.  
  63.  
  64. public function __construct()
  65. {
  66. // $this->isActive = true;
  67. $this->salt = md5(uniqid(null, true));
  68.  
  69. }
  70.  
  71.  
  72. /**
  73.   * Get id_user
  74.   *
  75.   * @return integer
  76.   */
  77. public function getId()
  78. {
  79. return $this->id_user;
  80. }
  81.  
  82. /**
  83.   * Set username
  84.   *
  85.   * @param string $username
  86.   * @return Users
  87.   */
  88. public function setUsername($username)
  89. {
  90. $this->username = $username;
  91.  
  92. return $this;
  93. }
  94.  
  95. /**
  96.   * Get username
  97.   *
  98.   * @return string
  99.   */
  100. public function getUsername()
  101. {
  102. return $this->username;
  103. }
  104.  
  105. /**
  106.   * Set salt
  107.   *
  108.   * @param string $salt
  109.   * @return Users
  110.   */
  111. public function setSalt($salt)
  112. {
  113. $this->salt = $salt;
  114.  
  115. return $this;
  116. }
  117.  
  118. /**
  119.   * Get salt
  120.   *
  121.   * @return string
  122.   */
  123. public function getSalt()
  124. {
  125. return $this->salt;
  126. }
  127.  
  128. /**
  129.   * Set password
  130.   *
  131.   * @param string $password
  132.   * @return Users
  133.   */
  134. public function setPassword($password)
  135. {
  136.  
  137. $this->password = $password;
  138. return $this;
  139. }
  140.  
  141. /**
  142.   * Get password
  143.   *
  144.   * @return string
  145.   */
  146. public function getPassword()
  147. {
  148. return $this->password;
  149. }
  150.  
  151. /**
  152.   * Set emailAddress
  153.   *
  154.   * @param string $emailAddress
  155.   * @return Users
  156.   */
  157. public function setEmailAddress($emailAddress)
  158. {
  159. $this->emailAddress = $emailAddress;
  160.  
  161. return $this;
  162. }
  163.  
  164. /**
  165.   * Get emailAddress
  166.   *
  167.   * @return string
  168.   */
  169. public function getEmailAddress()
  170. {
  171. return $this->emailAddress;
  172. }
  173.  
  174. /**
  175.   * Set role
  176.   *
  177.   * @param string $role
  178.   * @return Users
  179.   */
  180. public function setRoles($role)
  181. {
  182. $this->role = $role;
  183.  
  184. return $this;
  185. }
  186.  
  187. /**
  188.   * Get role
  189.   *
  190.   * @return string
  191.   */
  192. public function getRoles()
  193. {
  194. return array('ROLE_SUPER_ADMIN');
  195. // return $this->role;
  196. }
  197.  
  198.  
  199. /**
  200.   * @inheritDoc
  201.   */
  202. public function eraseCredentials() {}
  203. }


Opis problemu:
Użytkownicy są dodawani do BD ale nie mam funkcjonalności haszowania haseł. Prosiłbym o wskazanie, gdzie mógłbym w sposób poprawny takie haszowanie ustawiać i nakierowanie na to jak to zrobić. Do tej pory dodawałem testowo użytkowników w taki sposób:
  1. public function dodajAction(){
  2.  
  3. $user = new User();
  4. $factory = $this->container->get('security.encoder_factory');
  5. $encoder = $factory->getEncoder($user);
  6. $pwd = $encoder->encodePassword('zenek', $user->getSalt());
  7. $user->setUsername('zenek');
  8. $user->setEmailAddress('exampleas@example.com');
  9. $user->setRoles('ROLE_SUPER_ADMIN');
  10. $user->setSalt($user->getSalt());
  11. $user->setPassword($pwd);
  12.  
  13. $em = $this->getDoctrine()->getManager();
  14. $em->persist($user);
  15. $em->flush();
  16.  
  17. return $this->render('AcmeLogowanieBundle:Default:dodano.html.twig');
  18.  
  19.  
  20. }
gorden
jak wygląda metoda encodePassword questionmark.gif i dlaczego w jej argumencie podałeś nazwę użytkownika? w niej powinno być coś takiego
  1. return hashingAlgorithm( $password . $salt )

z tej metody korzstaj wszędzie gdzie użytkownik się autoryzuje (logowanie, zmiana hasła, etc)

samym salt może być nazwa użytkownika, albo jakiś randomowy ciąg znaków jak w Twoim przypadku, który będziesz trzymać w bazie
pedro84
@gorden - OP używa encodera poprawnie. A ta nazwa usera, to jest pewnie testowe hasło.

@kosmos - encoder w pliku security.yml nie jest czasem ustawiony na plain?
kosmos
@gorden
Ostatni przytoczony przeze mnie kod dotyczy testowego dodawania userów do bazy danych.
Mógłbyś przytczyć jakiśdokładniejszy przykład wykorzystania encodera?

@pedro84

  1. encoders:
  2. Acme\LogowanieBundle\Entity\User:
  3. algorithm: sha1
  4. encode_as_base64: false
  5. iterations: 1


pedro84
Jak dodasz usera to bazy w ten sposób, to hasło jest czyste czy haszowane?
  1. $user = new User();
  2. $factory = $this->container->get('security.encoder_factory');
  3. $encoder = $factory->getEncoder($user);
  4. $pwd = $encoder->encodePassword('zenek', $user->getSalt());
  5. $user->setUsername('zenek');
  6. $user->setEmailAddress('exampleas@example.com');
  7. $user->setRoles('ROLE_SUPER_ADMIN');
  8. $user->setSalt($user->getSalt());
  9. $user->setPassword($pwd);
  10.  
  11. $em = $this->getDoctrine()->getManager();
  12. $em->persist($user);
  13. $em->flush();


Sam encoder
  1. $hash = $this->encoderFactory->getEncoder($user)->encodePassword($plaintextPassword, 'SALT');
powinien Ci w tym miejscu zwrócić hash. Czyściłeś cache?
kosmos
Tak, jeśli dodam użytkownika w ten sposób to hasła są haszowane poprawnie (później mogę się elegancko zalogować na usera), ale jak wiadomo nie mogę tego tak zostawić smile.gif Ponieważ chcę dodawać ich z formularza rejestracyjnego. Więc zapewne muszę dopisać metodę w pliku registration.php?
Pamięć cache wyczyściłem przed chwilką.

Crozin
  1. if ($form->isValid()) {
  2. $registration = $form->getData();
  3.  
  4. $em->persist($registration->getUser());
  5. $em->flush();
  6.  
  7. // return $this->redirect('');
  8. }
Nigdzie tutaj nie widać kodu związanego z hashowaniem, więc o ile nie robi tego jakiś poboczny kod (np. jakieś zdarzenie) to nie ma powodu by oczekiwać w bazie czegoś poza czystym hasłem.
kosmos
@Crozin
nie spodziewam się po obecnym kodzie zahaszowanego hasła smile.gif Chcę go zmienić aby takie haszowanie wprowadzić.
W testowym wprowadzaniu userów, udało mi się to zaimplementować, ale w przypadku rejestracji poprzez formlarz mam problem.
Crozin
No to musisz je najzwyczajniej w świecie dodać. Mniej-więcej coś takiego:
  1. if ($form->isValid()) {
  2. $user = $form->getData()->getUser();
  3. $user->setPassword($this->encoderFactory->getEncoder($user)->encodePassword($form->getData()->getPassword(), $user->getSalt()));
  4.  
  5. $em->persist($user);
  6. $em->flush();
  7.  
  8. // return $this->redirect('');
  9. }

Kilka dobrych rad na przyszłość:
- najprawdopodobniej powinieneś mieć osobny obiekt na dane z formularza rejestracyjnego na podstawie którego dopiero utworzysz obiekt użytkownika - operujesz na innych danych w obu przypadkach,
- powinieneś mieć dedykowaną usługę do zarządzania użytkownikami - bezpośrednie użycie Doctrine czy hashowania hasła w kontrolerze to zły pomysł,
- hasło lepiej jest hashować jakimś blowfishem niż SHA-1.
kosmos
Nie użyję tego kodu.
Korzystam z metody createForm klasy Controller.
  1. public function registerAction()
  2. {
  3. $registration = new Registration();
  4. $form = $this->createForm(new RegistrationType(), $registration, array(
  5. 'action' => $this->generateUrl('account_create'),
  6. ));
  7.  
  8. return $this->render(
  9. 'AcmeLogowanieBundle:Account:register.html.twig',
  10. array('form' => $form->createView())
  11. );
  12. }

Nie chcę tworzyć i wywoływać osobnej metody która ponownie odwoła sie do obiketu user`a w celu zahaszowanie hasła.
Poszukuję rozwiązania jak wpleść haszowanie w kod który podałem w pierwszym poście.

Może to wydawać się banalne ale jestem początkujący w Symfony stąd temat w dziale o przedszkolakach smile.gif
Damonsson
Ale co ma tworzenie forma, do obsługi jego?

Masz metodę createAction i tam dodajesz jedną linijkę, którą podał Ci kolega wyżej.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.