AuthSettingsController.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@owncloud.com>
  6. * @author Fabrizio Steiner <fabrizio.steiner@gmail.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Marcel Waldvogel <marcel.waldvogel@uni-konstanz.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Settings\Controller;
  28. use BadMethodCallException;
  29. use OC\AppFramework\Http;
  30. use OC\Authentication\Exceptions\InvalidTokenException;
  31. use OC\Authentication\Exceptions\PasswordlessTokenException;
  32. use OC\Authentication\Token\INamedToken;
  33. use OC\Authentication\Token\IProvider;
  34. use OC\Authentication\Token\IToken;
  35. use OC\Settings\Activity\Provider;
  36. use OCP\Activity\IManager;
  37. use OC\Authentication\Token\PublicKeyToken;
  38. use OCP\AppFramework\Controller;
  39. use OCP\AppFramework\Http\JSONResponse;
  40. use OCP\ILogger;
  41. use OCP\IRequest;
  42. use OCP\ISession;
  43. use OCP\Security\ISecureRandom;
  44. use OCP\Session\Exceptions\SessionNotAvailableException;
  45. class AuthSettingsController extends Controller {
  46. /** @var IProvider */
  47. private $tokenProvider;
  48. /** @var ISession */
  49. private $session;
  50. /** @var string */
  51. private $uid;
  52. /** @var ISecureRandom */
  53. private $random;
  54. /** @var IManager */
  55. private $activityManager;
  56. /** @var ILogger */
  57. private $logger;
  58. /**
  59. * @param string $appName
  60. * @param IRequest $request
  61. * @param IProvider $tokenProvider
  62. * @param ISession $session
  63. * @param ISecureRandom $random
  64. * @param string|null $userId
  65. * @param IManager $activityManager
  66. * @param ILogger $logger
  67. */
  68. public function __construct(string $appName,
  69. IRequest $request,
  70. IProvider $tokenProvider,
  71. ISession $session,
  72. ISecureRandom $random,
  73. ?string $userId,
  74. IManager $activityManager,
  75. ILogger $logger) {
  76. parent::__construct($appName, $request);
  77. $this->tokenProvider = $tokenProvider;
  78. $this->uid = $userId;
  79. $this->session = $session;
  80. $this->random = $random;
  81. $this->activityManager = $activityManager;
  82. $this->logger = $logger;
  83. }
  84. /**
  85. * @NoAdminRequired
  86. * @NoSubadminRequired
  87. * @PasswordConfirmationRequired
  88. *
  89. * @param string $name
  90. * @return JSONResponse
  91. */
  92. public function create($name) {
  93. try {
  94. $sessionId = $this->session->getId();
  95. } catch (SessionNotAvailableException $ex) {
  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. $token = $this->generateRandomDeviceToken();
  110. $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  111. $tokenData = $deviceToken->jsonSerialize();
  112. $tokenData['canDelete'] = true;
  113. $tokenData['canRename'] = true;
  114. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  115. return new JSONResponse([
  116. 'token' => $token,
  117. 'loginName' => $loginName,
  118. 'deviceToken' => $tokenData,
  119. ]);
  120. }
  121. /**
  122. * @return JSONResponse
  123. */
  124. private function getServiceNotAvailableResponse() {
  125. $resp = new JSONResponse();
  126. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  127. return $resp;
  128. }
  129. /**
  130. * Return a 25 digit device password
  131. *
  132. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  133. *
  134. * @return string
  135. */
  136. private function generateRandomDeviceToken() {
  137. $groups = [];
  138. for ($i = 0; $i < 5; $i++) {
  139. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  140. }
  141. return implode('-', $groups);
  142. }
  143. /**
  144. * @NoAdminRequired
  145. * @NoSubadminRequired
  146. *
  147. * @param int $id
  148. * @return array|JSONResponse
  149. */
  150. public function destroy($id) {
  151. try {
  152. $token = $this->findTokenByIdAndUser($id);
  153. } catch (InvalidTokenException $e) {
  154. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  155. }
  156. $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
  157. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  158. return [];
  159. }
  160. /**
  161. * @NoAdminRequired
  162. * @NoSubadminRequired
  163. *
  164. * @param int $id
  165. * @param array $scope
  166. * @param string $name
  167. * @return array|JSONResponse
  168. */
  169. public function update($id, array $scope, string $name) {
  170. try {
  171. $token = $this->findTokenByIdAndUser($id);
  172. } catch (InvalidTokenException $e) {
  173. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  174. }
  175. $currentName = $token->getName();
  176. if ($scope !== $token->getScopeAsArray()) {
  177. $token->setScope(['filesystem' => $scope['filesystem']]);
  178. $this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  179. }
  180. if ($token instanceof INamedToken && $name !== $currentName) {
  181. $token->setName($name);
  182. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  183. }
  184. $this->tokenProvider->updateToken($token);
  185. return [];
  186. }
  187. /**
  188. * @param string $subject
  189. * @param int $id
  190. * @param array $parameters
  191. */
  192. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  193. $event = $this->activityManager->generateEvent();
  194. $event->setApp('settings')
  195. ->setType('security')
  196. ->setAffectedUser($this->uid)
  197. ->setAuthor($this->uid)
  198. ->setSubject($subject, $parameters)
  199. ->setObject('app_token', $id, 'App Password');
  200. try {
  201. $this->activityManager->publish($event);
  202. } catch (BadMethodCallException $e) {
  203. $this->logger->warning('could not publish activity');
  204. $this->logger->logException($e);
  205. }
  206. }
  207. /**
  208. * Find a token by given id and check if uid for current session belongs to this token
  209. *
  210. * @param int $id
  211. * @return IToken
  212. * @throws InvalidTokenException
  213. * @throws \OC\Authentication\Exceptions\ExpiredTokenException
  214. */
  215. private function findTokenByIdAndUser(int $id): IToken {
  216. $token = $this->tokenProvider->getTokenById($id);
  217. if ($token->getUID() !== $this->uid) {
  218. throw new InvalidTokenException('This token does not belong to you!');
  219. }
  220. return $token;
  221. }
  222. }