1
0

ClientFlowLoginV2Controller.php 11 KB

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