Authtokens.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Settings\Settings\Personal\Security;
  8. use OC\Authentication\Token\INamedToken;
  9. use OC\Authentication\Token\IProvider as IAuthTokenProvider;
  10. use OC\Authentication\Token\IToken;
  11. use OCP\AppFramework\Http\TemplateResponse;
  12. use OCP\AppFramework\Services\IInitialState;
  13. use OCP\Authentication\Exceptions\InvalidTokenException;
  14. use OCP\ISession;
  15. use OCP\IUserSession;
  16. use OCP\Session\Exceptions\SessionNotAvailableException;
  17. use OCP\Settings\ISettings;
  18. use function array_map;
  19. class Authtokens implements ISettings {
  20. public function __construct(
  21. private IAuthTokenProvider $tokenProvider,
  22. private ISession $session,
  23. private IUserSession $userSession,
  24. private IInitialState $initialState,
  25. private ?string $userId,
  26. ) {
  27. }
  28. public function getForm(): TemplateResponse {
  29. $this->initialState->provideInitialState(
  30. 'app_tokens',
  31. $this->getAppTokens()
  32. );
  33. $this->initialState->provideInitialState(
  34. 'can_create_app_token',
  35. $this->userSession->getImpersonatingUserID() === null
  36. );
  37. return new TemplateResponse('settings', 'settings/personal/security/authtokens');
  38. }
  39. public function getSection(): string {
  40. return 'security';
  41. }
  42. public function getPriority(): int {
  43. return 100;
  44. }
  45. private function getAppTokens(): array {
  46. $tokens = $this->tokenProvider->getTokenByUser($this->userId);
  47. try {
  48. $sessionId = $this->session->getId();
  49. } catch (SessionNotAvailableException $ex) {
  50. return [];
  51. }
  52. try {
  53. $sessionToken = $this->tokenProvider->getToken($sessionId);
  54. } catch (InvalidTokenException $ex) {
  55. return [];
  56. }
  57. return array_map(function (IToken $token) use ($sessionToken) {
  58. $data = $token->jsonSerialize();
  59. $data['canDelete'] = true;
  60. $data['canRename'] = $token instanceof INamedToken && $data['type'] !== IToken::WIPE_TOKEN;
  61. if ($sessionToken->getId() === $token->getId()) {
  62. $data['canDelete'] = false;
  63. $data['canRename'] = false;
  64. $data['current'] = true;
  65. }
  66. return $data;
  67. }, $tokens);
  68. }
  69. }