MediaWiki master
Token.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
26use Stringable;
27
34class Token implements Stringable {
38 public const SUFFIX = '+\\';
39
41 private $secret;
42
44 private $salt;
45
47 private $new;
48
54 public function __construct( $secret, $salt, $new = false ) {
55 $this->secret = $secret;
56 $this->salt = $salt;
57 $this->new = $new;
58 }
59
69 public static function getTimestamp( $token ) {
70 $suffixLen = strlen( self::SUFFIX );
71 $len = strlen( $token );
72 if ( $len <= 32 + $suffixLen ||
73 substr( $token, -$suffixLen ) !== self::SUFFIX ||
74 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
75 ) {
76 return null;
77 }
78
79 return hexdec( substr( $token, 32, -$suffixLen ) );
80 }
81
87 protected function toStringAtTimestamp( $timestamp ) {
88 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
89 dechex( $timestamp ) .
91 }
92
97 public function toString() {
98 return $this->toStringAtTimestamp( (int)wfTimestamp( TS_UNIX ) );
99 }
100
101 public function __toString() {
102 return $this->toString();
103 }
104
111 public function match( $userToken, $maxAge = null ) {
112 if ( !$userToken ) {
113 return false;
114 }
115 $timestamp = self::getTimestamp( $userToken );
116 if ( $timestamp === null ) {
117 return false;
118 }
119 if ( $maxAge !== null && $timestamp < (int)wfTimestamp( TS_UNIX ) - $maxAge ) {
120 // Expired token
121 return false;
122 }
123
124 $sessionToken = $this->toStringAtTimestamp( $timestamp );
125 return hash_equals( $sessionToken, $userToken );
126 }
127
132 public function wasNew() {
133 return $this->new;
134 }
135
136}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Value object representing a CSRF token.
Definition Token.php:34
match( $userToken, $maxAge=null)
Test if the token-string matches this token.
Definition Token.php:111
__construct( $secret, $salt, $new=false)
Definition Token.php:54
toString()
Get the string representation of the token.
Definition Token.php:97
wasNew()
Indicate whether this token was just created.
Definition Token.php:132
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:87
const SUFFIX
CSRF token suffix.
Definition Token.php:38
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:69