MediaWiki REL1_40
Token.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
32class Token {
36 public const SUFFIX = '+\\';
37
39 private $secret;
40
42 private $salt;
43
45 private $new;
46
52 public function __construct( $secret, $salt, $new = false ) {
53 $this->secret = $secret;
54 $this->salt = $salt;
55 $this->new = $new;
56 }
57
67 public static function getTimestamp( $token ) {
68 $suffixLen = strlen( self::SUFFIX );
69 $len = strlen( $token );
70 if ( $len <= 32 + $suffixLen ||
71 substr( $token, -$suffixLen ) !== self::SUFFIX ||
72 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
73 ) {
74 return null;
75 }
76
77 return hexdec( substr( $token, 32, -$suffixLen ) );
78 }
79
85 protected function toStringAtTimestamp( $timestamp ) {
86 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
87 dechex( $timestamp ) .
89 }
90
95 public function toString() {
96 return $this->toStringAtTimestamp( (int)wfTimestamp( TS_UNIX ) );
97 }
98
99 public function __toString() {
100 return $this->toString();
101 }
102
109 public function match( $userToken, $maxAge = null ) {
110 if ( !$userToken ) {
111 return false;
112 }
113 $timestamp = self::getTimestamp( $userToken );
114 if ( $timestamp === null ) {
115 return false;
116 }
117 if ( $maxAge !== null && $timestamp < (int)wfTimestamp( TS_UNIX ) - $maxAge ) {
118 // Expired token
119 return false;
120 }
121
122 $sessionToken = $this->toStringAtTimestamp( $timestamp );
123 return hash_equals( $sessionToken, $userToken );
124 }
125
130 public function wasNew() {
131 return $this->new;
132 }
133
134}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Value object representing a CSRF token.
Definition Token.php:32
match( $userToken, $maxAge=null)
Test if the token-string matches this token.
Definition Token.php:109
__construct( $secret, $salt, $new=false)
Definition Token.php:52
toString()
Get the string representation of the token.
Definition Token.php:95
wasNew()
Indicate whether this token was just created.
Definition Token.php:130
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:85
const SUFFIX
CSRF token suffix.
Definition Token.php:36
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:67