You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthSettingsController.php 8.0KB

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