ClientFlowLoginV2Controller.php 10 KB

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