1
0

ClientFlowLoginV2Controller.php 7.9 KB

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