SettingsController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\OAuth2\Controller;
  8. use OCA\OAuth2\Db\AccessTokenMapper;
  9. use OCA\OAuth2\Db\Client;
  10. use OCA\OAuth2\Db\ClientMapper;
  11. use OCP\AppFramework\Controller;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Http\JSONResponse;
  14. use OCP\Authentication\Token\IProvider as IAuthTokenProvider;
  15. use OCP\IL10N;
  16. use OCP\IRequest;
  17. use OCP\IUser;
  18. use OCP\IUserManager;
  19. use OCP\Security\ICrypto;
  20. use OCP\Security\ISecureRandom;
  21. class SettingsController extends Controller {
  22. public const validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  23. public function __construct(
  24. string $appName,
  25. IRequest $request,
  26. private ClientMapper $clientMapper,
  27. private ISecureRandom $secureRandom,
  28. private AccessTokenMapper $accessTokenMapper,
  29. private IL10N $l,
  30. private IAuthTokenProvider $tokenProvider,
  31. private IUserManager $userManager,
  32. private ICrypto $crypto
  33. ) {
  34. parent::__construct($appName, $request);
  35. }
  36. public function addClient(string $name,
  37. string $redirectUri): JSONResponse {
  38. if (filter_var($redirectUri, FILTER_VALIDATE_URL) === false) {
  39. return new JSONResponse(['message' => $this->l->t('Your redirect URL needs to be a full URL for example: https://yourdomain.com/path')], Http::STATUS_BAD_REQUEST);
  40. }
  41. $client = new Client();
  42. $client->setName($name);
  43. $client->setRedirectUri($redirectUri);
  44. $secret = $this->secureRandom->generate(64, self::validChars);
  45. $hashedSecret = bin2hex($this->crypto->calculateHMAC($secret));
  46. $client->setSecret($hashedSecret);
  47. $client->setClientIdentifier($this->secureRandom->generate(64, self::validChars));
  48. $client = $this->clientMapper->insert($client);
  49. $result = [
  50. 'id' => $client->getId(),
  51. 'name' => $client->getName(),
  52. 'redirectUri' => $client->getRedirectUri(),
  53. 'clientId' => $client->getClientIdentifier(),
  54. 'clientSecret' => $secret,
  55. ];
  56. return new JSONResponse($result);
  57. }
  58. public function deleteClient(int $id): JSONResponse {
  59. $client = $this->clientMapper->getByUid($id);
  60. $this->userManager->callForSeenUsers(function (IUser $user) use ($client) {
  61. $this->tokenProvider->invalidateTokensOfUser($user->getUID(), $client->getName());
  62. });
  63. $this->accessTokenMapper->deleteByClientId($id);
  64. $this->clientMapper->delete($client);
  65. return new JSONResponse([]);
  66. }
  67. }