ClientFlowLoginV2Controller.php 10 KB

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