ClientFlowLoginV2Controller.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Core\Db\LoginFlowV2;
  9. use OC\Core\Exception\LoginFlowV2NotFoundException;
  10. use OC\Core\ResponseDefinitions;
  11. use OC\Core\Service\LoginFlowV2Service;
  12. use OCP\AppFramework\Controller;
  13. use OCP\AppFramework\Http;
  14. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  15. use OCP\AppFramework\Http\Attribute\OpenAPI;
  16. use OCP\AppFramework\Http\Attribute\UseSession;
  17. use OCP\AppFramework\Http\JSONResponse;
  18. use OCP\AppFramework\Http\RedirectResponse;
  19. use OCP\AppFramework\Http\Response;
  20. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  21. use OCP\Authentication\Exceptions\InvalidTokenException;
  22. use OCP\Defaults;
  23. use OCP\IL10N;
  24. use OCP\IRequest;
  25. use OCP\ISession;
  26. use OCP\IURLGenerator;
  27. use OCP\IUser;
  28. use OCP\IUserSession;
  29. use OCP\Security\ISecureRandom;
  30. /**
  31. * @psalm-import-type CoreLoginFlowV2Credentials from ResponseDefinitions
  32. * @psalm-import-type CoreLoginFlowV2 from ResponseDefinitions
  33. */
  34. class ClientFlowLoginV2Controller extends Controller {
  35. public const TOKEN_NAME = 'client.flow.v2.login.token';
  36. public const STATE_NAME = 'client.flow.v2.state.token';
  37. public function __construct(
  38. string $appName,
  39. IRequest $request,
  40. private LoginFlowV2Service $loginFlowV2Service,
  41. private IURLGenerator $urlGenerator,
  42. private ISession $session,
  43. private IUserSession $userSession,
  44. private ISecureRandom $random,
  45. private Defaults $defaults,
  46. private ?string $userId,
  47. private IL10N $l10n,
  48. ) {
  49. parent::__construct($appName, $request);
  50. }
  51. /**
  52. * @NoCSRFRequired
  53. * @PublicPage
  54. *
  55. * Poll the login flow credentials
  56. *
  57. * @param string $token Token of the flow
  58. * @return JSONResponse<Http::STATUS_OK, CoreLoginFlowV2Credentials, array{}>|JSONResponse<Http::STATUS_NOT_FOUND, array<empty>, array{}>
  59. *
  60. * 200: Login flow credentials returned
  61. * 404: Login flow not found or completed
  62. */
  63. #[FrontpageRoute(verb: 'POST', url: '/login/v2/poll')]
  64. public function poll(string $token): JSONResponse {
  65. try {
  66. $creds = $this->loginFlowV2Service->poll($token);
  67. } catch (LoginFlowV2NotFoundException $e) {
  68. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  69. }
  70. return new JSONResponse($creds->jsonSerialize());
  71. }
  72. /**
  73. * @NoCSRFRequired
  74. * @PublicPage
  75. */
  76. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  77. #[UseSession]
  78. #[FrontpageRoute(verb: 'GET', url: '/login/v2/flow/{token}')]
  79. public function landing(string $token, $user = ''): Response {
  80. if (!$this->loginFlowV2Service->startLoginFlow($token)) {
  81. return $this->loginTokenForbiddenResponse();
  82. }
  83. $this->session->set(self::TOKEN_NAME, $token);
  84. return new RedirectResponse(
  85. $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.showAuthPickerPage', ['user' => $user])
  86. );
  87. }
  88. /**
  89. * @NoCSRFRequired
  90. * @PublicPage
  91. */
  92. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  93. #[UseSession]
  94. #[FrontpageRoute(verb: 'GET', url: '/login/v2/flow')]
  95. public function showAuthPickerPage($user = ''): StandaloneTemplateResponse {
  96. try {
  97. $flow = $this->getFlowByLoginToken();
  98. } catch (LoginFlowV2NotFoundException $e) {
  99. return $this->loginTokenForbiddenResponse();
  100. }
  101. $stateToken = $this->random->generate(
  102. 64,
  103. ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
  104. );
  105. $this->session->set(self::STATE_NAME, $stateToken);
  106. return new StandaloneTemplateResponse(
  107. $this->appName,
  108. 'loginflowv2/authpicker',
  109. [
  110. 'client' => $flow->getClientName(),
  111. 'instanceName' => $this->defaults->getName(),
  112. 'urlGenerator' => $this->urlGenerator,
  113. 'stateToken' => $stateToken,
  114. 'user' => $user,
  115. ],
  116. 'guest'
  117. );
  118. }
  119. /**
  120. * @NoAdminRequired
  121. * @NoCSRFRequired
  122. * @NoSameSiteCookieRequired
  123. */
  124. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  125. #[UseSession]
  126. #[FrontpageRoute(verb: 'GET', url: '/login/v2/grant')]
  127. public function grantPage(?string $stateToken): StandaloneTemplateResponse {
  128. if ($stateToken === null) {
  129. return $this->stateTokenMissingResponse();
  130. }
  131. if (!$this->isValidStateToken($stateToken)) {
  132. return $this->stateTokenForbiddenResponse();
  133. }
  134. try {
  135. $flow = $this->getFlowByLoginToken();
  136. } catch (LoginFlowV2NotFoundException $e) {
  137. return $this->loginTokenForbiddenResponse();
  138. }
  139. /** @var IUser $user */
  140. $user = $this->userSession->getUser();
  141. return new StandaloneTemplateResponse(
  142. $this->appName,
  143. 'loginflowv2/grant',
  144. [
  145. 'userId' => $user->getUID(),
  146. 'userDisplayName' => $user->getDisplayName(),
  147. 'client' => $flow->getClientName(),
  148. 'instanceName' => $this->defaults->getName(),
  149. 'urlGenerator' => $this->urlGenerator,
  150. 'stateToken' => $stateToken,
  151. ],
  152. 'guest'
  153. );
  154. }
  155. /**
  156. * @PublicPage
  157. */
  158. #[FrontpageRoute(verb: 'POST', url: '/login/v2/apptoken')]
  159. public function apptokenRedirect(?string $stateToken, string $user, string $password) {
  160. if ($stateToken === null) {
  161. return $this->stateTokenMissingResponse();
  162. }
  163. if (!$this->isValidStateToken($stateToken)) {
  164. return $this->stateTokenForbiddenResponse();
  165. }
  166. try {
  167. $this->getFlowByLoginToken();
  168. } catch (LoginFlowV2NotFoundException $e) {
  169. return $this->loginTokenForbiddenResponse();
  170. }
  171. $loginToken = $this->session->get(self::TOKEN_NAME);
  172. // Clear session variables
  173. $this->session->remove(self::TOKEN_NAME);
  174. $this->session->remove(self::STATE_NAME);
  175. try {
  176. $token = \OC::$server->get(\OC\Authentication\Token\IProvider::class)->getToken($password);
  177. if ($token->getLoginName() !== $user) {
  178. throw new InvalidTokenException('login name does not match');
  179. }
  180. } catch (InvalidTokenException $e) {
  181. $response = new StandaloneTemplateResponse(
  182. $this->appName,
  183. '403',
  184. [
  185. 'message' => $this->l10n->t('Invalid app password'),
  186. ],
  187. 'guest'
  188. );
  189. $response->setStatus(Http::STATUS_FORBIDDEN);
  190. return $response;
  191. }
  192. $result = $this->loginFlowV2Service->flowDoneWithAppPassword($loginToken, $this->getServerPath(), $token->getLoginName(), $password);
  193. return $this->handleFlowDone($result);
  194. }
  195. /**
  196. * @NoAdminRequired
  197. */
  198. #[UseSession]
  199. #[FrontpageRoute(verb: 'POST', url: '/login/v2/grant')]
  200. public function generateAppPassword(?string $stateToken): Response {
  201. if ($stateToken === null) {
  202. return $this->stateTokenMissingResponse();
  203. }
  204. if (!$this->isValidStateToken($stateToken)) {
  205. return $this->stateTokenForbiddenResponse();
  206. }
  207. try {
  208. $this->getFlowByLoginToken();
  209. } catch (LoginFlowV2NotFoundException $e) {
  210. return $this->loginTokenForbiddenResponse();
  211. }
  212. $loginToken = $this->session->get(self::TOKEN_NAME);
  213. // Clear session variables
  214. $this->session->remove(self::TOKEN_NAME);
  215. $this->session->remove(self::STATE_NAME);
  216. $sessionId = $this->session->getId();
  217. $result = $this->loginFlowV2Service->flowDone($loginToken, $sessionId, $this->getServerPath(), $this->userId);
  218. return $this->handleFlowDone($result);
  219. }
  220. private function handleFlowDone(bool $result): StandaloneTemplateResponse {
  221. if ($result) {
  222. return new StandaloneTemplateResponse(
  223. $this->appName,
  224. 'loginflowv2/done',
  225. [],
  226. 'guest'
  227. );
  228. }
  229. $response = new StandaloneTemplateResponse(
  230. $this->appName,
  231. '403',
  232. [
  233. 'message' => $this->l10n->t('Could not complete login'),
  234. ],
  235. 'guest'
  236. );
  237. $response->setStatus(Http::STATUS_FORBIDDEN);
  238. return $response;
  239. }
  240. /**
  241. * @NoCSRFRequired
  242. * @PublicPage
  243. *
  244. * Init a login flow
  245. *
  246. * @return JSONResponse<Http::STATUS_OK, CoreLoginFlowV2, array{}>
  247. *
  248. * 200: Login flow init returned
  249. */
  250. #[FrontpageRoute(verb: 'POST', url: '/login/v2')]
  251. public function init(): JSONResponse {
  252. // Get client user agent
  253. $userAgent = $this->request->getHeader('USER_AGENT');
  254. $tokens = $this->loginFlowV2Service->createTokens($userAgent);
  255. $data = [
  256. 'poll' => [
  257. 'token' => $tokens->getPollToken(),
  258. 'endpoint' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.poll')
  259. ],
  260. 'login' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.landing', ['token' => $tokens->getLoginToken()]),
  261. ];
  262. return new JSONResponse($data);
  263. }
  264. private function isValidStateToken(string $stateToken): bool {
  265. $currentToken = $this->session->get(self::STATE_NAME);
  266. if (!is_string($stateToken) || !is_string($currentToken)) {
  267. return false;
  268. }
  269. return hash_equals($currentToken, $stateToken);
  270. }
  271. private function stateTokenMissingResponse(): StandaloneTemplateResponse {
  272. $response = new StandaloneTemplateResponse(
  273. $this->appName,
  274. '403',
  275. [
  276. 'message' => $this->l10n->t('State token missing'),
  277. ],
  278. 'guest'
  279. );
  280. $response->setStatus(Http::STATUS_FORBIDDEN);
  281. return $response;
  282. }
  283. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  284. $response = new StandaloneTemplateResponse(
  285. $this->appName,
  286. '403',
  287. [
  288. 'message' => $this->l10n->t('State token does not match'),
  289. ],
  290. 'guest'
  291. );
  292. $response->setStatus(Http::STATUS_FORBIDDEN);
  293. return $response;
  294. }
  295. /**
  296. * @return LoginFlowV2
  297. * @throws LoginFlowV2NotFoundException
  298. */
  299. private function getFlowByLoginToken(): LoginFlowV2 {
  300. $currentToken = $this->session->get(self::TOKEN_NAME);
  301. if (!is_string($currentToken)) {
  302. throw new LoginFlowV2NotFoundException('Login token not set in session');
  303. }
  304. return $this->loginFlowV2Service->getByLoginToken($currentToken);
  305. }
  306. private function loginTokenForbiddenResponse(): StandaloneTemplateResponse {
  307. $response = new StandaloneTemplateResponse(
  308. $this->appName,
  309. '403',
  310. [
  311. 'message' => $this->l10n->t('Your login token is invalid or has expired'),
  312. ],
  313. 'guest'
  314. );
  315. $response->setStatus(Http::STATUS_FORBIDDEN);
  316. return $response;
  317. }
  318. private function getServerPath(): string {
  319. $serverPostfix = '';
  320. if (str_contains($this->request->getRequestUri(), '/index.php')) {
  321. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  322. } elseif (str_contains($this->request->getRequestUri(), '/login/v2')) {
  323. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/v2'));
  324. }
  325. $protocol = $this->request->getServerProtocol();
  326. return $protocol . '://' . $this->request->getServerHost() . $serverPostfix;
  327. }
  328. }