AuthSettingsController.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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\Authentication\Exceptions\InvalidTokenException;
  30. use OC\Authentication\Exceptions\PasswordlessTokenException;
  31. use OC\Authentication\Exceptions\WipeTokenException;
  32. use OC\Authentication\Token\INamedToken;
  33. use OC\Authentication\Token\IProvider;
  34. use OC\Authentication\Token\IToken;
  35. use OC\Authentication\Token\IWipeableToken;
  36. use OC\Settings\Activity\Provider;
  37. use OCP\Activity\IManager;
  38. use OCP\AppFramework\Controller;
  39. use OCP\AppFramework\Http;
  40. use OCP\AppFramework\Http\JSONResponse;
  41. use OCP\ILogger;
  42. use OCP\IRequest;
  43. use OCP\ISession;
  44. use OCP\Security\ISecureRandom;
  45. use OCP\Session\Exceptions\SessionNotAvailableException;
  46. class AuthSettingsController extends Controller {
  47. /** @var IProvider */
  48. private $tokenProvider;
  49. /** @var ISession */
  50. private $session;
  51. /** @var string */
  52. private $uid;
  53. /** @var ISecureRandom */
  54. private $random;
  55. /** @var IManager */
  56. private $activityManager;
  57. /** @var ILogger */
  58. private $logger;
  59. /**
  60. * @param string $appName
  61. * @param IRequest $request
  62. * @param IProvider $tokenProvider
  63. * @param ISession $session
  64. * @param ISecureRandom $random
  65. * @param string|null $userId
  66. * @param IManager $activityManager
  67. * @param ILogger $logger
  68. */
  69. public function __construct(string $appName,
  70. IRequest $request,
  71. IProvider $tokenProvider,
  72. ISession $session,
  73. ISecureRandom $random,
  74. ?string $userId,
  75. IManager $activityManager,
  76. ILogger $logger) {
  77. parent::__construct($appName, $request);
  78. $this->tokenProvider = $tokenProvider;
  79. $this->uid = $userId;
  80. $this->session = $session;
  81. $this->random = $random;
  82. $this->activityManager = $activityManager;
  83. $this->logger = $logger;
  84. }
  85. /**
  86. * @NoAdminRequired
  87. * @NoSubadminRequired
  88. * @PasswordConfirmationRequired
  89. *
  90. * @param string $name
  91. * @return JSONResponse
  92. */
  93. public function create($name) {
  94. try {
  95. $sessionId = $this->session->getId();
  96. } catch (SessionNotAvailableException $ex) {
  97. return $this->getServiceNotAvailableResponse();
  98. }
  99. try {
  100. $sessionToken = $this->tokenProvider->getToken($sessionId);
  101. $loginName = $sessionToken->getLoginName();
  102. try {
  103. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  104. } catch (PasswordlessTokenException $ex) {
  105. $password = null;
  106. }
  107. } catch (InvalidTokenException $ex) {
  108. return $this->getServiceNotAvailableResponse();
  109. }
  110. $token = $this->generateRandomDeviceToken();
  111. $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  112. $tokenData = $deviceToken->jsonSerialize();
  113. $tokenData['canDelete'] = true;
  114. $tokenData['canRename'] = true;
  115. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  116. return new JSONResponse([
  117. 'token' => $token,
  118. 'loginName' => $loginName,
  119. 'deviceToken' => $tokenData,
  120. ]);
  121. }
  122. /**
  123. * @return JSONResponse
  124. */
  125. private function getServiceNotAvailableResponse() {
  126. $resp = new JSONResponse();
  127. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  128. return $resp;
  129. }
  130. /**
  131. * Return a 25 digit device password
  132. *
  133. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  134. *
  135. * @return string
  136. */
  137. private function generateRandomDeviceToken() {
  138. $groups = [];
  139. for ($i = 0; $i < 5; $i++) {
  140. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  141. }
  142. return implode('-', $groups);
  143. }
  144. /**
  145. * @NoAdminRequired
  146. * @NoSubadminRequired
  147. *
  148. * @param int $id
  149. * @return array|JSONResponse
  150. */
  151. public function destroy($id) {
  152. try {
  153. $token = $this->findTokenByIdAndUser($id);
  154. } catch (WipeTokenException $e) {
  155. //continue as we can destroy tokens in wipe
  156. $token = $e->getToken();
  157. } catch (InvalidTokenException $e) {
  158. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  159. }
  160. $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
  161. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  162. return [];
  163. }
  164. /**
  165. * @NoAdminRequired
  166. * @NoSubadminRequired
  167. *
  168. * @param int $id
  169. * @param array $scope
  170. * @param string $name
  171. * @return array|JSONResponse
  172. */
  173. public function update($id, array $scope, string $name) {
  174. try {
  175. $token = $this->findTokenByIdAndUser($id);
  176. } catch (InvalidTokenException $e) {
  177. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  178. }
  179. $currentName = $token->getName();
  180. if ($scope !== $token->getScopeAsArray()) {
  181. $token->setScope(['filesystem' => $scope['filesystem']]);
  182. $this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  183. }
  184. if ($token instanceof INamedToken && $name !== $currentName) {
  185. $token->setName($name);
  186. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  187. }
  188. $this->tokenProvider->updateToken($token);
  189. return [];
  190. }
  191. /**
  192. * @param string $subject
  193. * @param int $id
  194. * @param array $parameters
  195. */
  196. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  197. $event = $this->activityManager->generateEvent();
  198. $event->setApp('settings')
  199. ->setType('security')
  200. ->setAffectedUser($this->uid)
  201. ->setAuthor($this->uid)
  202. ->setSubject($subject, $parameters)
  203. ->setObject('app_token', $id, 'App Password');
  204. try {
  205. $this->activityManager->publish($event);
  206. } catch (BadMethodCallException $e) {
  207. $this->logger->warning('could not publish activity');
  208. $this->logger->logException($e);
  209. }
  210. }
  211. /**
  212. * Find a token by given id and check if uid for current session belongs to this token
  213. *
  214. * @param int $id
  215. * @return IToken
  216. * @throws InvalidTokenException
  217. * @throws \OC\Authentication\Exceptions\ExpiredTokenException
  218. */
  219. private function findTokenByIdAndUser(int $id): IToken {
  220. $token = $this->tokenProvider->getTokenById($id);
  221. if ($token->getUID() !== $this->uid) {
  222. throw new InvalidTokenException('This token does not belong to you!');
  223. }
  224. return $token;
  225. }
  226. /**
  227. * @NoAdminRequired
  228. * @NoSubadminRequired
  229. * @PasswordConfirmationRequired
  230. *
  231. * @param int $id
  232. * @return JSONResponse
  233. * @throws InvalidTokenException
  234. * @throws \OC\Authentication\Exceptions\ExpiredTokenException
  235. */
  236. public function wipe(int $id): JSONResponse {
  237. $token = $this->tokenProvider->getTokenById($id);
  238. if (!($token instanceof IWipeableToken)) {
  239. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  240. }
  241. $token->wipe();
  242. $this->tokenProvider->updateToken($token);
  243. return new JSONResponse([]);
  244. }
  245. }