Skip to content

Commit

Permalink
refactor: token generation for iframe
Browse files Browse the repository at this point in the history
Signed-off-by: codewithvk <[email protected]>
  • Loading branch information
codewithvk committed Jan 20, 2025
1 parent a4621fe commit 32d0845
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 49 deletions.
1 change: 1 addition & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
'name' => '.+',
],
],
['name' => 'settings#generateIframeToken', 'url' => 'settings/generateToken/{type}', 'verb' => 'GET'],

// Direct Editing: Webview
['name' => 'directView#show', 'url' => '/direct/{token}', 'verb' => 'GET'],
Expand Down
18 changes: 0 additions & 18 deletions lib/Controller/DocumentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -385,24 +385,6 @@ public function editOnlineTarget(int $fileId, ?string $target = null): RedirectR
#[PublicPage]
public function token(int $fileId, ?string $shareToken = null, ?string $path = null, ?string $guestName = null): DataResponse {
try {
if ($fileId === -1 && $path !== null && str_starts_with($path, 'adminIntegratorSettings/')) {
$parts = explode('/', $path);
$adminUserId = $parts[1] ?? $this->userId; // fallback if needed

$docKey = $fileId . '_' . $this->config->getSystemValue('instanceid');

$wopi = $this->tokenManager->generateWopiToken($fileId, null, $adminUserId);

$coolBaseUrl = $this->appConfig->getCollaboraUrlPublic();
$adminSettingsWopiSrc = $coolBaseUrl . '/browser/adminIntegratorSettings.html?';

return new DataResponse([
'urlSrc' => $adminSettingsWopiSrc,
'token' => $wopi->getToken(),
'token_ttl' => $wopi->getExpiry(),
]);
}

// Normal file handling (unchanged)
$share = $shareToken ? $this->shareManager->getShareByToken($shareToken) : null;
$file = $shareToken ? $this->getFileForShare($share, $fileId, $path) : $this->getFileForUser($fileId, $path);
Expand Down
31 changes: 31 additions & 0 deletions lib/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
use OCA\Richdocuments\Service\DiscoveryService;
use OCA\Richdocuments\Service\FontService;
use OCA\Richdocuments\UploadException;
use OCA\Richdocuments\Db\WopiMapper;
use OCP\App\IAppManager;
use OCP\IGroupManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
Expand Down Expand Up @@ -58,6 +60,9 @@ public function __construct(
private FontService $fontService,
private SettingsService $settingsService,
private LoggerInterface $logger,
private IGroupManager $groupManager,
private IURLGenerator $urlGenerator,
private WopiMapper $wopiMapper,
private ?string $userId,
) {
parent::__construct($appName, $request);
Expand Down Expand Up @@ -411,6 +416,32 @@ public function getFontFileOverview(string $name): DataDisplayResponse {
}
}

/**
* @NoAdminRequired
* @PublicPage
* @NoCSRFRequired
*
* @param string $type - Type is 'admin' or 'user'
* @return DataDisplayResponse
*/
public function generateIframeToken(string $type) : DataResponse {
$userId = $this->userId;
if ($type === 'admin' && !$this->groupManager->isAdmin($userId)) {
return new DataResponse([
'message' => 'Permission denied'
], Http::STATUS_FORBIDDEN);
}
$serverHost = $this->urlGenerator->getAbsoluteURL('/');
$version = $this->capabilitiesService->getProductVersion();

$wopi = $this->wopiMapper->generateUserSettingsToken(-1, $userId, $version, $serverHost);

return new DataResponse([
'token' => $wopi->getToken(),
'token_ttl' => $wopi->getExpiry(),
]);
}

/**
* @param string $name
* @return DataResponse
Expand Down
6 changes: 4 additions & 2 deletions lib/Controller/WopiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public function checkFileInfo(string $fileId, string $access_token): JSONRespons
try {
$wopi = $this->wopiMapper->getWopiForToken($access_token);

// TODO: condition for $wopi not found?
// TODO: condition for $wopi not found? -auth???
$userSettingsUri = $this->generateUserSettingsUri($wopi);

Expand Down Expand Up @@ -413,7 +413,7 @@ public function getSettings(string $type, string $access_token): JSONResponse {
return new JSONResponse(['error' => 'Invalid token type'], Http::STATUS_FORBIDDEN);
}

$user = $this->userManager->get($wopi->getEditorUid());
$user = $this->userManager->get($wopi->getOwnerUid());
if (!$user || !$this->groupManager->isAdmin($user->getUID())) {
return new JSONResponse(['error' => 'Access denied'], Http::STATUS_FORBIDDEN);
}
Expand Down Expand Up @@ -441,6 +441,8 @@ public function uploadSettingsFile(string $fileId, string $access_token): JSONRe
return new JSONResponse(['error' => 'Invalid token type'], Http::STATUS_FORBIDDEN);
}

// auth - for admin??

$content = fopen('php://input', 'rb');
if (!$content) {
throw new \Exception("Failed to read input stream.");
Expand Down
17 changes: 5 additions & 12 deletions lib/Db/WopiMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,26 +66,19 @@ public function generateFileToken($fileId, $owner, $editor, $version, $updatable
return $wopi;
}

public function generateUserSettingsToken($fileId, $owner, $editor, $version, $updatable, $serverHost, ?string $guestDisplayname = null, $hideDownload = false, $direct = false, $templateId = 0, $share = null) {
public function generateUserSettingsToken($fileId, $userId, $version, $serverHost) {
$token = $this->random->generate(32, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);

$wopi = Wopi::fromParams([
'fileid' => $fileId,
'ownerUid' => $owner,
'editorUid' => $editor,
'ownerUid' => $userId,
'version' => $version,
'canwrite' => $updatable,
'canwrite' => true,
'serverHost' => $serverHost,
'token' => $token,
'expiry' => $this->calculateNewTokenExpiry(),
'guestDisplayname' => $guestDisplayname,
'hideDownload' => $hideDownload,
'direct' => $direct,
'templateId' => $templateId,
'remoteServer' => '',
'remoteServerToken' => '',
'share' => $share,
'tokenType' => Wopi::TOKEN_TYPE_SETTING_AUTH
'templateId' => "0",
'tokenType' => Wopi::TOKEN_TYPE_SETTING_AUTH,
]);

/** @var Wopi $wopi */
Expand Down
7 changes: 0 additions & 7 deletions lib/TokenManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,6 @@ public function generateWopiToken(string $fileId, ?string $shareToken = null, ?s
$hideDownload = false;
$rootFolder = $this->rootFolder;

if ($fileId == "-1")
{
$editoruid = $this->userId;
$serverHost = $this->urlGenerator->getAbsoluteURL('/');
return $this->wopiMapper->generateUserSettingsToken($fileId, $owneruid, $editoruid, 0, true, $serverHost, "", $hideDownload, $direct, 0, $shareToken);
}

[$fileId, , $version] = Helper::parseFileId($fileId);

// if the user is not logged-in do use the sharers storage
Expand Down
11 changes: 1 addition & 10 deletions src/components/AdminSettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -641,16 +641,7 @@ export default {
},
methods: {
async generateAccessToken() {
const fileId = -1
const path = `adminIntegratorSettings/${this.userId}`
const guestName = this.userId

const { data } = await axios.post(generateUrl('/apps/richdocuments/token'), {
fileId,
path,
guestName,
})

const { data } = await axios.get(generateUrl('/apps/richdocuments/settings/generateToken/admin'))
if (data.token) {
this.accessToken = data.token
this.accessTokenTTL = data.token_ttl
Expand Down

0 comments on commit 32d0845

Please sign in to comment.