MediaWiki master
Token.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Session;
8
9use Stringable;
10use Wikimedia\Timestamp\ConvertibleTimestamp;
11use Wikimedia\Timestamp\TimestampFormat as TS;
12
19class Token implements Stringable {
23 public const SUFFIX = '+\\';
24
26 private $secret;
27
29 private $salt;
30
32 private $new;
33
39 public function __construct( $secret, $salt, $new = false ) {
40 $this->secret = $secret;
41 $this->salt = $salt;
42 $this->new = $new;
43 }
44
54 public static function getTimestamp( $token ) {
55 $suffixLen = strlen( self::SUFFIX );
56 $len = strlen( $token );
57 if ( $len <= 32 + $suffixLen ||
58 substr( $token, -$suffixLen ) !== self::SUFFIX ||
59 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
60 ) {
61 return null;
62 }
63
64 return hexdec( substr( $token, 32, -$suffixLen ) );
65 }
66
72 protected function toStringAtTimestamp( $timestamp ) {
73 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
74 dechex( $timestamp ) .
76 }
77
82 public function toString() {
83 return $this->toStringAtTimestamp( (int)ConvertibleTimestamp::now( TS::UNIX ) );
84 }
85
86 public function __toString() {
87 return $this->toString();
88 }
89
96 public function match( $userToken, $maxAge = null ) {
97 if ( !$userToken ) {
98 return false;
99 }
100 $timestamp = self::getTimestamp( $userToken );
101 if ( $timestamp === null ) {
102 return false;
103 }
104 if ( $maxAge !== null && $timestamp < (int)ConvertibleTimestamp::now( TS::UNIX ) - $maxAge ) {
105 // Expired token
106 return false;
107 }
108
109 $sessionToken = $this->toStringAtTimestamp( $timestamp );
110 return hash_equals( $sessionToken, $userToken );
111 }
112
118 public function wasNew() {
119 return $this->new;
120 }
121
122}
Value object representing a CSRF token.
Definition Token.php:19
match( $userToken, $maxAge=null)
Test if the token-string matches this token.
Definition Token.php:96
__construct( $secret, $salt, $new=false)
Definition Token.php:39
toString()
Get the string representation of the token.
Definition Token.php:82
wasNew()
Indicate whether this token was created during the current request (true) or loaded from existing ses...
Definition Token.php:118
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:72
const SUFFIX
CSRF token suffix.
Definition Token.php:23
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:54