1
0

ClientFlowLoginV2Controller.php 10 KB

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