ClientFlowLoginV2Controller.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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\JSONResponse;
  34. use OCP\AppFramework\Http\RedirectResponse;
  35. use OCP\AppFramework\Http\Response;
  36. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  37. use OCP\Defaults;
  38. use OCP\IL10N;
  39. use OCP\IRequest;
  40. use OCP\ISession;
  41. use OCP\IURLGenerator;
  42. use OCP\IUser;
  43. use OCP\IUserSession;
  44. use OCP\Security\ISecureRandom;
  45. class ClientFlowLoginV2Controller extends Controller {
  46. public const TOKEN_NAME = 'client.flow.v2.login.token';
  47. public const STATE_NAME = 'client.flow.v2.state.token';
  48. private LoginFlowV2Service $loginFlowV2Service;
  49. private IURLGenerator $urlGenerator;
  50. private IUserSession $userSession;
  51. private ISession $session;
  52. private ISecureRandom $random;
  53. private Defaults $defaults;
  54. private ?string $userId;
  55. private IL10N $l10n;
  56. public function __construct(string $appName,
  57. IRequest $request,
  58. LoginFlowV2Service $loginFlowV2Service,
  59. IURLGenerator $urlGenerator,
  60. ISession $session,
  61. IUserSession $userSession,
  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->userSession = $userSession;
  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, $user = ''): 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', ['user' => $user])
  100. );
  101. }
  102. /**
  103. * @NoCSRFRequired
  104. * @PublicPage
  105. * @UseSession
  106. */
  107. public function showAuthPickerPage($user = ''): 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. 'user' => $user,
  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. /** @var IUser $user */
  147. $user = $this->userSession->getUser();
  148. return new StandaloneTemplateResponse(
  149. $this->appName,
  150. 'loginflowv2/grant',
  151. [
  152. 'userId' => $user->getUID(),
  153. 'userDisplayName' => $user->getDisplayName(),
  154. 'client' => $flow->getClientName(),
  155. 'instanceName' => $this->defaults->getName(),
  156. 'urlGenerator' => $this->urlGenerator,
  157. 'stateToken' => $stateToken,
  158. ],
  159. 'guest'
  160. );
  161. }
  162. /**
  163. * @PublicPage
  164. */
  165. public function apptokenRedirect(string $stateToken, string $user, string $password) {
  166. if (!$this->isValidStateToken($stateToken)) {
  167. return $this->stateTokenForbiddenResponse();
  168. }
  169. try {
  170. $this->getFlowByLoginToken();
  171. } catch (LoginFlowV2NotFoundException $e) {
  172. return $this->loginTokenForbiddenResponse();
  173. }
  174. $loginToken = $this->session->get(self::TOKEN_NAME);
  175. // Clear session variables
  176. $this->session->remove(self::TOKEN_NAME);
  177. $this->session->remove(self::STATE_NAME);
  178. try {
  179. $token = \OC::$server->get(\OC\Authentication\Token\IProvider::class)->getToken($password);
  180. if ($token->getLoginName() !== $user) {
  181. throw new InvalidTokenException('login name does not match');
  182. }
  183. } catch (InvalidTokenException $e) {
  184. $response = new StandaloneTemplateResponse(
  185. $this->appName,
  186. '403',
  187. [
  188. 'message' => $this->l10n->t('Invalid app password'),
  189. ],
  190. 'guest'
  191. );
  192. $response->setStatus(Http::STATUS_FORBIDDEN);
  193. return $response;
  194. }
  195. $result = $this->loginFlowV2Service->flowDoneWithAppPassword($loginToken, $this->getServerPath(), $this->userId, $password);
  196. return $this->handleFlowDone($result);
  197. }
  198. /**
  199. * @NoAdminRequired
  200. * @UseSession
  201. */
  202. public function generateAppPassword(string $stateToken): Response {
  203. if (!$this->isValidStateToken($stateToken)) {
  204. return $this->stateTokenForbiddenResponse();
  205. }
  206. try {
  207. $this->getFlowByLoginToken();
  208. } catch (LoginFlowV2NotFoundException $e) {
  209. return $this->loginTokenForbiddenResponse();
  210. }
  211. $loginToken = $this->session->get(self::TOKEN_NAME);
  212. // Clear session variables
  213. $this->session->remove(self::TOKEN_NAME);
  214. $this->session->remove(self::STATE_NAME);
  215. $sessionId = $this->session->getId();
  216. $result = $this->loginFlowV2Service->flowDone($loginToken, $sessionId, $this->getServerPath(), $this->userId);
  217. return $this->handleFlowDone($result);
  218. }
  219. private function handleFlowDone(bool $result): StandaloneTemplateResponse {
  220. if ($result) {
  221. return new StandaloneTemplateResponse(
  222. $this->appName,
  223. 'loginflowv2/done',
  224. [],
  225. 'guest'
  226. );
  227. }
  228. $response = new StandaloneTemplateResponse(
  229. $this->appName,
  230. '403',
  231. [
  232. 'message' => $this->l10n->t('Could not complete login'),
  233. ],
  234. 'guest'
  235. );
  236. $response->setStatus(Http::STATUS_FORBIDDEN);
  237. return $response;
  238. }
  239. /**
  240. * @NoCSRFRequired
  241. * @PublicPage
  242. */
  243. public function init(): JSONResponse {
  244. // Get client user agent
  245. $userAgent = $this->request->getHeader('USER_AGENT');
  246. $tokens = $this->loginFlowV2Service->createTokens($userAgent);
  247. $data = [
  248. 'poll' => [
  249. 'token' => $tokens->getPollToken(),
  250. 'endpoint' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.poll')
  251. ],
  252. 'login' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.landing', ['token' => $tokens->getLoginToken()]),
  253. ];
  254. return new JSONResponse($data);
  255. }
  256. private function isValidStateToken(string $stateToken): bool {
  257. $currentToken = $this->session->get(self::STATE_NAME);
  258. if (!is_string($stateToken) || !is_string($currentToken)) {
  259. return false;
  260. }
  261. return hash_equals($currentToken, $stateToken);
  262. }
  263. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  264. $response = new StandaloneTemplateResponse(
  265. $this->appName,
  266. '403',
  267. [
  268. 'message' => $this->l10n->t('State token does not match'),
  269. ],
  270. 'guest'
  271. );
  272. $response->setStatus(Http::STATUS_FORBIDDEN);
  273. return $response;
  274. }
  275. /**
  276. * @return LoginFlowV2
  277. * @throws LoginFlowV2NotFoundException
  278. */
  279. private function getFlowByLoginToken(): LoginFlowV2 {
  280. $currentToken = $this->session->get(self::TOKEN_NAME);
  281. if (!is_string($currentToken)) {
  282. throw new LoginFlowV2NotFoundException('Login token not set in session');
  283. }
  284. return $this->loginFlowV2Service->getByLoginToken($currentToken);
  285. }
  286. private function loginTokenForbiddenResponse(): StandaloneTemplateResponse {
  287. $response = new StandaloneTemplateResponse(
  288. $this->appName,
  289. '403',
  290. [
  291. 'message' => $this->l10n->t('Your login token is invalid or has expired'),
  292. ],
  293. 'guest'
  294. );
  295. $response->setStatus(Http::STATUS_FORBIDDEN);
  296. return $response;
  297. }
  298. private function getServerPath(): string {
  299. $serverPostfix = '';
  300. if (strpos($this->request->getRequestUri(), '/index.php') !== false) {
  301. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  302. } elseif (strpos($this->request->getRequestUri(), '/login/v2') !== false) {
  303. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/v2'));
  304. }
  305. $protocol = $this->request->getServerProtocol();
  306. return $protocol . '://' . $this->request->getServerHost() . $serverPostfix;
  307. }
  308. }