AppPasswordController.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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\UseSession;
  15. use OCP\AppFramework\Http\DataResponse;
  16. use OCP\AppFramework\OCS\OCSForbiddenException;
  17. use OCP\Authentication\Exceptions\CredentialsUnavailableException;
  18. use OCP\Authentication\Exceptions\InvalidTokenException;
  19. use OCP\Authentication\Exceptions\PasswordUnavailableException;
  20. use OCP\Authentication\LoginCredentials\IStore;
  21. use OCP\EventDispatcher\IEventDispatcher;
  22. use OCP\IRequest;
  23. use OCP\ISession;
  24. use OCP\IUserManager;
  25. use OCP\Security\Bruteforce\IThrottler;
  26. use OCP\Security\ISecureRandom;
  27. class AppPasswordController extends \OCP\AppFramework\OCSController {
  28. public function __construct(
  29. string $appName,
  30. IRequest $request,
  31. private ISession $session,
  32. private ISecureRandom $random,
  33. private IProvider $tokenProvider,
  34. private IStore $credentialStore,
  35. private IEventDispatcher $eventDispatcher,
  36. private Session $userSession,
  37. private IUserManager $userManager,
  38. private IThrottler $throttler,
  39. ) {
  40. parent::__construct($appName, $request);
  41. }
  42. /**
  43. * @NoAdminRequired
  44. * @PasswordConfirmationRequired
  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. #[ApiRoute(verb: 'GET', url: '/getapppassword', root: '/core')]
  54. public function getAppPassword(): DataResponse {
  55. // We do not allow the creation of new tokens if this is an app password
  56. if ($this->session->exists('app_password')) {
  57. throw new OCSForbiddenException('You cannot request an new apppassword with an apppassword');
  58. }
  59. try {
  60. $credentials = $this->credentialStore->getLoginCredentials();
  61. } catch (CredentialsUnavailableException $e) {
  62. throw new OCSForbiddenException();
  63. }
  64. try {
  65. $password = $credentials->getPassword();
  66. } catch (PasswordUnavailableException $e) {
  67. $password = null;
  68. }
  69. $userAgent = $this->request->getHeader('USER_AGENT');
  70. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  71. $generatedToken = $this->tokenProvider->generateToken(
  72. $token,
  73. $credentials->getUID(),
  74. $credentials->getLoginName(),
  75. $password,
  76. $userAgent,
  77. IToken::PERMANENT_TOKEN,
  78. IToken::DO_NOT_REMEMBER
  79. );
  80. $this->eventDispatcher->dispatchTyped(
  81. new AppPasswordCreatedEvent($generatedToken)
  82. );
  83. return new DataResponse([
  84. 'apppassword' => $token
  85. ]);
  86. }
  87. /**
  88. * @NoAdminRequired
  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. #[ApiRoute(verb: 'DELETE', url: '/apppassword', root: '/core')]
  98. public function deleteAppPassword(): DataResponse {
  99. if (!$this->session->exists('app_password')) {
  100. throw new OCSForbiddenException('no app password in use');
  101. }
  102. $appPassword = $this->session->get('app_password');
  103. try {
  104. $token = $this->tokenProvider->getToken($appPassword);
  105. } catch (InvalidTokenException $e) {
  106. throw new OCSForbiddenException('could not remove apptoken');
  107. }
  108. $this->tokenProvider->invalidateTokenById($token->getUID(), $token->getId());
  109. return new DataResponse();
  110. }
  111. /**
  112. * @NoAdminRequired
  113. *
  114. * Rotate app password
  115. *
  116. * @return DataResponse<Http::STATUS_OK, array{apppassword: string}, array{}>
  117. * @throws OCSForbiddenException Rotating app password is not allowed
  118. *
  119. * 200: App password returned
  120. */
  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. * @NoAdminRequired
  142. * @BruteForceProtection(action=sudo)
  143. *
  144. * @param string $password The password of the user
  145. *
  146. * @return DataResponse<Http::STATUS_OK, array{lastLogin: int}, array{}>|DataResponse<Http::STATUS_FORBIDDEN, array<empty>, array{}>
  147. *
  148. * 200: Password confirmation succeeded
  149. * 403: Password confirmation failed
  150. */
  151. #[UseSession]
  152. #[ApiRoute(verb: 'PUT', url: '/apppassword/confirm', root: '/core')]
  153. public function confirmUserPassword(string $password): DataResponse {
  154. $loginName = $this->userSession->getLoginName();
  155. $loginResult = $this->userManager->checkPassword($loginName, $password);
  156. if ($loginResult === false) {
  157. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  158. $response->throttle(['loginName' => $loginName]);
  159. return $response;
  160. }
  161. $confirmTimestamp = time();
  162. $this->session->set('last-password-confirm', $confirmTimestamp);
  163. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'sudo', ['loginName' => $loginName]);
  164. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  165. }
  166. }