Skip to content

Commit b1816ba

Browse files
Merge pull request #93 from josephmcdermott/specify-current-timestamp
Use static $timestamp instead of time()
2 parents 8087bbe + d6e222c commit b1816ba

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/JWT.php

+13-3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ class JWT
2929
*/
3030
public static $leeway = 0;
3131

32+
/**
33+
* Allow the current timestamp to be specified.
34+
* Useful for fixing a value within unit testing.
35+
*
36+
* Will default to PHP time() value if null.
37+
*/
38+
public static $timestamp = null;
39+
3240
public static $supported_algs = array(
3341
'HS256' => array('hash_hmac', 'SHA256'),
3442
'HS512' => array('hash_hmac', 'SHA512'),
@@ -59,6 +67,8 @@ class JWT
5967
*/
6068
public static function decode($jwt, $key, $allowed_algs = array())
6169
{
70+
$timestamp = is_null(self::$timestamp) ? time() : self::$timestamp;
71+
6272
if (empty($key)) {
6373
throw new InvalidArgumentException('Key may not be empty');
6474
}
@@ -99,7 +109,7 @@ public static function decode($jwt, $key, $allowed_algs = array())
99109

100110
// Check if the nbf if it is defined. This is the time that the
101111
// token can actually be used. If it's not yet that time, abort.
102-
if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) {
112+
if (isset($payload->nbf) && $payload->nbf > ($timestamp + self::$leeway)) {
103113
throw new BeforeValidException(
104114
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
105115
);
@@ -108,14 +118,14 @@ public static function decode($jwt, $key, $allowed_algs = array())
108118
// Check that this token has been created before 'now'. This prevents
109119
// using tokens that have been created for later use (and haven't
110120
// correctly used the nbf claim).
111-
if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) {
121+
if (isset($payload->iat) && $payload->iat > ($timestamp + self::$leeway)) {
112122
throw new BeforeValidException(
113123
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
114124
);
115125
}
116126

117127
// Check if this token has expired.
118-
if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) {
128+
if (isset($payload->exp) && ($timestamp - self::$leeway) >= $payload->exp) {
119129
throw new ExpiredException('Expired token');
120130
}
121131

0 commit comments

Comments
 (0)