Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [Symfony]Logowanie na podstawie bazy danych
PawelC
post 20.02.2018, 23:29:11
Post #1





Grupa: Zarejestrowani
Postów: 1 173
Pomógł: 121
Dołączył: 24.09.2007
Skąd: Toruń

Ostrzeżenie: (0%)
-----


Witam,
Od jakiegoś czasu męcze SF3, a dokładnie autoryzacje tylko nic mi nie idzie. Mam taki kod:
AppBundle\Entity\User

  1. <?php
  2.  
  3. namespace AppBundle\Entity;
  4.  
  5. use Doctrine\ORM\Mapping as ORM;
  6. use Symfony\Component\Security\Core\User\AdvancedUserInterface;
  7.  
  8. /**
  9.  * @ORM\Table(name="app_users")
  10.  * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
  11.  */
  12. class User implements AdvancedUserInterface, \Serializable
  13. {
  14. /**
  15.   * @ORM\Column(type="integer")
  16.   * @ORM\Id
  17.   * @ORM\GeneratedValue(strategy="AUTO")
  18.   */
  19. private $id;
  20.  
  21. /**
  22.   * @ORM\Column(type="string", length=25, unique=true)
  23.   */
  24. private $username;
  25.  
  26. /**
  27.   * @ORM\Column(type="string", length=64)
  28.   */
  29. private $password;
  30.  
  31. /**
  32.   * @ORM\Column(type="string", length=60, unique=true)
  33.   */
  34. private $email;
  35.  
  36. /**
  37.   * @ORM\Column(name="is_active", type="boolean")
  38.   */
  39. private $isActive;
  40.  
  41. public function __construct()
  42. {
  43. $this->isActive = true;
  44. // may not be needed, see section on salt below
  45. // $this->salt = md5(uniqid('', true));
  46. }
  47.  
  48. public function getUsername()
  49. {
  50. return $this->username;
  51. }
  52.  
  53. public function getSalt()
  54. {
  55. // you *may* need a real salt depending on your encoder
  56. // see section on salt below
  57. return null;
  58. }
  59.  
  60. public function getPassword()
  61. {
  62. return $this->password;
  63. }
  64.  
  65. public function getRoles()
  66. {
  67. return array('ROLE_USER');
  68. }
  69.  
  70. public function eraseCredentials()
  71. {
  72. }
  73.  
  74. public function isAccountNonExpired()
  75. {
  76. return true;
  77. }
  78.  
  79. public function isAccountNonLocked()
  80. {
  81. return true;
  82. }
  83.  
  84. public function isCredentialsNonExpired()
  85. {
  86. return true;
  87. }
  88.  
  89. public function isEnabled()
  90. {
  91. return $this->isActive;
  92. }
  93.  
  94. /** @see \Serializable::serialize() */
  95. public function serialize()
  96. {
  97. return serialize(array(
  98. $this->id,
  99. $this->username,
  100. $this->password,
  101. $this->isActive,
  102. // see section on salt below
  103. // $this->salt,
  104. ));
  105. }
  106.  
  107. /** @see \Serializable::unserialize() */
  108. public function unserialize($serialized)
  109. {
  110. list (
  111. $this->id,
  112. $this->username,
  113. $this->password,
  114. $this->isActive,
  115. // see section on salt below
  116. // $this->salt
  117. ) = unserialize($serialized);
  118. }
  119. }

  1. security.yml

Kod
# app/config/security.yml
security:
    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt

    # ...

    providers:
        our_db_provider:
            entity:
                class: AppBundle:User
                property: username
                # if you're using multiple entity managers
                # manager_name: customer

    firewalls:
        main:
            pattern:    ^/
            http_basic: ~
            provider: our_db_provider

    # ...


DefaultController
  1. <?php
  2.  
  3. namespace AppBundle\Controller;
  4.  
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  6. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9.  
  10. class DefaultController extends Controller
  11. {
  12. /**
  13.   * @Route("/", name="homepage")
  14.   */
  15. public function indexAction(Request $request)
  16. {
  17. // replace this example code with whatever you need
  18. return $this->render('default/index.html.twig', [
  19. 'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
  20. ]);
  21. }
  22.  
  23. /**
  24.   * @Route("/admin")
  25.   */
  26. public function adminAction()
  27. {
  28. return new Response('<html><body>Admin page!</body></html>');
  29. }
  30. }


ładuje się przez przeglądarkę na adres /admin, po zalogowaniu powinno mi pokazać Admin Page! niestety u mnie po podaniu prawidłowych danych admin/admin i kliknięciu zaloguj się, ponownie pokazuje się formularz logowania. Co robię nie tak? Wszystko robiłem zgodnie z tym poradnikiem https://symfony.com/doc/3.4/security/entity_provider.html

Od 3h nad tym siedzę i brak efektu sad.gif
Go to the top of the page
+Quote Post
aras785
post 21.02.2018, 11:12:11
Post #2





Grupa: Zarejestrowani
Postów: 859
Pomógł: 177
Dołączył: 29.10.2009

Ostrzeżenie: (0%)
-----


Cześć, specjalnie dla Ciebie zainstalowałem sobie SF3 aby rozwiązać Twój problem tongue.gif
Nie powiem Ci gdzie masz błąd bo nie dałeś wszystkich plików (gdzie akcja z logowaniem?) ale pokaże Ci sposób w jaki sposób stworzyć prosty system autoryzacji

Jedziemy:

1. Zainstalowałem sobie symfony 3 (my_project)
2. Stworzyłem bazę w phpmyadmin (symfony3) i dodałem dane dostępowe do konfiguracji (app/config/parameters.yml)
3. Dodałem entity (src/AppBundle/Entity/User.php):

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


4. Następnie użyłem: php bin/console doctrine:schema:update --force i dodatkowo wygenerowalem gettery i settery: php bin/console doctrine:generate:entities AppBundle
5. Następnie stworzyłem kontroller do logowania,rejestracji (dane ręcznie zadeklarowane do testów), sprawdzenia czy jest zalogowany (src/AppBundle/Controller/SecurityController.php):
  1. <?php
  2. namespace AppBundle\Controller;
  3.  
  4. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. use AppBundle\Entity\User;
  11.  
  12. class SecurityController extends Controller
  13. {
  14. /**
  15.   * @Route("/login", name="login")
  16.   */
  17. public function loginAction(Request $request)
  18. {
  19. return $this->render('security/login.html.twig');
  20. }
  21. /**
  22.   * @Route("/admin")
  23.   */
  24. public function adminAction()
  25. {
  26. $auth_checker = $this->get('security.authorization_checker');
  27. $token = $this->get('security.token_storage')->getToken();
  28. var_dump($token->getUser());
  29. return new Response('<html><body>Admin page!</body></html>');
  30. }
  31. /**
  32.   * @Route("/register")
  33.   */
  34. public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
  35. {
  36. $user = new User;
  37. $password = $passwordEncoder->encodePassword($user, 'admin');
  38. $user->setPassword($password);
  39. $user->setEmail('admin@admin.lc');
  40. $user->setUsername('admin');
  41. $em = $this->getDoctrine()->getManager();
  42. $em->persist($user);
  43. $em->flush();
  44.  
  45. }
  46. }

6. Dodałem widok dla logowania (app/Resources/views/security/login.html.twig):
  1. <form action="{{ path('login') }}" method="post">
  2. <label for="username">Username:</label>
  3. <input type="text" id="username" name="_username" value="" />
  4.  
  5. <label for="password">Password:</label>
  6. <input type="password" id="password" name="_password" />
  7.  
  8. {#
  9. If you want to control the URL the user
  10. is redirected to on success (more details below)
  11. <input type="hidden" name="_target_path" value="/account" />
  12. #}
  13.  
  14. <button type="submit">login</button>
  15. </form>


7. Dodałem kilka linijek do security (gdzie logowanie, gdzie ma dostep): app/config/security.yml :
  1. security:
  2. encoders:
  3. AppBundle\Entity\User:
  4. algorithm: bcrypt
  5. providers:
  6. our_db_provider:
  7. entity:
  8. class: AppBundle:User
  9. property: username
  10. firewalls:
  11. main:
  12. anonymous: ~
  13. form_login:
  14. login_path: login
  15. check_path: login
  16. access_control:
  17. - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
  18. - { path: ^/admin, roles: ROLE_USER }



Po wejściu na /admin przenosi Cię do logowania.
Jeśli jesteś zalogowany to po wejściu na /admin pokazuje Ci obiekt użytkownika zalogowanego

Daj znać czy działa smile.gif
Go to the top of the page
+Quote Post
PawelC
post 21.02.2018, 21:57:47
Post #3





Grupa: Zarejestrowani
Postów: 1 173
Pomógł: 121
Dołączył: 24.09.2007
Skąd: Toruń

Ostrzeżenie: (0%)
-----


Działa super tak jak powinno smile.gif
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 19.03.2024 - 12:57