1
0

AuthSettingsController.php 7.7 KB

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