Skip to content

Commit

Permalink
Add CSRF token and store/return it in token() method
Browse files Browse the repository at this point in the history
  • Loading branch information
Xymph committed Aug 25, 2021
1 parent 5acedf8 commit d782d4a
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion Wikimate.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ class Wikimate
*/
protected $maxretries = -1;

/**
* Stored CSRF token for API requests
*
* @var string|null
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Tokens
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit#Additional_notes
*/
private $csrf_token = null;

/**
* Creates a new Wikimate object.
*
Expand Down Expand Up @@ -229,6 +238,9 @@ private function request($data, $headers = array(), $post = false)

/**
* Obtains a wiki token for logging in or data-modifying actions.
*
* If a CSRF (default) token is requested, it is stored and returned
* upon further such requests, instead of making another API call.
* For now this method, in Wikimate tradition, is kept simple and supports
* only the two token types needed elsewhere in the library. It also
* doesn't support the option to request multiple tokens at once.
Expand All @@ -247,6 +259,11 @@ protected function token($type = self::TOKEN_DEFAULT)
return false;
}

// Check for existing CSRF token for this login session
if ($type == self::TOKEN_DEFAULT && $this->csrf_token !== null) {
return $this->csrf_token;
}

$details = array(
'action' => 'query',
'meta' => 'tokens',
Expand Down Expand Up @@ -281,7 +298,9 @@ protected function token($type = self::TOKEN_DEFAULT)
if ($type == self::TOKEN_LOGIN) {
return $tokenResult['query']['tokens']['logintoken'];
} else {
return $tokenResult['query']['tokens']['csrftoken'];
// Store CSRF token for this login session
$this->csrf_token = $tokenResult['query']['tokens']['csrftoken'];
return $this->csrf_token;
}
}

Expand Down

0 comments on commit d782d4a

Please sign in to comment.