AuthSettingsController.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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\IRequest;
  48. use OCP\ISession;
  49. use OCP\IUserSession;
  50. use OCP\Security\ISecureRandom;
  51. use OCP\Session\Exceptions\SessionNotAvailableException;
  52. use Psr\Log\LoggerInterface;
  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 LoggerInterface */
  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 LoggerInterface $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. LoggerInterface $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. if ($this->checkAppToken()) {
  112. return $this->getServiceNotAvailableResponse();
  113. }
  114. try {
  115. $sessionId = $this->session->getId();
  116. } catch (SessionNotAvailableException $ex) {
  117. return $this->getServiceNotAvailableResponse();
  118. }
  119. if ($this->userSession->getImpersonatingUserID() !== null) {
  120. return $this->getServiceNotAvailableResponse();
  121. }
  122. try {
  123. $sessionToken = $this->tokenProvider->getToken($sessionId);
  124. $loginName = $sessionToken->getLoginName();
  125. try {
  126. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  127. } catch (PasswordlessTokenException $ex) {
  128. $password = null;
  129. }
  130. } catch (InvalidTokenException $ex) {
  131. return $this->getServiceNotAvailableResponse();
  132. }
  133. if (mb_strlen($name) > 128) {
  134. $name = mb_substr($name, 0, 120) . '…';
  135. }
  136. $token = $this->generateRandomDeviceToken();
  137. $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  138. $tokenData = $deviceToken->jsonSerialize();
  139. $tokenData['canDelete'] = true;
  140. $tokenData['canRename'] = true;
  141. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  142. return new JSONResponse([
  143. 'token' => $token,
  144. 'loginName' => $loginName,
  145. 'deviceToken' => $tokenData,
  146. ]);
  147. }
  148. /**
  149. * @return JSONResponse
  150. */
  151. private function getServiceNotAvailableResponse() {
  152. $resp = new JSONResponse();
  153. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  154. return $resp;
  155. }
  156. /**
  157. * Return a 25 digit device password
  158. *
  159. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  160. *
  161. * @return string
  162. */
  163. private function generateRandomDeviceToken() {
  164. $groups = [];
  165. for ($i = 0; $i < 5; $i++) {
  166. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  167. }
  168. return implode('-', $groups);
  169. }
  170. private function checkAppToken(): bool {
  171. return $this->session->exists('app_password');
  172. }
  173. /**
  174. * @NoAdminRequired
  175. * @NoSubAdminRequired
  176. *
  177. * @param int $id
  178. * @return array|JSONResponse
  179. */
  180. public function destroy($id) {
  181. if ($this->checkAppToken()) {
  182. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  183. }
  184. try {
  185. $token = $this->findTokenByIdAndUser($id);
  186. } catch (WipeTokenException $e) {
  187. //continue as we can destroy tokens in wipe
  188. $token = $e->getToken();
  189. } catch (InvalidTokenException $e) {
  190. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  191. }
  192. $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
  193. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  194. return [];
  195. }
  196. /**
  197. * @NoAdminRequired
  198. * @NoSubAdminRequired
  199. *
  200. * @param int $id
  201. * @param array $scope
  202. * @param string $name
  203. * @return array|JSONResponse
  204. */
  205. public function update($id, array $scope, string $name) {
  206. if ($this->checkAppToken()) {
  207. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  208. }
  209. try {
  210. $token = $this->findTokenByIdAndUser($id);
  211. } catch (InvalidTokenException $e) {
  212. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  213. }
  214. $currentName = $token->getName();
  215. if ($scope !== $token->getScopeAsArray()) {
  216. $token->setScope(['filesystem' => $scope['filesystem']]);
  217. $this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  218. }
  219. if (mb_strlen($name) > 128) {
  220. $name = mb_substr($name, 0, 120) . '…';
  221. }
  222. if ($token instanceof INamedToken && $name !== $currentName) {
  223. $token->setName($name);
  224. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  225. }
  226. $this->tokenProvider->updateToken($token);
  227. return [];
  228. }
  229. /**
  230. * @param string $subject
  231. * @param int $id
  232. * @param array $parameters
  233. */
  234. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  235. $event = $this->activityManager->generateEvent();
  236. $event->setApp('settings')
  237. ->setType('security')
  238. ->setAffectedUser($this->uid)
  239. ->setAuthor($this->uid)
  240. ->setSubject($subject, $parameters)
  241. ->setObject('app_token', $id, 'App Password');
  242. try {
  243. $this->activityManager->publish($event);
  244. } catch (BadMethodCallException $e) {
  245. $this->logger->warning('could not publish activity', ['exception' => $e]);
  246. }
  247. }
  248. /**
  249. * Find a token by given id and check if uid for current session belongs to this token
  250. *
  251. * @param int $id
  252. * @return IToken
  253. * @throws InvalidTokenException
  254. */
  255. private function findTokenByIdAndUser(int $id): IToken {
  256. try {
  257. $token = $this->tokenProvider->getTokenById($id);
  258. } catch (ExpiredTokenException $e) {
  259. $token = $e->getToken();
  260. }
  261. if ($token->getUID() !== $this->uid) {
  262. throw new InvalidTokenException('This token does not belong to you!');
  263. }
  264. return $token;
  265. }
  266. /**
  267. * @NoAdminRequired
  268. * @NoSubAdminRequired
  269. * @PasswordConfirmationRequired
  270. *
  271. * @param int $id
  272. * @return JSONResponse
  273. * @throws InvalidTokenException
  274. * @throws \OC\Authentication\Exceptions\ExpiredTokenException
  275. */
  276. public function wipe(int $id): JSONResponse {
  277. if ($this->checkAppToken()) {
  278. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  279. }
  280. try {
  281. $token = $this->findTokenByIdAndUser($id);
  282. } catch (InvalidTokenException $e) {
  283. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  284. }
  285. if (!$this->remoteWipe->markTokenForWipe($token)) {
  286. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  287. }
  288. return new JSONResponse([]);
  289. }
  290. }