AuthSettingsController.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Settings\Controller;
  8. use BadMethodCallException;
  9. use OC\Authentication\Exceptions\InvalidTokenException as OcInvalidTokenException;
  10. use OC\Authentication\Exceptions\PasswordlessTokenException;
  11. use OC\Authentication\Token\INamedToken;
  12. use OC\Authentication\Token\IProvider;
  13. use OC\Authentication\Token\RemoteWipe;
  14. use OCA\Settings\Activity\Provider;
  15. use OCP\Activity\IManager;
  16. use OCP\AppFramework\Controller;
  17. use OCP\AppFramework\Http;
  18. use OCP\AppFramework\Http\JSONResponse;
  19. use OCP\Authentication\Exceptions\ExpiredTokenException;
  20. use OCP\Authentication\Exceptions\InvalidTokenException;
  21. use OCP\Authentication\Exceptions\WipeTokenException;
  22. use OCP\Authentication\Token\IToken;
  23. use OCP\IRequest;
  24. use OCP\ISession;
  25. use OCP\IUserSession;
  26. use OCP\Security\ISecureRandom;
  27. use OCP\Session\Exceptions\SessionNotAvailableException;
  28. use Psr\Log\LoggerInterface;
  29. class AuthSettingsController extends Controller {
  30. /** @var IProvider */
  31. private $tokenProvider;
  32. /** @var ISession */
  33. private $session;
  34. /** @var IUserSession */
  35. private $userSession;
  36. /** @var string */
  37. private $uid;
  38. /** @var ISecureRandom */
  39. private $random;
  40. /** @var IManager */
  41. private $activityManager;
  42. /** @var RemoteWipe */
  43. private $remoteWipe;
  44. /** @var LoggerInterface */
  45. private $logger;
  46. /**
  47. * @param string $appName
  48. * @param IRequest $request
  49. * @param IProvider $tokenProvider
  50. * @param ISession $session
  51. * @param ISecureRandom $random
  52. * @param string|null $userId
  53. * @param IUserSession $userSession
  54. * @param IManager $activityManager
  55. * @param RemoteWipe $remoteWipe
  56. * @param LoggerInterface $logger
  57. */
  58. public function __construct(string $appName,
  59. IRequest $request,
  60. IProvider $tokenProvider,
  61. ISession $session,
  62. ISecureRandom $random,
  63. ?string $userId,
  64. IUserSession $userSession,
  65. IManager $activityManager,
  66. RemoteWipe $remoteWipe,
  67. LoggerInterface $logger) {
  68. parent::__construct($appName, $request);
  69. $this->tokenProvider = $tokenProvider;
  70. $this->uid = $userId;
  71. $this->userSession = $userSession;
  72. $this->session = $session;
  73. $this->random = $random;
  74. $this->activityManager = $activityManager;
  75. $this->remoteWipe = $remoteWipe;
  76. $this->logger = $logger;
  77. }
  78. /**
  79. * @NoAdminRequired
  80. * @NoSubAdminRequired
  81. * @PasswordConfirmationRequired
  82. *
  83. * @param string $name
  84. * @return JSONResponse
  85. */
  86. public function create($name) {
  87. if ($this->checkAppToken()) {
  88. return $this->getServiceNotAvailableResponse();
  89. }
  90. try {
  91. $sessionId = $this->session->getId();
  92. } catch (SessionNotAvailableException $ex) {
  93. return $this->getServiceNotAvailableResponse();
  94. }
  95. if ($this->userSession->getImpersonatingUserID() !== null) {
  96. return $this->getServiceNotAvailableResponse();
  97. }
  98. try {
  99. $sessionToken = $this->tokenProvider->getToken($sessionId);
  100. $loginName = $sessionToken->getLoginName();
  101. try {
  102. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  103. } catch (PasswordlessTokenException $ex) {
  104. $password = null;
  105. }
  106. } catch (InvalidTokenException $ex) {
  107. return $this->getServiceNotAvailableResponse();
  108. }
  109. if (mb_strlen($name) > 128) {
  110. $name = mb_substr($name, 0, 120) . '…';
  111. }
  112. $token = $this->generateRandomDeviceToken();
  113. $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  114. $tokenData = $deviceToken->jsonSerialize();
  115. $tokenData['canDelete'] = true;
  116. $tokenData['canRename'] = true;
  117. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  118. return new JSONResponse([
  119. 'token' => $token,
  120. 'loginName' => $loginName,
  121. 'deviceToken' => $tokenData,
  122. ]);
  123. }
  124. /**
  125. * @return JSONResponse
  126. */
  127. private function getServiceNotAvailableResponse() {
  128. $resp = new JSONResponse();
  129. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  130. return $resp;
  131. }
  132. /**
  133. * Return a 25 digit device password
  134. *
  135. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  136. *
  137. * @return string
  138. */
  139. private function generateRandomDeviceToken() {
  140. $groups = [];
  141. for ($i = 0; $i < 5; $i++) {
  142. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  143. }
  144. return implode('-', $groups);
  145. }
  146. private function checkAppToken(): bool {
  147. return $this->session->exists('app_password');
  148. }
  149. /**
  150. * @NoAdminRequired
  151. * @NoSubAdminRequired
  152. *
  153. * @param int $id
  154. * @return array|JSONResponse
  155. */
  156. public function destroy($id) {
  157. if ($this->checkAppToken()) {
  158. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  159. }
  160. try {
  161. $token = $this->findTokenByIdAndUser($id);
  162. } catch (WipeTokenException $e) {
  163. //continue as we can destroy tokens in wipe
  164. $token = $e->getToken();
  165. } catch (InvalidTokenException $e) {
  166. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  167. }
  168. $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
  169. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  170. return [];
  171. }
  172. /**
  173. * @NoAdminRequired
  174. * @NoSubAdminRequired
  175. *
  176. * @param int $id
  177. * @param array $scope
  178. * @param string $name
  179. * @return array|JSONResponse
  180. */
  181. public function update($id, array $scope, string $name) {
  182. if ($this->checkAppToken()) {
  183. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  184. }
  185. try {
  186. $token = $this->findTokenByIdAndUser($id);
  187. } catch (InvalidTokenException $e) {
  188. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  189. }
  190. $currentName = $token->getName();
  191. if ($scope !== $token->getScopeAsArray()) {
  192. $token->setScope([IToken::SCOPE_FILESYSTEM => $scope[IToken::SCOPE_FILESYSTEM]]);
  193. $this->publishActivity($scope[IToken::SCOPE_FILESYSTEM] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  194. }
  195. if (mb_strlen($name) > 128) {
  196. $name = mb_substr($name, 0, 120) . '…';
  197. }
  198. if ($token instanceof INamedToken && $name !== $currentName) {
  199. $token->setName($name);
  200. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  201. }
  202. $this->tokenProvider->updateToken($token);
  203. return [];
  204. }
  205. /**
  206. * @param string $subject
  207. * @param int $id
  208. * @param array $parameters
  209. */
  210. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  211. $event = $this->activityManager->generateEvent();
  212. $event->setApp('settings')
  213. ->setType('security')
  214. ->setAffectedUser($this->uid)
  215. ->setAuthor($this->uid)
  216. ->setSubject($subject, $parameters)
  217. ->setObject('app_token', $id, 'App Password');
  218. try {
  219. $this->activityManager->publish($event);
  220. } catch (BadMethodCallException $e) {
  221. $this->logger->warning('could not publish activity', ['exception' => $e]);
  222. }
  223. }
  224. /**
  225. * Find a token by given id and check if uid for current session belongs to this token
  226. *
  227. * @param int $id
  228. * @return IToken
  229. * @throws InvalidTokenException
  230. */
  231. private function findTokenByIdAndUser(int $id): IToken {
  232. try {
  233. $token = $this->tokenProvider->getTokenById($id);
  234. } catch (ExpiredTokenException $e) {
  235. $token = $e->getToken();
  236. }
  237. if ($token->getUID() !== $this->uid) {
  238. /** @psalm-suppress DeprecatedClass We have to throw the OC version so both OC and OCP catches catch it */
  239. throw new OcInvalidTokenException('This token does not belong to you!');
  240. }
  241. return $token;
  242. }
  243. /**
  244. * @NoAdminRequired
  245. * @NoSubAdminRequired
  246. * @PasswordConfirmationRequired
  247. *
  248. * @param int $id
  249. * @return JSONResponse
  250. * @throws InvalidTokenException
  251. * @throws ExpiredTokenException
  252. */
  253. public function wipe(int $id): JSONResponse {
  254. if ($this->checkAppToken()) {
  255. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  256. }
  257. try {
  258. $token = $this->findTokenByIdAndUser($id);
  259. } catch (InvalidTokenException $e) {
  260. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  261. }
  262. if (!$this->remoteWipe->markTokenForWipe($token)) {
  263. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  264. }
  265. return new JSONResponse([]);
  266. }
  267. }