MediaWiki master
Token.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Session;
8
9use Stringable;
10
17class Token implements Stringable {
21 public const SUFFIX = '+\\';
22
24 private $secret;
25
27 private $salt;
28
30 private $new;
31
37 public function __construct( $secret, $salt, $new = false ) {
38 $this->secret = $secret;
39 $this->salt = $salt;
40 $this->new = $new;
41 }
42
52 public static function getTimestamp( $token ) {
53 $suffixLen = strlen( self::SUFFIX );
54 $len = strlen( $token );
55 if ( $len <= 32 + $suffixLen ||
56 substr( $token, -$suffixLen ) !== self::SUFFIX ||
57 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
58 ) {
59 return null;
60 }
61
62 return hexdec( substr( $token, 32, -$suffixLen ) );
63 }
64
70 protected function toStringAtTimestamp( $timestamp ) {
71 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
72 dechex( $timestamp ) .
74 }
75
80 public function toString() {
81 return $this->toStringAtTimestamp( (int)wfTimestamp( TS_UNIX ) );
82 }
83
84 public function __toString() {
85 return $this->toString();
86 }
87
94 public function match( $userToken, $maxAge = null ) {
95 if ( !$userToken ) {
96 return false;
97 }
98 $timestamp = self::getTimestamp( $userToken );
99 if ( $timestamp === null ) {
100 return false;
101 }
102 if ( $maxAge !== null && $timestamp < (int)wfTimestamp( TS_UNIX ) - $maxAge ) {
103 // Expired token
104 return false;
105 }
106
107 $sessionToken = $this->toStringAtTimestamp( $timestamp );
108 return hash_equals( $sessionToken, $userToken );
109 }
110
116 public function wasNew() {
117 return $this->new;
118 }
119
120}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Value object representing a CSRF token.
Definition Token.php:17
match( $userToken, $maxAge=null)
Test if the token-string matches this token.
Definition Token.php:94
__construct( $secret, $salt, $new=false)
Definition Token.php:37
toString()
Get the string representation of the token.
Definition Token.php:80
wasNew()
Indicate whether this token was created during the current request (true) or loaded from existing ses...
Definition Token.php:116
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:70
const SUFFIX
CSRF token suffix.
Definition Token.php:21
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:52