Skip to content

Commit 7d92fc4

Browse files
committed
token extension and api settings
1 parent ae57d79 commit 7d92fc4

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Change Log
22

3+
### 1.1.1
4+
* Added: ApiSettings class
5+
* Changed: Token expiration time is pulled from settings. Old constant deprecated
6+
* Added: Support for extending token expiration on use
7+
38
### 1.1.0
49

510
* Added: Changelog

src/ApiSettings.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Rhubarb\Scaffolds\TokenBasedRestApi;
4+
5+
use Rhubarb\Crown\Settings;
6+
7+
class ApiSettings extends Settings
8+
{
9+
public $tokenExpiration = '+1 day';
10+
public $extendTokenExpirationOnUse = false;
11+
}

src/Model/ApiToken.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
namespace Rhubarb\Scaffolds\TokenBasedRestApi\Model;
2020

21+
use Rhubarb\Scaffolds\TokenBasedRestApi\ApiSettings;
2122
use Rhubarb\Scaffolds\TokenBasedRestApi\Exceptions\TokenInvalidException;
2223
use Rhubarb\Stem\Exceptions\RecordNotFoundException;
2324
use Rhubarb\Stem\Filters\AndGroup;
@@ -35,6 +36,7 @@
3536

3637
class ApiToken extends Model
3738
{
39+
/** @deprecated Use ApiSettings::$tokenExpiration */
3840
const TOKEN_EXPIRATION = "+1 day";
3941

4042
protected function createSchema()
@@ -76,7 +78,13 @@ public static function validateToken($tokenString)
7678
throw new TokenInvalidException();
7779
}
7880

81+
/** @var ApiToken $token */
7982
$token = $tokens[0];
83+
$settings = ApiSettings::singleton();
84+
if ($settings->extendTokenExpirationOnUse) {
85+
$token->Expires = $settings->tokenExpiration;
86+
$token->save();
87+
}
8088

8189
return $token->AuthenticatedUser;
8290
}
@@ -110,8 +118,7 @@ public static function retrieveOrCreateToken(Model $user, $ipAddress)
110118
new Equals("IpAddress", $ipAddress),
111119
new GreaterThan("Expires", "now", true)
112120
]));
113-
114-
$token->Expires = self::TOKEN_EXPIRATION;
121+
$token->Expires = ApiSettings::singleton()->tokenExpiration;
115122
$token->save();
116123
} catch (RecordNotFoundException $ex) {
117124
$token = self::createToken($user, $ipAddress);
@@ -131,7 +138,7 @@ protected function createConsistencyValidator()
131138
protected function beforeSave()
132139
{
133140
if ($this->isNewRecord()) {
134-
$this->Expires = self::TOKEN_EXPIRATION;
141+
$this->Expires = ApiSettings::singleton()->tokenExpiration;
135142
}
136143

137144
parent::beforeSave();

0 commit comments

Comments
 (0)