Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.79 KB | None | 0 0
  1. namespace AppBundleController;
  2.  
  3. use SymfonyBundleFrameworkBundleControllerController;
  4. use SymfonyComponentHttpFoundationRequest;
  5. use SensioBundleFrameworkExtraBundleConfigurationRoute;
  6. use SymfonyComponentSecurityCoreExceptionAuthenticationException;
  7. use SymfonyComponentSecurityCoreUserUserInterface;
  8.  
  9. class SecurityController extends Controller
  10. {
  11. /**
  12. * @param $name
  13. * @return SymfonyComponentHttpFoundationResponse
  14. * @Route("/login", name="login")
  15. */
  16. public function indexAction(Request $request)
  17. {
  18. $user = $this->getUser();
  19.  
  20. if($user instanceof UserInterface) {
  21. return $this->redirectToRoute('homepage');
  22. }
  23.  
  24. return $this->render('AppBundle:Security:index.html.twig', array(
  25. 'error' => $this->get('security.authentication_utils')->getLastAuthenticationError(),
  26. 'last_username' => $this->get('security.authentication_utils')->getLastUsername()
  27. ));
  28. }
  29. }
  30.  
  31. security:
  32. providers:
  33. in_memory:
  34. memory: ~
  35.  
  36. encoders:
  37. AppBundleEntityUser: sha512
  38.  
  39. firewalls:
  40. dev:
  41. pattern: ^/(_(profiler|wdt)|css|images|js)/
  42. security: false
  43.  
  44. main:
  45. anonymous: ~
  46. logout:
  47. path: /logout
  48. target: /
  49. guard:
  50. authenticators:
  51. - form_authenticator
  52. entry_point: form_authenticator
  53.  
  54. access_control:
  55. - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
  56.  
  57. namespace AppBundleEntity;
  58.  
  59. use DoctrineORMMapping as ORM;
  60. use SymfonyComponentSecurityCoreUserUserInterface;
  61. use SymfonyComponentValidatorConstraints as Assert;
  62.  
  63. /**
  64. * Class User
  65. * @package AppBundleEntity
  66. * @ORMEntity(repositoryClass="AppBundleEntityUserRepository")
  67. * @ORMTable(name="users")
  68. */
  69. class User implements UserInterface, Serializable {
  70. /**
  71. * @ORMColumn(type="string")
  72. * @ORMId
  73. * @ORMGeneratedValue(strategy="UUID")
  74. */
  75. private $id;
  76.  
  77. /**
  78. * @ORMColumn(type="string", length=100)
  79. */
  80. private $username;
  81.  
  82. /**
  83. * @ORMColumn(type="string", length=100)
  84. */
  85. private $email;
  86.  
  87. /**
  88. * @ORMColumn(type="string", length=255)
  89. */
  90. private $password;
  91.  
  92. /**
  93. * @AssertNotBlank()
  94. * @AssertLength(max=4096)
  95. */
  96. private $plainPassword;
  97.  
  98. /**
  99. * Get id
  100. *
  101. * @return string
  102. */
  103. public function getId()
  104. {
  105. return $this->id;
  106. }
  107.  
  108. /**
  109. * Set username
  110. *
  111. * @param string $username
  112. *
  113. * @return User
  114. */
  115. public function setUsername($username)
  116. {
  117. $this->username = $username;
  118.  
  119. return $this;
  120. }
  121.  
  122. /**
  123. * Get username
  124. *
  125. * @return string
  126. */
  127. public function getUsername()
  128. {
  129. return $this->username;
  130. }
  131.  
  132. /**
  133. * Set email
  134. *
  135. * @param string $email
  136. *
  137. * @return User
  138. */
  139. public function setEmail($email)
  140. {
  141. $this->email = $email;
  142.  
  143. return $this;
  144. }
  145.  
  146. /**
  147. * Get email
  148. *
  149. * @return string
  150. */
  151. public function getEmail()
  152. {
  153. return $this->email;
  154. }
  155.  
  156. /**
  157. * Set password
  158. *
  159. * @param string $password
  160. *
  161. * @return User
  162. */
  163. public function setPassword($password)
  164. {
  165. $this->password = $password;
  166.  
  167. return $this;
  168. }
  169.  
  170. /**
  171. * Get password
  172. *
  173. * @return string
  174. */
  175. public function getPassword()
  176. {
  177. return $this->password;
  178. }
  179.  
  180. /**
  181. * String representation of object
  182. * @link http://php.net/manual/en/serializable.serialize.php
  183. * @return string the string representation of the object or null
  184. * @since 5.1.0
  185. */
  186. public function serialize()
  187. {
  188. return serialize(array(
  189. $this->getId(),
  190. $this->getUsername(),
  191. $this->getEmail(),
  192. $this->getPassword()
  193. ));
  194. }
  195.  
  196. /**
  197. * Constructs the object
  198. * @link http://php.net/manual/en/serializable.unserialize.php
  199. * @param string $serialized <p>
  200. * The string representation of the object.
  201. * </p>
  202. * @return void
  203. * @since 5.1.0
  204. */
  205. public function unserialize($serialized)
  206. {
  207. $id = $this->getId();
  208. $username = $this->getUsername();
  209. $email = $this->getEmail();
  210. $password = $this->getPassword();
  211.  
  212. list(
  213. $id,
  214. $username,
  215. $email,
  216. $password
  217. ) = unserialize($serialized);
  218. }
  219.  
  220. /**
  221. * Returns the roles granted to the user.
  222. *
  223. * <code>
  224. * public function getRoles()
  225. * {
  226. * return array('ROLE_USER');
  227. * }
  228. * </code>
  229. *
  230. * Alternatively, the roles might be stored on a ``roles`` property,
  231. * and populated in any number of different ways when the user object
  232. * is created.
  233. *
  234. * @return (Role|string)[] The user roles
  235. */
  236. public function getRoles()
  237. {
  238. return array(
  239. 'ROLE_USER'
  240. );
  241. }
  242.  
  243. /**
  244. * Returns the salt that was originally used to encode the password.
  245. *
  246. * This can return null if the password was not encoded using a salt.
  247. *
  248. * @return string|null The salt
  249. */
  250. public function getSalt()
  251. {
  252. return null;
  253. }
  254.  
  255. /**
  256. * Removes sensitive data from the user.
  257. *
  258. * This is important if, at any given point, sensitive information like
  259. * the plain-text password is stored on this object.
  260. */
  261. public function eraseCredentials()
  262. {
  263. }
  264.  
  265. /**
  266. * @return string
  267. */
  268. public function getPlainPassword()
  269. {
  270. return $this->plainPassword;
  271. }
  272.  
  273. /**
  274. * @param string $plainPassword
  275. */
  276. public function setPlainPassword($plainPassword)
  277. {
  278. $this->plainPassword = $plainPassword;
  279. }
  280. }
  281.  
  282. {% extends 'AppBundle::base.html.twig' %}
  283.  
  284. {% block mainContent %}
  285. {% if error %}
  286. <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
  287. {% endif %}
  288.  
  289. <form action="{{ path('login') }}" method="post">
  290. <label for="username">Username/Email:</label>
  291. <input type="text" id="username" name="username" value="{{ last_username }}">
  292.  
  293. <label for="password">Password:</label>
  294. <input type="password" id="password" name="password">
  295.  
  296. <button type="submit">Login</button>
  297. </form>
  298. {% endblock %}
  299.  
  300. parameters:
  301.  
  302. services:
  303. form_authenticator:
  304. class: AppBundleSecurityFormAuthenticator
  305. arguments: ['@router', '@service_container']
  306.  
  307. namespace AppBundleSecurity;
  308.  
  309. use SymfonyComponentDependencyInjectionContainerInterface;
  310. use SymfonyComponentHttpFoundationRedirectResponse;
  311. use SymfonyComponentHttpFoundationRequest;
  312. use SymfonyComponentHttpFoundationResponse;
  313. use SymfonyComponentRoutingRouterInterface;
  314. use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
  315. use SymfonyComponentSecurityCoreExceptionAuthenticationException;
  316. use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
  317. use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
  318. use SymfonyComponentSecurityCoreSecurity;
  319. use SymfonyComponentSecurityCoreUserInMemoryUserProvider;
  320. use SymfonyComponentSecurityCoreUserUserInterface;
  321. use SymfonyComponentSecurityCoreUserUserProviderInterface;
  322. use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;
  323.  
  324. class FormAuthenticator extends AbstractGuardAuthenticator {
  325.  
  326. /**
  327. * @var RouterInterface
  328. */
  329. private $router;
  330.  
  331. /**
  332. * @var ContainerInterface
  333. */
  334. private $container;
  335.  
  336. /**
  337. * @var string
  338. */
  339. private $failMessage = 'Chris says you are not valid.';
  340.  
  341. public function __construct(RouterInterface $routerInterface, ContainerInterface $containerInterface)
  342. {
  343. $this->container = $containerInterface;
  344. $this->router = $routerInterface;
  345. }
  346.  
  347. /**
  348. * Returns a response that directs the user to authenticate.
  349. *
  350. * This is called when an anonymous request accesses a resource that
  351. * requires authentication. The job of this method is to return some
  352. * response that "helps" the user start into the authentication process.
  353. *
  354. * Examples:
  355. * A) For a form login, you might redirect to the login page
  356. * return new RedirectResponse('/login');
  357. * B) For an API token authentication system, you return a 401 response
  358. * return new Response('Auth header required', 401);
  359. *
  360. * @param Request $request The request that resulted in an AuthenticationException
  361. * @param AuthenticationException $authException The exception that started the authentication process
  362. *
  363. * @return Response
  364. */
  365. public function start(Request $request, AuthenticationException $authException = null)
  366. {
  367. $url = $this->router->generate('login');
  368.  
  369. return new RedirectResponse($url);
  370. }
  371.  
  372. /**
  373. * Get the authentication credentials from the request and return them
  374. * as any type (e.g. an associate array). If you return null, authentication
  375. * will be skipped.
  376. *
  377. * Whatever value you return here will be passed to getUser() and checkCredentials()
  378. *
  379. * For example, for a form login, you might:
  380. *
  381. * return array(
  382. * 'username' => $request->request->get('_username'),
  383. * 'password' => $request->request->get('_password'),
  384. * );
  385. *
  386. * Or for an API token that's on a header, you might use:
  387. *
  388. * return array('api_key' => $request->headers->get('X-API-TOKEN'));
  389. *
  390. * @param Request $request
  391. *
  392. * @return mixed|null
  393. */
  394. public function getCredentials(Request $request)
  395. {
  396. if($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
  397. return;
  398. }
  399.  
  400. return array(
  401. 'username' => $request->request->get('username'),
  402. 'password' => $request->request->get('password'),
  403. );
  404. }
  405.  
  406. /**
  407. * Return a UserInterface object based on the credentials.
  408. *
  409. * The *credentials* are the return value from getCredentials()
  410. *
  411. * You may throw an AuthenticationException if you wish. If you return
  412. * null, then a UsernameNotFoundException is thrown for you.
  413. *
  414. * @param mixed $credentials
  415. * @param UserProviderInterface $userProvider
  416. *
  417. * @throws AuthenticationException
  418. *
  419. * @return UserInterface|null
  420. */
  421. public function getUser($credentials, UserProviderInterface $userProvider)
  422. {
  423. if(!$userProvider instanceof InMemoryUserProvider) {
  424. return;
  425. }
  426.  
  427. dump($userProvider->loadUserByUsername($credentials['username'])); die();
  428. try {
  429. return $userProvider->loadUserByUsername($credentials['username']);
  430. } catch(UsernameNotFoundException $e) {
  431. throw new CustomUserMessageAuthenticationException($this->failMessage);
  432. }
  433. }
  434.  
  435. /**
  436. * Returns true if the credentials are valid.
  437. *
  438. * If any value other than true is returned, authentication will
  439. * fail. You may also throw an AuthenticationException if you wish
  440. * to cause authentication to fail.
  441. *
  442. * The *credentials* are the return value from getCredentials()
  443. *
  444. * @param mixed $credentials
  445. * @param UserInterface $user
  446. *
  447. * @return bool
  448. *
  449. * @throws AuthenticationException
  450. */
  451. public function checkCredentials($credentials, UserInterface $user)
  452. {
  453. $plainPassword = $credentials['password'];
  454. $encoder = $this->container->get('security.password_encoder');
  455.  
  456. if(!$encoder->isPasswordValid($user, $plainPassword)) {
  457. throw new CustomUserMessageAuthenticationException($this->failMessage);
  458. }
  459.  
  460. return true;
  461. }
  462.  
  463. /**
  464. * Called when authentication executed, but failed (e.g. wrong username password).
  465. *
  466. * This should return the Response sent back to the user, like a
  467. * RedirectResponse to the login page or a 403 response.
  468. *
  469. * If you return null, the request will continue, but the user will
  470. * not be authenticated. This is probably not what you want to do.
  471. *
  472. * @param Request $request
  473. * @param AuthenticationException $exception
  474. *
  475. * @return Response|null
  476. */
  477. public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  478. {
  479. $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
  480. $url = $this->router->generate('login');
  481.  
  482. return new RedirectResponse($url);
  483. }
  484.  
  485. /**
  486. * Called when authentication executed and was successful!
  487. *
  488. * This should return the Response sent back to the user, like a
  489. * RedirectResponse to the last page they visited.
  490. *
  491. * If you return null, the current request will continue, and the user
  492. * will be authenticated. This makes sense, for example, with an API.
  493. *
  494. * @param Request $request
  495. * @param TokenInterface $token
  496. * @param string $providerKey The provider (i.e. firewall) key
  497. *
  498. * @return Response|null
  499. */
  500. public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
  501. {
  502. $url = $this->router->generate('homepage');
  503.  
  504. return new RedirectResponse($url);
  505. }
  506.  
  507. /**
  508. * Does this method support remember me cookies?
  509. *
  510. * Remember me cookie will be set if *all* of the following are met:
  511. * A) This method returns true
  512. * B) The remember_me key under your firewall is configured
  513. * C) The "remember me" functionality is activated. This is usually
  514. * done by having a _remember_me checkbox in your form, but
  515. * can be configured by the "always_remember_me" and "remember_me_parameter"
  516. * parameters under the "remember_me" firewall key
  517. *
  518. * @return bool
  519. */
  520. public function supportsRememberMe()
  521. {
  522. return false;
  523. }
  524. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement