ClientFlowLoginV2Controller.php 9.7 KB

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