Skip to content

Commit

Permalink
Merge pull request #963 from nextcloud/enh/noid/api-ocs-controller
Browse files Browse the repository at this point in the history
Make the API controller an OCS controller
  • Loading branch information
julien-nc authored Oct 14, 2024
2 parents dfbdb52 + 66c863f commit 478baa1
Show file tree
Hide file tree
Showing 18 changed files with 207 additions and 44 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,26 @@ is enabled.
],
```

### Pre-provisioning

If you need the users to exist before they authenticate for the first time
(because you want other users to be able to share files with them, for example)
you can pre-provision them with the user_oidc API:

``` bash
curl -H "ocs-apirequest: true" -u admin:admin -X POST -H "content-type: application/json" \
-d '{"providerId":2,"userId":"new_user","displayName":"New User","email":"new@user.org","quota":"5GB"}' \
https://my.nextcloud.org/ocs/v2.php/apps/user_oidc/api/v1/user
```

Only the `providerId` and `userId` parameters are mandatory.

You can also delete users managed by user_oidc with this API endpoint:

``` bash
curl -H "ocs-apirequest: true" -u admin:admin -X DELETE
https://my.nextcloud.org/ocs/v2.php/apps/user_oidc/api/v1/user/USER_ID
```

### UserInfo request for Bearer token validation

Expand Down
10 changes: 9 additions & 1 deletion appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
*
*/

$requirements = [
'apiVersion' => '(v1)',
];

return [
'routes' => [
['name' => 'login#login', 'url' => '/login/{providerId}', 'verb' => 'GET'],
Expand All @@ -43,5 +47,9 @@
['name' => 'Settings#setID4ME', 'url' => '/provider/id4me', 'verb' => 'POST'],

['name' => 'Timezone#setTimezone', 'url' => '/config/timezone', 'verb' => 'POST'],
]
],
'ocs' => [
['name' => 'ocsApi#createUser', 'url' => '/api/{apiVersion}/user', 'verb' => 'POST', 'requirements' => $requirements],
['name' => 'ocsApi#deleteUser', 'url' => '/api/{apiVersion}/user/{userId}', 'verb' => 'DELETE', 'requirements' => $requirements],
],
];
59 changes: 53 additions & 6 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions lib/Command/UpsertProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class UpsertProvider extends Base {
public function __construct(
ProviderService $providerService,
ProviderMapper $providerMapper,
ICrypto $crypto
ICrypto $crypto,
) {
parent::__construct();
$this->providerService = $providerService;
Expand Down Expand Up @@ -242,7 +242,7 @@ protected function execute(InputInterface $input, OutputInterface $output) {
// invalidate JWKS cache (even if it was just created)
$this->providerService->setSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE, '');
$this->providerService->setSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE_TIMESTAMP, '');
} catch (DoesNotExistException | MultipleObjectsReturnedException $e) {
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
$output->writeln('<error>' . $e->getMessage() . '</error>');
return -1;
}
Expand Down
20 changes: 4 additions & 16 deletions lib/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,14 @@
use OCP\IUserManager;

class ApiController extends Controller {
/** @var UserMapper */
private $userMapper;

/** @var IUserManager */
private $userManager;
/**
* @var IRootFolder
*/
private $root;

public function __construct(
IRequest $request,
IRootFolder $root,
UserMapper $userMapper,
IUserManager $userManager
private IRootFolder $root,
private UserMapper $userMapper,
private IUserManager $userManager,
) {
parent::__construct(Application::APP_ID, $request);
$this->userMapper = $userMapper;
$this->userManager = $userManager;
$this->root = $root;
}

/**
Expand All @@ -81,7 +69,7 @@ public function createUser(int $providerId, string $userId, ?string $displayName
}

if ($email) {
$user->setEMailAddress($email);
$user->setSystemEMailAddress($email);
}

if ($quota) {
Expand Down
6 changes: 3 additions & 3 deletions lib/Controller/Id4meController.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public function __construct(
Id4MeMapper $id4MeMapper,
ID4MeService $id4MeService,
LoggerInterface $logger,
ICrypto $crypto
ICrypto $crypto,
) {
parent::__construct($request, $config);

Expand Down Expand Up @@ -167,7 +167,7 @@ public function login(string $domain) {

try {
$authorityName = $this->id4me->discover($domain);
} catch (InvalidOpenIdDomainException | OpenIdDnsRecordNotFoundException $e) {
} catch (InvalidOpenIdDomainException|OpenIdDnsRecordNotFoundException $e) {
$message = $this->l10n->t('Invalid OpenID domain');
return $this->buildErrorTemplateResponse($message, Http::STATUS_BAD_REQUEST, ['invalid_openid_domain' => $domain]);
}
Expand Down Expand Up @@ -266,7 +266,7 @@ public function code(string $state = '', string $code = '', string $scope = '')

try {
$id4Me = $this->id4MeMapper->findByIdentifier($authorityName);
} catch (DoesNotExistException | MultipleObjectsReturnedException $e) {
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
$message = $this->l10n->t('Authority not found');
return $this->buildErrorTemplateResponse($message, Http::STATUS_BAD_REQUEST, ['authority_not_found' => $authorityName]);
}
Expand Down
10 changes: 5 additions & 5 deletions lib/Controller/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public function __construct(
ProvisioningService $provisioningService,
IL10N $l10n,
LoggerInterface $logger,
ICrypto $crypto
ICrypto $crypto,
) {
parent::__construct($request, $config);

Expand Down Expand Up @@ -234,7 +234,7 @@ public function login(int $providerId, ?string $redirectUrl = null) {

try {
$provider = $this->providerMapper->getProvider($providerId);
} catch (DoesNotExistException | MultipleObjectsReturnedException $e) {
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
$message = $this->l10n->t('There is not such OpenID Connect provider.');
return $this->buildErrorTemplateResponse($message, Http::STATUS_NOT_FOUND, ['provider_not_found' => $providerId]);
}
Expand Down Expand Up @@ -460,9 +460,9 @@ public function code(string $state = '', string $code = '', string $scope = '',
'headers' => $headers,
]
);
} catch (ClientException | ServerException $e) {
} catch (ClientException|ServerException $e) {
$response = $e->getResponse();
$body = (string) $response->getBody();
$body = (string)$response->getBody();
$responseBodyArray = json_decode($body, true);
if ($responseBodyArray !== null && isset($responseBodyArray['error'], $responseBodyArray['error_description'])) {
$this->logger->debug('Failed to contact the OIDC provider token endpoint', [
Expand Down Expand Up @@ -645,7 +645,7 @@ public function singleLogoutService() {
if ($providerId) {
try {
$provider = $this->providerMapper->getProvider((int)$providerId);
} catch (DoesNotExistException | MultipleObjectsReturnedException $e) {
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
$message = $this->l10n->t('There is not such OpenID Connect provider.');
return $this->buildErrorTemplateResponse($message, Http::STATUS_NOT_FOUND, ['provider_id' => $providerId]);
}
Expand Down
101 changes: 101 additions & 0 deletions lib/Controller/OcsApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022, Julien Veyssier <eneiluj@posteo.net>
*
* @author Julien Veyssier <eneiluj@posteo.net>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OCA\UserOIDC\Controller;

use OCA\UserOIDC\AppInfo\Application;
use OCA\UserOIDC\Db\UserMapper;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\Files\IRootFolder;
use OCP\Files\NotPermittedException;
use OCP\IRequest;
use OCP\IUserManager;

class OcsApiController extends OCSController {

public function __construct(
IRequest $request,
private IRootFolder $root,
private UserMapper $userMapper,
private IUserManager $userManager,
) {
parent::__construct(Application::APP_ID, $request);
}

/**
* @param int $providerId
* @param string $userId
* @param string|null $displayName
* @param string|null $email
* @param string|null $quota
* @return DataResponse
*/
public function createUser(int $providerId, string $userId, ?string $displayName = null,
?string $email = null, ?string $quota = null): DataResponse {
$backendUser = $this->userMapper->getOrCreate($providerId, $userId);
$user = $this->userManager->get($backendUser->getUserId());

if ($displayName) {
if ($displayName !== $backendUser->getDisplayName()) {
$backendUser->setDisplayName($displayName);
$this->userMapper->update($backendUser);
}
}

if ($email) {
$user->setSystemEMailAddress($email);
}

if ($quota) {
$user->setQuota($quota);
}

$userFolder = $this->root->getUserFolder($user->getUID());
try {
// copy skeleton
\OC_Util::copySkeleton($user->getUID(), $userFolder);
} catch (NotPermittedException $ex) {
// read only uses
}

return new DataResponse(['user_id' => $user->getUID()]);
}

/**
* @param string $userId
* @return DataResponse
*/
public function deleteUser(string $userId): DataResponse {
$user = $this->userManager->get($userId);
if (is_null($user) || $user->getBackendClassName() !== 'user_oidc') {
return new DataResponse(['message' => 'User not found'], Http::STATUS_NOT_FOUND);
}

$user->delete();
return new DataResponse(['user_id' => $userId], Http::STATUS_OK);
}
}
2 changes: 1 addition & 1 deletion lib/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function __construct(
ProviderService $providerService,
ICrypto $crypto,
IClientService $clientService,
LoggerInterface $logger
LoggerInterface $logger,
) {
parent::__construct(Application::APP_ID, $request);

Expand Down
2 changes: 1 addition & 1 deletion lib/Listener/TimezoneHandlingListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class TimezoneHandlingListener implements IEventListener {
public function __construct(
IUserSession $userSession,
ISession $session,
IConfig $config
IConfig $config,
) {
$this->userSession = $userSession;
$this->session = $session;
Expand Down
2 changes: 1 addition & 1 deletion lib/Migration/Version010303Date20230602125945.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Version010303Date20230602125945 extends SimpleMigrationStep {

public function __construct(
IDBConnection $connection,
ICrypto $crypto
ICrypto $crypto,
) {
$this->connection = $connection;
$this->crypto = $crypto;
Expand Down
2 changes: 1 addition & 1 deletion lib/Migration/Version010304Date20231121102449.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Version010304Date20231121102449 extends SimpleMigrationStep {

public function __construct(
IDBConnection $connection,
ICrypto $crypto
ICrypto $crypto,
) {
$this->connection = $connection;
$this->crypto = $crypto;
Expand Down
Loading

0 comments on commit 478baa1

Please sign in to comment.