]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/form/Symfony/Component/Form/Extension/Csrf/CsrfProvider/DefaultCsrfProvider.php
5354886cba2c92476801546194fd166e546c243e
[github/wallabag/wallabag.git] / vendor / symfony / form / Symfony / Component / Form / Extension / Csrf / CsrfProvider / DefaultCsrfProvider.php
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Form\Extension\Csrf\CsrfProvider;
13
14 /**
15 * Default implementation of CsrfProviderInterface.
16 *
17 * This provider uses the session ID returned by session_id() as well as a
18 * user-defined secret value to secure the CSRF token.
19 *
20 * @author Bernhard Schussek <bschussek@gmail.com>
21 */
22 class DefaultCsrfProvider implements CsrfProviderInterface
23 {
24 /**
25 * A secret value used for generating the CSRF token
26 * @var string
27 */
28 protected $secret;
29
30 /**
31 * Initializes the provider with a secret value
32 *
33 * A recommended value for the secret is a generated value with at least
34 * 32 characters and mixed letters, digits and special characters.
35 *
36 * @param string $secret A secret value included in the CSRF token
37 */
38 public function __construct($secret)
39 {
40 $this->secret = $secret;
41 }
42
43 /**
44 * {@inheritDoc}
45 */
46 public function generateCsrfToken($intention)
47 {
48 return sha1($this->secret.$intention.$this->getSessionId());
49 }
50
51 /**
52 * {@inheritDoc}
53 */
54 public function isCsrfTokenValid($intention, $token)
55 {
56 return $token === $this->generateCsrfToken($intention);
57 }
58
59 /**
60 * Returns the ID of the user session.
61 *
62 * Automatically starts the session if necessary.
63 *
64 * @return string The session ID
65 */
66 protected function getSessionId()
67 {
68 if (version_compare(PHP_VERSION, '5.4', '>=')) {
69 if (PHP_SESSION_NONE === session_status()) {
70 session_start();
71 }
72 } elseif (!session_id()) {
73 session_start();
74 }
75
76 return session_id();
77 }
78 }