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 Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC\Core\Controller;
  26. use OC\Core\Db\LoginFlowV2;
  27. use OC\Core\Exception\LoginFlowV2NotFoundException;
  28. use OC\Core\Service\LoginFlowV2Service;
  29. use OCP\AppFramework\Controller;
  30. use OCP\AppFramework\Http;
  31. use OCP\AppFramework\Http\JSONResponse;
  32. use OCP\AppFramework\Http\RedirectResponse;
  33. use OCP\AppFramework\Http\Response;
  34. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  35. use OCP\Defaults;
  36. use OCP\IL10N;
  37. use OCP\IRequest;
  38. use OCP\ISession;
  39. use OCP\IURLGenerator;
  40. use OCP\Security\ISecureRandom;
  41. class ClientFlowLoginV2Controller extends Controller {
  42. public const TOKEN_NAME = 'client.flow.v2.login.token';
  43. public const STATE_NAME = 'client.flow.v2.state.token';
  44. /** @var LoginFlowV2Service */
  45. private $loginFlowV2Service;
  46. /** @var IURLGenerator */
  47. private $urlGenerator;
  48. /** @var ISession */
  49. private $session;
  50. /** @var ISecureRandom */
  51. private $random;
  52. /** @var Defaults */
  53. private $defaults;
  54. /** @var string */
  55. private $userId;
  56. /** @var IL10N */
  57. private $l10n;
  58. public function __construct(string $appName,
  59. IRequest $request,
  60. LoginFlowV2Service $loginFlowV2Service,
  61. IURLGenerator $urlGenerator,
  62. ISession $session,
  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->random = $random;
  72. $this->defaults = $defaults;
  73. $this->userId = $userId;
  74. $this->l10n = $l10n;
  75. }
  76. /**
  77. * @NoCSRFRequired
  78. * @PublicPage
  79. */
  80. public function poll(string $token): JSONResponse {
  81. try {
  82. $creds = $this->loginFlowV2Service->poll($token);
  83. } catch (LoginFlowV2NotFoundException $e) {
  84. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  85. }
  86. return new JSONResponse($creds);
  87. }
  88. /**
  89. * @NoCSRFRequired
  90. * @PublicPage
  91. * @UseSession
  92. */
  93. public function landing(string $token): Response {
  94. if (!$this->loginFlowV2Service->startLoginFlow($token)) {
  95. return $this->loginTokenForbiddenResponse();
  96. }
  97. $this->session->set(self::TOKEN_NAME, $token);
  98. return new RedirectResponse(
  99. $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.showAuthPickerPage')
  100. );
  101. }
  102. /**
  103. * @NoCSRFRequired
  104. * @PublicPage
  105. * @UseSession
  106. */
  107. public function showAuthPickerPage(): StandaloneTemplateResponse {
  108. try {
  109. $flow = $this->getFlowByLoginToken();
  110. } catch (LoginFlowV2NotFoundException $e) {
  111. return $this->loginTokenForbiddenResponse();
  112. }
  113. $stateToken = $this->random->generate(
  114. 64,
  115. ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
  116. );
  117. $this->session->set(self::STATE_NAME, $stateToken);
  118. return new StandaloneTemplateResponse(
  119. $this->appName,
  120. 'loginflowv2/authpicker',
  121. [
  122. 'client' => $flow->getClientName(),
  123. 'instanceName' => $this->defaults->getName(),
  124. 'urlGenerator' => $this->urlGenerator,
  125. 'stateToken' => $stateToken,
  126. ],
  127. 'guest'
  128. );
  129. }
  130. /**
  131. * @NoAdminRequired
  132. * @UseSession
  133. * @NoCSRFRequired
  134. * @NoSameSiteCookieRequired
  135. */
  136. public function grantPage(string $stateToken): StandaloneTemplateResponse {
  137. if (!$this->isValidStateToken($stateToken)) {
  138. return $this->stateTokenForbiddenResponse();
  139. }
  140. try {
  141. $flow = $this->getFlowByLoginToken();
  142. } catch (LoginFlowV2NotFoundException $e) {
  143. return $this->loginTokenForbiddenResponse();
  144. }
  145. return new StandaloneTemplateResponse(
  146. $this->appName,
  147. 'loginflowv2/grant',
  148. [
  149. 'client' => $flow->getClientName(),
  150. 'instanceName' => $this->defaults->getName(),
  151. 'urlGenerator' => $this->urlGenerator,
  152. 'stateToken' => $stateToken,
  153. ],
  154. 'guest'
  155. );
  156. }
  157. /**
  158. * @NoAdminRequired
  159. * @UseSession
  160. */
  161. public function generateAppPassword(string $stateToken): Response {
  162. if (!$this->isValidStateToken($stateToken)) {
  163. return $this->stateTokenForbiddenResponse();
  164. }
  165. try {
  166. $this->getFlowByLoginToken();
  167. } catch (LoginFlowV2NotFoundException $e) {
  168. return $this->loginTokenForbiddenResponse();
  169. }
  170. $loginToken = $this->session->get(self::TOKEN_NAME);
  171. // Clear session variables
  172. $this->session->remove(self::TOKEN_NAME);
  173. $this->session->remove(self::STATE_NAME);
  174. $sessionId = $this->session->getId();
  175. $result = $this->loginFlowV2Service->flowDone($loginToken, $sessionId, $this->getServerPath(), $this->userId);
  176. if ($result) {
  177. return new StandaloneTemplateResponse(
  178. $this->appName,
  179. 'loginflowv2/done',
  180. [],
  181. 'guest'
  182. );
  183. }
  184. $response = new StandaloneTemplateResponse(
  185. $this->appName,
  186. '403',
  187. [
  188. 'message' => $this->l10n->t('Could not complete login'),
  189. ],
  190. 'guest'
  191. );
  192. $response->setStatus(Http::STATUS_FORBIDDEN);
  193. return $response;
  194. }
  195. /**
  196. * @NoCSRFRequired
  197. * @PublicPage
  198. */
  199. public function init(): JSONResponse {
  200. // Get client user agent
  201. $userAgent = $this->request->getHeader('USER_AGENT');
  202. $tokens = $this->loginFlowV2Service->createTokens($userAgent);
  203. $data = [
  204. 'poll' => [
  205. 'token' => $tokens->getPollToken(),
  206. 'endpoint' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.poll')
  207. ],
  208. 'login' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.landing', ['token' => $tokens->getLoginToken()]),
  209. ];
  210. return new JSONResponse($data);
  211. }
  212. private function isValidStateToken(string $stateToken): bool {
  213. $currentToken = $this->session->get(self::STATE_NAME);
  214. if (!is_string($stateToken) || !is_string($currentToken)) {
  215. return false;
  216. }
  217. return hash_equals($currentToken, $stateToken);
  218. }
  219. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  220. $response = new StandaloneTemplateResponse(
  221. $this->appName,
  222. '403',
  223. [
  224. 'message' => $this->l10n->t('State token does not match'),
  225. ],
  226. 'guest'
  227. );
  228. $response->setStatus(Http::STATUS_FORBIDDEN);
  229. return $response;
  230. }
  231. /**
  232. * @return LoginFlowV2
  233. * @throws LoginFlowV2NotFoundException
  234. */
  235. private function getFlowByLoginToken(): LoginFlowV2 {
  236. $currentToken = $this->session->get(self::TOKEN_NAME);
  237. if (!is_string($currentToken)) {
  238. throw new LoginFlowV2NotFoundException('Login token not set in session');
  239. }
  240. return $this->loginFlowV2Service->getByLoginToken($currentToken);
  241. }
  242. private function loginTokenForbiddenResponse(): StandaloneTemplateResponse {
  243. $response = new StandaloneTemplateResponse(
  244. $this->appName,
  245. '403',
  246. [
  247. 'message' => $this->l10n->t('Your login token is invalid or has expired'),
  248. ],
  249. 'guest'
  250. );
  251. $response->setStatus(Http::STATUS_FORBIDDEN);
  252. return $response;
  253. }
  254. private function getServerPath(): string {
  255. $serverPostfix = '';
  256. if (strpos($this->request->getRequestUri(), '/index.php') !== false) {
  257. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  258. } elseif (strpos($this->request->getRequestUri(), '/login/v2') !== false) {
  259. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/v2'));
  260. }
  261. $protocol = $this->request->getServerProtocol();
  262. return $protocol . '://' . $this->request->getServerHost() . $serverPostfix;
  263. }
  264. }