Advertisement
Guest User

Untitled

a guest
Sep 11th, 2017
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.60 KB | None | 0 0
  1. public function loginAction(Request $request)
  2. {
  3. if ($request->get('usuario')) {
  4. $usuario = $request->get('usuario');
  5. $senha = $request->get('senha');
  6.  
  7. $user_manager = $this->getDoctrine()->getRepository('AppBundle:Usuarios');
  8. $factory = $this->get('security.encoder_factory');
  9.  
  10. $user = $user_manager->loadUserByUsername($usuario);
  11. $encoder = $factory->getEncoder($user);
  12. $salt = $user->getSalt();
  13.  
  14. if($encoder->isPasswordValid($user->getPassword(), $senha, $salt)) {
  15. return $this->redirect('/home');
  16. }
  17. else {
  18. $this->addFlash('error', 'Usuario ou senha não não encontrados!');
  19. return $this->redirect('/');
  20. }
  21. }
  22.  
  23. $authenticationUtils = $this->get('security.authentication_utils');
  24. $error = $authenticationUtils->getLastAuthenticationError();
  25. $lastUsername = $authenticationUtils->getLastUsername();
  26.  
  27. return $this->render(
  28. 'login/index.html.twig',
  29. array(
  30. 'last_username' => $lastUsername,
  31. 'error' => $error,
  32. )
  33. );
  34. }
  35.  
  36. class UserRepository extends EntityRepository implements UserLoaderInterface
  37. {
  38. public function loadUserByUsername($username)
  39. {
  40. $user = $this->createQueryBuilder('u')
  41. ->where('u.usulogin = :usulogin')
  42. ->setParameter('usulogin', $username)
  43. ->getQuery()
  44. ->getOneOrNullResult();
  45.  
  46. if (null === $user) {
  47. $message = sprintf(
  48. 'Unable to find an active admin AppBundle:User object identified by "%s".',
  49. $username
  50. );
  51. throw new UsernameNotFoundException($message);
  52. }
  53.  
  54. return $user;
  55. }
  56. }
  57.  
  58. class Usuarios implements UserInterface, Serializable
  59. {
  60. //codigos não coloquei a classe interira, apenas a implemetação da interface, para ficar menor, porem garanto estar de acordo com a doc.
  61. /**
  62. * inicio das implementações da inteface
  63. */
  64. public function getUsername()
  65. {
  66. return $this->usunom;
  67. }
  68.  
  69. public function getRoles()
  70. {
  71. return array('ROLE_ADMIN');
  72. }
  73.  
  74. public function getPassword()
  75. {
  76. return $this->ususenha;
  77. }
  78. public function getSalt()
  79. {
  80. return null;
  81. }
  82. public function eraseCredentials()
  83. {
  84. }
  85.  
  86. /** @see Serializable::serialize() */
  87. public function serialize()
  88. {
  89. return serialize(array(
  90. $this->usuid,
  91. $this->usunom,
  92. $this->ususenha,
  93. // ver la sección salt debajo
  94. // $this->salt,
  95. ));
  96. }
  97.  
  98. /** @see Serializable::unserialize() */
  99. public function unserialize($serialized)
  100. {
  101. list (
  102. $this->usuid,
  103. $this->usunom,
  104. $this->ususenha,
  105. // ver la sección salt debajo
  106. // $this->salt
  107. ) = unserialize($serialized);
  108. }
  109. }
  110.  
  111. # app/config/security.yml
  112. security:
  113. encoders:
  114. AppBundleEntityUsuarios:
  115. algorithm: bcrypt
  116.  
  117. providers:
  118. our_db_provider:
  119. entity:
  120. class: AppBundle:Usuarios
  121.  
  122. firewalls:
  123. main:
  124. provider: our_db_provider
  125.  
  126. anonymous: true
  127.  
  128. form_login:
  129. login_path: /login
  130. check_path: /
  131.  
  132. logout:
  133. path: /logout
  134. target: /login
  135.  
  136. remember_me:
  137. secret: '%secret%'
  138. lifetime: 604800 # 1 week in seconds
  139. path: /
  140.  
  141. access_control:
  142. - { path: ^/home, roles: ROLE_ADMIN }
  143. # ...
  144.  
  145. <?php
  146.  
  147. namespace AppBundleController;
  148.  
  149. use SymfonyBundleFrameworkBundleControllerController;
  150. use SensioBundleFrameworkExtraBundleConfigurationRoute;
  151. use AppBundleEntityUsuarios;
  152. use AppBundleRepositoryUserRepository;
  153. use SymfonyComponentHttpFoundationRequest;
  154. use SymfonyComponentHttpFoundationResponse;
  155. use SymfonyComponentHttpFoundationSessionSession;
  156.  
  157. class LoginController extends Controller
  158. {
  159. /**
  160. * @Route("/",name="authentication");
  161. */
  162. public function indexAction()
  163. {
  164. $authenticationUtils = $this->get('security.authentication_utils');
  165. $error = $authenticationUtils->getLastAuthenticationError();
  166. $lastUsername = $authenticationUtils->getLastUsername();
  167.  
  168. return $this->render(
  169. 'login/index.html.twig',
  170. array(
  171. 'last_username' => $lastUsername,
  172. 'error' => $error,
  173. )
  174. );
  175. }
  176.  
  177. /**
  178. * @Route("/login", name="login");
  179. */
  180. public function loginAction(Request $request)
  181. {
  182. }
  183.  
  184. /**
  185. * @Route("/logout");
  186. */
  187. public function logoutAction()
  188. {
  189. }
  190.  
  191. }
  192.  
  193. class Usuarios implements UserInterface, Serializable
  194. {
  195. /**
  196. * inicio das implementações
  197. */
  198. public function getUsername()
  199. {
  200. return $this->usunom;
  201. }
  202.  
  203. public function getRoles()
  204. {
  205. return array('ROLE_ADMIN');
  206. }
  207.  
  208. public function getPassword()
  209. {
  210. return $this->ususenha;
  211. }
  212. public function getSalt()
  213. {
  214. return null;
  215. }
  216. public function eraseCredentials()
  217. {
  218. }
  219.  
  220. /** @see Serializable::serialize() */
  221. public function serialize()
  222. {
  223. return serialize(array(
  224. $this->usuid,
  225. $this->usunom,
  226. $this->ususenha,
  227. // ver la sección salt debajo
  228. // $this->salt,
  229. ));
  230. }
  231.  
  232. /** @see Serializable::unserialize() */
  233. public function unserialize($serialized)
  234. {
  235. list (
  236. $this->usuid,
  237. $this->usunom,
  238. $this->ususenha,
  239. // ver la sección salt debajo
  240. // $this->salt
  241. ) = unserialize($serialized);
  242. }
  243. }
  244.  
  245. <?php
  246. namespace AppBundleRepository;
  247.  
  248. use SymfonyBridgeDoctrineSecurityUserUserLoaderInterface;
  249. use SymfonyComponentSecurityCoreUserUserInterface;
  250. use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
  251. use DoctrineORMEntityRepository;
  252.  
  253. class UserRepository extends EntityRepository implements UserLoaderInterface
  254. {
  255. public function loadUserByUsername($username)
  256. {
  257. $user = $this->createQueryBuilder('u')
  258. ->where('u.usulogin = :usulogin')
  259. ->setParameter('usulogin', $username)
  260. ->getQuery()
  261. ->getOneOrNullResult();
  262.  
  263. if (null === $user) {
  264. $message = sprintf(
  265. "Usuário $username, não foi encontrado!"
  266. );
  267. throw new UsernameNotFoundException($message);
  268. }
  269.  
  270. return $user;
  271. }
  272. }
  273.  
  274. ?>
  275.  
  276. <?php
  277. namespace AppBundleSecurity;
  278.  
  279. use SymfonyComponentHttpFoundationRequest;
  280. use SymfonyComponentHttpFoundationResponse;
  281. use SymfonyComponentHttpFoundationRedirectResponse;
  282. use SymfonyComponentRoutingRouterInterface;
  283. use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
  284. use SymfonyComponentSecurityCoreExceptionBadCredentialsException;
  285. use SymfonyComponentSecurityCoreExceptionAuthenticationException;
  286. use SymfonyComponentSecurityCoreUserUserInterface;
  287. use SymfonyComponentSecurityCoreUserUserProviderInterface;
  288. use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
  289. use SymfonyComponentSecurityGuardAuthenticatorAbstractFormLoginAuthenticator;
  290. use SymfonyComponentSecurityCoreSecurity;
  291.  
  292. class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
  293. {
  294. private $router;
  295. private $encoder;
  296.  
  297. public function __construct(RouterInterface $router, UserPasswordEncoderInterface $encoder)
  298. {
  299. $this->router = $router;
  300. $this->encoder = $encoder;
  301. }
  302.  
  303. public function getCredentials(Request $request)
  304. {
  305. if ($request->getPathInfo() != '/login') {
  306. return;
  307. }
  308.  
  309. $email = $request->request->get('usuario');
  310. $request->getSession()->set(Security::LAST_USERNAME, $email);
  311. $password = $request->request->get('senha');
  312.  
  313. return [
  314. 'usulogin' => $email,
  315. 'ususenha' => $password,
  316. ];
  317. }
  318.  
  319. public function getUser($credentials, UserProviderInterface $userProvider)
  320. {
  321. $email = $credentials['usulogin'];
  322.  
  323. return $userProvider->loadUserByUsername($email);
  324. }
  325.  
  326. public function checkCredentials($credentials, UserInterface $user)
  327. {
  328. $plainPassword = $credentials['ususenha'];
  329. if ($this->encoder->isPasswordValid($user, $plainPassword)) {
  330. return true;
  331. }
  332.  
  333. throw new BadCredentialsException('Erro ao autenticar!');
  334. }
  335.  
  336. public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
  337. {
  338. $url = $this->router->generate('home');
  339.  
  340. return new RedirectResponse($url);
  341. }
  342.  
  343. public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  344. {
  345. $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
  346.  
  347. $url = $this->router->generate('authentication');
  348.  
  349. return new RedirectResponse($url);
  350. }
  351.  
  352. protected function getLoginUrl()
  353. {
  354. return $this->router->generate('authentication');
  355. }
  356.  
  357. protected function getDefaultSuccessRedirectUrl()
  358. {
  359. return $this->router->generate('home');
  360. }
  361.  
  362. public function supportsRememberMe()
  363. {
  364. return false;
  365. }
  366. }
  367.  
  368. # app/config/security.yml
  369. security:
  370. encoders:
  371. AppBundleEntityUsuarios:
  372. algorithm: bcrypt
  373.  
  374. providers:
  375. our_db_provider:
  376. entity:
  377. class: AppBundle:Usuarios
  378.  
  379. firewalls:
  380. # disables authentication for assets and the profiler, adapt it according to your needs
  381. dev:
  382. pattern: ^/(_(profiler|wdt)|css|images|js)/
  383. security: false
  384.  
  385. main:
  386. anonymous: ~
  387. guard:
  388. authenticators:
  389. - app.form_login_authenticator
  390. logout:
  391. path: /logout
  392. target: /
  393.  
  394. remember_me:
  395. secret: '%secret%'
  396. lifetime: 604800 # 1 week in seconds
  397. path: /
  398.  
  399. access_control:
  400. - { path: ^/home, roles: ROLE_ADMIN }
  401. - { path: ^/cadastrarUsuario, roles: ROLE_ADMIN }
  402. # ...
  403.  
  404. # Learn more about services, parameters and containers at
  405. # https://symfony.com/doc/current/service_container.html
  406. parameters:
  407. #parameter_name: value
  408.  
  409. services:
  410. # default configuration for services in *this* file
  411. app.form_login_authenticator:
  412. class: AppBundleSecurityFormLoginAuthenticator
  413. arguments: ["@router", "@security.password_encoder"]
  414. _defaults:
  415. # automatically injects dependencies in your services
  416. autowire: true
  417. # automatically registers your services as commands, event subscribers, etc.
  418. autoconfigure: true
  419. # this means you cannot fetch services directly from the container via $container->get()
  420. # if you need to do this, you can override this setting on individual services
  421. public: false
  422.  
  423. # makes classes in src/AppBundle available to be used as services
  424. # this creates a service per class whose id is the fully-qualified class name
  425. AppBundle:
  426. resource: '../../src/AppBundle/*'
  427. # you can exclude directories or files
  428. # but if a service is unused, it's removed anyway
  429. exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
  430.  
  431. # controllers are imported separately to make sure they're public
  432. # and have a tag that allows actions to type-hint services
  433. AppBundleController:
  434. resource: '../../src/AppBundle/Controller'
  435. public: true
  436. tags: ['controller.service_arguments']
  437.  
  438. # add more services, or override services that need manual wiring
  439. # AppBundleServiceExampleService:
  440. # arguments:
  441. # $someArgument: 'some_value'
  442.  
  443. access_control:
  444. - { path: ^/home, roles: ROLE_ADMIN }
  445. - { path: ^/cadastrarUsuario, roles: ROLE_ADMIN }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement