Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add option to invalidate tokens on user logout #335

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions appinfo/Migrations/Version20220525140622.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
namespace OCA\oauth2\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Types;
use OCP\Migration\ISchemaMigration;

class Version20220525140622 implements ISchemaMigration {
public function changeSchema(Schema $schema, array $options) {
$prefix = $options['tablePrefix'];
$table = $schema->getTable("{$prefix}oauth2_clients");
if (!$table->hasColumn('invalidate_on_logout')) {
$table->addColumn('invalidate_on_logout', Types::BOOLEAN, [
'notnull' => true,
'default' => false,
]);
}
}
}
1 change: 1 addition & 0 deletions js/settings-admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ $(document).ready(function () {
$('#oauth2 input[name="name"]').val('');
$('#oauth2 input[name="redirect_uri"]').val('');
$('#oauth2 input[name="allow_subdomains"]').prop('checked', false);
$('#oauth2 input[name="invalidate_on_logout"]').prop('checked', false);
}
}
);
Expand Down
2 changes: 2 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ public function __construct(array $urlParams = []) {
$c->query('OCA\OAuth2\Db\AuthorizationCodeMapper'),
$c->query('OCA\OAuth2\Db\AccessTokenMapper'),
$c->query('OCA\OAuth2\Db\RefreshTokenMapper'),
$c->query('OCA\OAuth2\Db\ClientMapper'),
$c->query('Logger'),
\OC::$server->getUserSession(),
$c->query('AppName')
);
});
Expand Down
12 changes: 12 additions & 0 deletions lib/Commands/AddClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ protected function configure() {
'Trust the client even if the redirect-url is localhost.',
'false'
)
->addArgument(
'invalidate-on-logout',
InputArgument::OPTIONAL,
'Invalidate the oauth token when logging out of the ownCloud web client',
'false'
)
;
}

Expand All @@ -101,6 +107,7 @@ protected function execute(InputInterface $input, OutputInterface $output) {
$allowSubDomains = $input->getArgument('allow-sub-domains');
$trusted = $input->getArgument('trusted');
$forceTrust = $input->getArgument('force-trust');
$invalidateOnLogout = $input->getArgument('invalidate-on-logout');

if (\strlen($id) < 32) {
throw new \InvalidArgumentException('The client id should be at least 32 characters long');
Expand All @@ -117,6 +124,9 @@ protected function execute(InputInterface $input, OutputInterface $output) {
if (!\in_array($trusted, ['true', 'false'])) {
throw new \InvalidArgumentException('Please enter true or false for trusted.');
}
if (!\in_array($invalidateOnLogout, ['true', 'false'])) {
throw new \InvalidArgumentException('Please enter true or false for invalidate-on-logout.');
}
try {
// the name should be uniq
$this->clientMapper->findByName($name);
Expand All @@ -139,13 +149,15 @@ protected function execute(InputInterface $input, OutputInterface $output) {
$allowSubDomains = \filter_var($allowSubDomains, FILTER_VALIDATE_BOOLEAN);
$client->setAllowSubdomains((bool)$allowSubDomains);
$trusted = \filter_var($trusted, FILTER_VALIDATE_BOOLEAN);
$invalidateOnLogout = \filter_var($invalidateOnLogout, FILTER_VALIDATE_BOOLEAN);
$forceTrust = \filter_var($forceTrust, FILTER_VALIDATE_BOOLEAN);
$rURI = new URL(Utilities::removeWildcardPort($url));
if ($trusted && !$forceTrust && ($rURI->hostname === 'localhost' || $rURI->hostname === '127.0.0.1')) {
$output->writeln("Cannot set localhost as trusted.");
return 1;
}
$client->setTrusted((bool)$trusted);
$client->setInvalidateOnLogout((bool)$invalidateOnLogout);

$this->clientMapper->insert($client);
}
Expand Down
1 change: 1 addition & 0 deletions lib/Commands/ListClients.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ protected function execute(InputInterface $input, OutputInterface $output) {
'client-secret' => $client->getSecret(),
'allow-sub-domains' => $client->getAllowSubdomains(),
'trusted' => $client->getTrusted(),
'invalidate-on-logout' => $client->getInvalidateOnLogout(),
];
}
parent::writeArrayInOutputFormat($input, $output, $clientsOutput, self::DEFAULT_OUTPUT_PREFIX, true);
Expand Down
8 changes: 6 additions & 2 deletions lib/Commands/ModifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected function configure() {
->addArgument(
'key',
InputArgument::REQUIRED,
'Key to be changed. Valid keys are : name, client-id, client-secret, redirect-url, allow-sub-domains, trusted'
'Key to be changed. Valid keys are : name, client-id, client-secret, redirect-url, allow-sub-domains, trusted, invalidate-on-logout'
)
->addArgument(
'value',
Expand Down Expand Up @@ -89,6 +89,7 @@ protected function execute(InputInterface $input, OutputInterface $output) {
'redirect-url' => 'setRedirectUri',
'allow-sub-domains' => 'setAllowSubdomains',
'trusted' => 'setTrusted',
'invalidate-on-logout' => 'setInvalidateOnLogout',
];

if (!\array_key_exists($key, $funcMapper)) {
Expand All @@ -111,8 +112,11 @@ protected function execute(InputInterface $input, OutputInterface $output) {
if ($key === 'trusted' && !\in_array($value, ['true', 'false'])) {
throw new \InvalidArgumentException('Please enter true or false for trusted.');
}
if ($key === 'invalidate-on-logout' && !\in_array($value, ['true', 'false'])) {
throw new \InvalidArgumentException('Please enter true or false for invalidate-on-logout.');
}

if ($key === 'trusted' || $key == 'allow-sub-domains') {
if ($key === 'trusted' || $key == 'allow-sub-domains' || $key == 'invalidate-on-logout') {
$value = \filter_var($value, FILTER_VALIDATE_BOOLEAN);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/PageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ public function logout(
);
}
// logout the current user
$this->userSession->logout();
// $this->userSession->logout();

$redirectUrl = $this->urlGenerator->linkToRoute('oauth2.page.authorize', [
'response_type' => $response_type,
Expand Down
3 changes: 3 additions & 0 deletions lib/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ public function addClient(): JSONResponse {
}
$client->setTrusted($trusted);

$invalidateOnLogout = $this->request->getParam('invalidate_on_logout', null) !== null;
$client->setInvalidateOnLogout($invalidateOnLogout);

$this->clientMapper->insert($client);
$this->logger->info('The client "' . $client->getName() . '" has been added.', ['app' => $this->appName]);

Expand Down
11 changes: 11 additions & 0 deletions lib/Db/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
* @method void setName(string $name)
* @method boolean getAllowSubdomains()
* @method boolean getTrusted()
* @method boolean getInvalidateOnLogout()
*/
class Client extends Entity {
protected $identifier;
Expand All @@ -41,6 +42,7 @@ class Client extends Entity {
protected $name;
protected $allowSubdomains;
protected $trusted;
protected $invalidateOnLogout;

/**
* Client constructor.
Expand All @@ -53,6 +55,7 @@ public function __construct() {
$this->addType('name', 'string');
$this->addType('allow_subdomains', 'boolean');
$this->addType('trusted', 'boolean');
$this->addType('invalidateOnLogout', 'boolean');
}

public function setAllowSubdomains(bool $value): void {
Expand All @@ -70,4 +73,12 @@ public function setTrusted(bool $value): void {
$this->setter('trusted', [$value]);
}
}

public function setInvalidateOnLogout(bool $value): void {
if (\OC::$server->getDatabaseConnection()->getDatabasePlatform() instanceof OraclePlatform) {
$this->setter('invalidateOnLogout', [$value ? 1 : 0]);
} else {
$this->setter('invalidateOnLogout', [$value]);
}
}
}
11 changes: 11 additions & 0 deletions lib/Db/ClientMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,15 @@ public function deleteAll() {
$stmt = $this->execute($sql, []);
$stmt->closeCursor();
}

/**
* Selects clients whose tokens should be invalidated on logout.
*
* @return Entity[] The client entities.
*/
public function findInvalidateOnLogout() {
$sql = 'SELECT * FROM `' . $this->tableName . '` '
. 'WHERE `invalidate_on_logout` = ?';
return $this->findEntities($sql, [1], null, null);
}
}
27 changes: 27 additions & 0 deletions lib/Hooks/UserHooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@
use OC\User\User;
use OCA\OAuth2\Db\AccessTokenMapper;
use OCA\OAuth2\Db\AuthorizationCodeMapper;
use OCA\OAuth2\Db\Client;
use OCA\OAuth2\Db\ClientMapper;
use OCA\OAuth2\Db\RefreshTokenMapper;
use OCP\ILogger;
use OCP\IUserSession;

class UserHooks {

Expand All @@ -40,35 +43,47 @@ class UserHooks {
/** @var RefreshTokenMapper */
private $refreshTokenMapper;

/** @var ClientMapper */
private $clientMapper;

/** @var ILogger */
private $logger;

/** @var string */
private $appName;

/** @var IUserSession */
private $userSession;

/**
* UserHooks constructor.
*
* @param Manager $userManager The user manager.
* @param AuthorizationCodeMapper $authorizationCodeMapper The authorization code mapper.
* @param AccessTokenMapper $accessTokenMapper The access token mapper.
* @param RefreshTokenMapper $refreshTokenMapper The refresh token mapper.
* @param ClientMapper $clientMapper The client mapper.
* @param ILogger $logger The logger.
* @param IUserSession $userSession The user session
* @param string $AppName The app's name.
*/
public function __construct(
Manager $userManager,
AuthorizationCodeMapper $authorizationCodeMapper,
AccessTokenMapper $accessTokenMapper,
RefreshTokenMapper $refreshTokenMapper,
ClientMapper $clientMapper,
ILogger $logger,
IUserSession $userSession,
$AppName
) {
$this->userManager = $userManager;
$this->authorizationCodeMapper = $authorizationCodeMapper;
$this->accessTokenMapper = $accessTokenMapper;
$this->refreshTokenMapper = $refreshTokenMapper;
$this->clientMapper = $clientMapper;
$this->logger = $logger;
$this->userSession = $userSession;
$this->appName = $AppName;
}

Expand All @@ -91,5 +106,17 @@ public function register() {
};
/** @phan-suppress-next-line PhanUndeclaredMethod */
$this->userManager->listen('\OC\User', 'preDelete', $callback);
$this->userManager->listen('\OC\User', 'preLogout', function () {
$user = $this->userSession->getUser();
$clientsWithInvalidate = $this->clientMapper->findInvalidateOnLogout();

foreach ($clientsWithInvalidate as $client) {
$this->authorizationCodeMapper->deleteByClientUser($client->getId(), $user->getUID());
$this->accessTokenMapper->deleteByClientUser($client->getId(), $user->getUID());
$this->refreshTokenMapper->deleteByClientUser($client->getId(), $user->getUID());
}

return null;
});
}
}
5 changes: 5 additions & 0 deletions templates/client.part.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
<?php else: ?>
<td></td>
<?php endif; ?>
<?php if ($client->getInvalidateOnLogout()): ?>
<td class="icon-32 icon-checkmark"></td>
<?php else: ?>
<td></td>
<?php endif; ?>
<td>
<button type="button" class="button icon-delete" data-id="<?php p($client->getId()) ?>"></button>
</td>
Expand Down
3 changes: 3 additions & 0 deletions templates/settings-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<th id="headerSecret" scope="col"><?php p($l->t('Secret')); ?></th>
<th id="headerSubdomains" scope="col"><?php p($l->t('Subdomains allowed')); ?></th>
<th id="headerTrusted" scope="col"><?php p($l->t('Trusted client')); ?></th>
<th id="headerInvalidateOnLogout" scope="col"><?php p($l->t('Invalidate on logout')); ?></th>
<th id="headerRemove">&nbsp;</th>
</tr>
</thead>
Expand All @@ -67,6 +68,8 @@
<label for="allow_subdomains"><?php p($l->t('Allow subdomains'));?></label>
<input name="trusted" id="trusted" type="checkbox" class="checkbox" value="1"/>
<label for="trusted"><?php p($l->t('Trusted client'));?></label>
<input name="invalidate_on_logout" id="invalidateOnLogout" type="checkbox" class="checkbox" value="1"/>
<label for="invalidateOnLogout"><?php p($l->t('Invalidate on logout'));?></label>
</form>
<button id="oauth2_submit" type="button" class="button"><?php p($l->t('Add')); ?></button>
<span id="oauth2_save_msg"></span>
Expand Down