ClientFlowLoginV2Controller.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 OCP\AppFramework\Controller;
  31. use OCP\AppFramework\Http;
  32. use OCP\AppFramework\Http\JSONResponse;
  33. use OCP\AppFramework\Http\RedirectResponse;
  34. use OCP\AppFramework\Http\Response;
  35. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  36. use OCP\Defaults;
  37. use OCP\IL10N;
  38. use OCP\IRequest;
  39. use OCP\ISession;
  40. use OCP\IURLGenerator;
  41. use OCP\Security\ISecureRandom;
  42. class ClientFlowLoginV2Controller extends Controller {
  43. public const TOKEN_NAME = 'client.flow.v2.login.token';
  44. public const STATE_NAME = 'client.flow.v2.state.token';
  45. /** @var LoginFlowV2Service */
  46. private $loginFlowV2Service;
  47. /** @var IURLGenerator */
  48. private $urlGenerator;
  49. /** @var ISession */
  50. private $session;
  51. /** @var ISecureRandom */
  52. private $random;
  53. /** @var Defaults */
  54. private $defaults;
  55. /** @var string */
  56. private $userId;
  57. /** @var IL10N */
  58. private $l10n;
  59. public function __construct(string $appName,
  60. IRequest $request,
  61. LoginFlowV2Service $loginFlowV2Service,
  62. IURLGenerator $urlGenerator,
  63. ISession $session,
  64. ISecureRandom $random,
  65. Defaults $defaults,
  66. ?string $userId,
  67. IL10N $l10n) {
  68. parent::__construct($appName, $request);
  69. $this->loginFlowV2Service = $loginFlowV2Service;
  70. $this->urlGenerator = $urlGenerator;
  71. $this->session = $session;
  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. * @UseSession
  93. */
  94. public function landing(string $token): 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')
  101. );
  102. }
  103. /**
  104. * @NoCSRFRequired
  105. * @PublicPage
  106. * @UseSession
  107. */
  108. public function showAuthPickerPage(): 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. ],
  128. 'guest'
  129. );
  130. }
  131. /**
  132. * @NoAdminRequired
  133. * @UseSession
  134. * @NoCSRFRequired
  135. * @NoSameSiteCookieRequired
  136. */
  137. public function grantPage(string $stateToken): StandaloneTemplateResponse {
  138. if (!$this->isValidStateToken($stateToken)) {
  139. return $this->stateTokenForbiddenResponse();
  140. }
  141. try {
  142. $flow = $this->getFlowByLoginToken();
  143. } catch (LoginFlowV2NotFoundException $e) {
  144. return $this->loginTokenForbiddenResponse();
  145. }
  146. return new StandaloneTemplateResponse(
  147. $this->appName,
  148. 'loginflowv2/grant',
  149. [
  150. 'client' => $flow->getClientName(),
  151. 'instanceName' => $this->defaults->getName(),
  152. 'urlGenerator' => $this->urlGenerator,
  153. 'stateToken' => $stateToken,
  154. ],
  155. 'guest'
  156. );
  157. }
  158. /**
  159. * @NoAdminRequired
  160. * @UseSession
  161. */
  162. public function generateAppPassword(string $stateToken): Response {
  163. if (!$this->isValidStateToken($stateToken)) {
  164. return $this->stateTokenForbiddenResponse();
  165. }
  166. try {
  167. $this->getFlowByLoginToken();
  168. } catch (LoginFlowV2NotFoundException $e) {
  169. return $this->loginTokenForbiddenResponse();
  170. }
  171. $loginToken = $this->session->get(self::TOKEN_NAME);
  172. // Clear session variables
  173. $this->session->remove(self::TOKEN_NAME);
  174. $this->session->remove(self::STATE_NAME);
  175. $sessionId = $this->session->getId();
  176. $result = $this->loginFlowV2Service->flowDone($loginToken, $sessionId, $this->getServerPath(), $this->userId);
  177. if ($result) {
  178. return new StandaloneTemplateResponse(
  179. $this->appName,
  180. 'loginflowv2/done',
  181. [],
  182. 'guest'
  183. );
  184. }
  185. $response = new StandaloneTemplateResponse(
  186. $this->appName,
  187. '403',
  188. [
  189. 'message' => $this->l10n->t('Could not complete login'),
  190. ],
  191. 'guest'
  192. );
  193. $response->setStatus(Http::STATUS_FORBIDDEN);
  194. return $response;
  195. }
  196. /**
  197. * @NoCSRFRequired
  198. * @PublicPage
  199. */
  200. public function init(): JSONResponse {
  201. // Get client user agent
  202. $userAgent = $this->request->getHeader('USER_AGENT');
  203. $tokens = $this->loginFlowV2Service->createTokens($userAgent);
  204. $data = [
  205. 'poll' => [
  206. 'token' => $tokens->getPollToken(),
  207. 'endpoint' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.poll')
  208. ],
  209. 'login' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.landing', ['token' => $tokens->getLoginToken()]),
  210. ];
  211. return new JSONResponse($data);
  212. }
  213. private function isValidStateToken(string $stateToken): bool {
  214. $currentToken = $this->session->get(self::STATE_NAME);
  215. if (!is_string($stateToken) || !is_string($currentToken)) {
  216. return false;
  217. }
  218. return hash_equals($currentToken, $stateToken);
  219. }
  220. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  221. $response = new StandaloneTemplateResponse(
  222. $this->appName,
  223. '403',
  224. [
  225. 'message' => $this->l10n->t('State token does not match'),
  226. ],
  227. 'guest'
  228. );
  229. $response->setStatus(Http::STATUS_FORBIDDEN);
  230. return $response;
  231. }
  232. /**
  233. * @return LoginFlowV2
  234. * @throws LoginFlowV2NotFoundException
  235. */
  236. private function getFlowByLoginToken(): LoginFlowV2 {
  237. $currentToken = $this->session->get(self::TOKEN_NAME);
  238. if (!is_string($currentToken)) {
  239. throw new LoginFlowV2NotFoundException('Login token not set in session');
  240. }
  241. return $this->loginFlowV2Service->getByLoginToken($currentToken);
  242. }
  243. private function loginTokenForbiddenResponse(): StandaloneTemplateResponse {
  244. $response = new StandaloneTemplateResponse(
  245. $this->appName,
  246. '403',
  247. [
  248. 'message' => $this->l10n->t('Your login token is invalid or has expired'),
  249. ],
  250. 'guest'
  251. );
  252. $response->setStatus(Http::STATUS_FORBIDDEN);
  253. return $response;
  254. }
  255. private function getServerPath(): string {
  256. $serverPostfix = '';
  257. if (strpos($this->request->getRequestUri(), '/index.php') !== false) {
  258. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  259. } elseif (strpos($this->request->getRequestUri(), '/login/v2') !== false) {
  260. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/v2'));
  261. }
  262. $protocol = $this->request->getServerProtocol();
  263. return $protocol . '://' . $this->request->getServerHost() . $serverPostfix;
  264. }
  265. }