3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Session
;
23 use MediaWiki\Request\WebRequest
;
24 use MediaWiki\User\LoggedOutEditToken
;
27 * Stores and matches CSRF tokens belonging to a given session user.
29 * @package MediaWiki\Session
34 * @var string default name for the form field to place the token in.
36 public const DEFAULT_FIELD_NAME
= 'wpEditToken';
38 private WebRequest
$request;
41 * @param WebRequest $request
43 public function __construct( WebRequest
$request ) {
44 $this->request
= $request;
48 * Initialize (if necessary) and return a current user CSRF token
49 * value which can be used in edit forms to show that the user's
50 * login credentials aren't being hijacked with a foreign form
53 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
55 * @param string|string[] $salt Optional function-specific data for hashing
59 public function getToken( $salt = '' ): Token
{
60 $session = $this->request
->getSession();
61 if ( !$session->getUser()->isRegistered() ) {
62 return new LoggedOutEditToken();
64 return $session->getToken( $salt );
68 * Check if a request contains a value named $valueName with the token value
69 * stored in the session.
71 * @param string $fieldName
72 * @param string|string[] $salt
75 * @see self::matchCSRFToken
77 public function matchTokenField(
78 string $fieldName = self
::DEFAULT_FIELD_NAME
,
81 return $this->matchToken( $this->request
->getVal( $fieldName ), $salt );
85 * Check if a value matches with the token value stored in the session.
86 * A match should confirm that the form was submitted from the user's own
87 * login session, not a form submission from a third-party site.
89 * @param string|null $value
90 * @param string|string[] $salt
94 public function matchToken(
101 $session = $this->request
->getSession();
102 // It's expensive to generate a new registered user token, so take a shortcut.
103 // Anon tokens are cheap and all the same, so we can afford to generate one just to match.
104 if ( $session->getUser()->isRegistered() && !$session->hasToken() ) {
107 return $this->getToken( $salt )->match( $value );