AuthSettingsController.php 8.4 KB

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