AppPasswordController.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Authentication\Events\AppPasswordCreatedEvent;
  9. use OC\Authentication\Token\IProvider;
  10. use OC\Authentication\Token\IToken;
  11. use OC\User\Session;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Http\Attribute\ApiRoute;
  14. use OCP\AppFramework\Http\Attribute\BruteForceProtection;
  15. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  16. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  17. use OCP\AppFramework\Http\Attribute\UseSession;
  18. use OCP\AppFramework\Http\DataResponse;
  19. use OCP\AppFramework\OCS\OCSForbiddenException;
  20. use OCP\Authentication\Exceptions\CredentialsUnavailableException;
  21. use OCP\Authentication\Exceptions\InvalidTokenException;
  22. use OCP\Authentication\Exceptions\PasswordUnavailableException;
  23. use OCP\Authentication\LoginCredentials\IStore;
  24. use OCP\EventDispatcher\IEventDispatcher;
  25. use OCP\IRequest;
  26. use OCP\ISession;
  27. use OCP\IUserManager;
  28. use OCP\Security\Bruteforce\IThrottler;
  29. use OCP\Security\ISecureRandom;
  30. class AppPasswordController extends \OCP\AppFramework\OCSController {
  31. public function __construct(
  32. string $appName,
  33. IRequest $request,
  34. private ISession $session,
  35. private ISecureRandom $random,
  36. private IProvider $tokenProvider,
  37. private IStore $credentialStore,
  38. private IEventDispatcher $eventDispatcher,
  39. private Session $userSession,
  40. private IUserManager $userManager,
  41. private IThrottler $throttler,
  42. ) {
  43. parent::__construct($appName, $request);
  44. }
  45. /**
  46. * Create app password
  47. *
  48. * @return DataResponse<Http::STATUS_OK, array{apppassword: string}, array{}>
  49. * @throws OCSForbiddenException Creating app password is not allowed
  50. *
  51. * 200: App password returned
  52. */
  53. #[NoAdminRequired]
  54. #[PasswordConfirmationRequired]
  55. #[ApiRoute(verb: 'GET', url: '/getapppassword', root: '/core')]
  56. public function getAppPassword(): DataResponse {
  57. // We do not allow the creation of new tokens if this is an app password
  58. if ($this->session->exists('app_password')) {
  59. throw new OCSForbiddenException('You cannot request an new apppassword with an apppassword');
  60. }
  61. try {
  62. $credentials = $this->credentialStore->getLoginCredentials();
  63. } catch (CredentialsUnavailableException $e) {
  64. throw new OCSForbiddenException();
  65. }
  66. try {
  67. $password = $credentials->getPassword();
  68. } catch (PasswordUnavailableException $e) {
  69. $password = null;
  70. }
  71. $userAgent = $this->request->getHeader('USER_AGENT');
  72. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  73. $generatedToken = $this->tokenProvider->generateToken(
  74. $token,
  75. $credentials->getUID(),
  76. $credentials->getLoginName(),
  77. $password,
  78. $userAgent,
  79. IToken::PERMANENT_TOKEN,
  80. IToken::DO_NOT_REMEMBER
  81. );
  82. $this->eventDispatcher->dispatchTyped(
  83. new AppPasswordCreatedEvent($generatedToken)
  84. );
  85. return new DataResponse([
  86. 'apppassword' => $token
  87. ]);
  88. }
  89. /**
  90. * Delete app password
  91. *
  92. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  93. * @throws OCSForbiddenException Deleting app password is not allowed
  94. *
  95. * 200: App password deleted successfully
  96. */
  97. #[NoAdminRequired]
  98. #[ApiRoute(verb: 'DELETE', url: '/apppassword', root: '/core')]
  99. public function deleteAppPassword(): DataResponse {
  100. if (!$this->session->exists('app_password')) {
  101. throw new OCSForbiddenException('no app password in use');
  102. }
  103. $appPassword = $this->session->get('app_password');
  104. try {
  105. $token = $this->tokenProvider->getToken($appPassword);
  106. } catch (InvalidTokenException $e) {
  107. throw new OCSForbiddenException('could not remove apptoken');
  108. }
  109. $this->tokenProvider->invalidateTokenById($token->getUID(), $token->getId());
  110. return new DataResponse();
  111. }
  112. /**
  113. * Rotate app password
  114. *
  115. * @return DataResponse<Http::STATUS_OK, array{apppassword: string}, array{}>
  116. * @throws OCSForbiddenException Rotating app password is not allowed
  117. *
  118. * 200: App password returned
  119. */
  120. #[NoAdminRequired]
  121. #[ApiRoute(verb: 'POST', url: '/apppassword/rotate', root: '/core')]
  122. public function rotateAppPassword(): DataResponse {
  123. if (!$this->session->exists('app_password')) {
  124. throw new OCSForbiddenException('no app password in use');
  125. }
  126. $appPassword = $this->session->get('app_password');
  127. try {
  128. $token = $this->tokenProvider->getToken($appPassword);
  129. } catch (InvalidTokenException $e) {
  130. throw new OCSForbiddenException('could not rotate apptoken');
  131. }
  132. $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  133. $this->tokenProvider->rotate($token, $appPassword, $newToken);
  134. return new DataResponse([
  135. 'apppassword' => $newToken,
  136. ]);
  137. }
  138. /**
  139. * Confirm the user password
  140. *
  141. * @param string $password The password of the user
  142. *
  143. * @return DataResponse<Http::STATUS_OK, array{lastLogin: int}, array{}>|DataResponse<Http::STATUS_FORBIDDEN, array<empty>, array{}>
  144. *
  145. * 200: Password confirmation succeeded
  146. * 403: Password confirmation failed
  147. */
  148. #[NoAdminRequired]
  149. #[BruteForceProtection(action: 'sudo')]
  150. #[UseSession]
  151. #[ApiRoute(verb: 'PUT', url: '/apppassword/confirm', root: '/core')]
  152. public function confirmUserPassword(string $password): DataResponse {
  153. $loginName = $this->userSession->getLoginName();
  154. $loginResult = $this->userManager->checkPassword($loginName, $password);
  155. if ($loginResult === false) {
  156. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  157. $response->throttle(['loginName' => $loginName]);
  158. return $response;
  159. }
  160. $confirmTimestamp = time();
  161. $this->session->set('last-password-confirm', $confirmTimestamp);
  162. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'sudo', ['loginName' => $loginName]);
  163. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  164. }
  165. }