Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update live edit feature to protect against overwriting modified content #1466

Merged
merged 4 commits into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/realtime-compiler/resources/live-edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
</header>
<input type="hidden" name="_token" value="{{ $csrfToken }}">
<input type="hidden" name="page" value="{{ $page->getSourcePath() }}">
<input type="hidden" name="currentContentHash" value="{{ hash('sha256', $page->markdown()->body()) }}">
<label for="live-editor" class="sr-only">Edit page contents</label>
<textarea name="markdown" id="live-editor" cols="30" rows="20" class="rounded-lg bg-gray-200 dark:bg-gray-800">{{ $markdown }}</textarea>
</form>
Expand Down
28 changes: 28 additions & 0 deletions packages/realtime-compiler/resources/live-edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ function initLiveEdit() {
showEditor();

document.getElementById('liveEditCancel').addEventListener('click', hideEditor);

document.getElementById('liveEditForm').addEventListener('submit', handleFormSubmit);
}

if (hasEditorBeenSetUp()) {
Expand All @@ -60,6 +62,32 @@ function initLiveEdit() {
}
}

function handleFormSubmit(event) {
event.preventDefault();

fetch('/_hyde/live-edit', {
method: "POST",
body: new FormData(event.target),
headers: new Headers({
"Accept": "application/json",
}),
}).then(async response => {
if (response.ok) {
window.location.reload();
} else {
if (response.status === 409) {
if (confirm('This page has been modified in another window. Do you want to overwrite the changes?')) {
document.getElementById('liveEditForm').insertAdjacentHTML('beforeend', '<input type="hidden" name="force" value="true">');
document.getElementById('liveEditForm').submit();
}
return;
}

alert(`Error saving content: ${response.status} ${response.statusText}\n${JSON.parse(await response.text()).error ?? 'Unknown error'}`);
}
});
}

function handleShortcut(event) {
let isEditorHidden = getLiveEditor() === null || getLiveEditor().style.display === 'none';
let isEditorVisible = getLiveEditor() !== null && getLiveEditor().style.display !== 'none';
Expand Down
31 changes: 27 additions & 4 deletions packages/realtime-compiler/src/Http/LiveEditController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@

use Hyde\Hyde;
use Hyde\Support\Models\Route;
use Desilva\Microserve\Response;
use Hyde\Support\Models\Redirect;
use Hyde\Markdown\Models\Markdown;
use Desilva\Microserve\JsonResponse;
use Illuminate\Support\Facades\Blade;
use Hyde\Pages\Concerns\BaseMarkdownPage;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
* @internal This class is not intended to be edited outside the Hyde Realtime Compiler.
Expand All @@ -19,29 +22,49 @@ class LiveEditController extends BaseController
protected bool $withConsoleOutput = true;
protected bool $withSession = true;

public function handle(): HtmlResponse
public function handle(): Response
{
$this->authorizePostRequest();
try {
$this->authorizePostRequest();

return $this->handleRequest();
return $this->handleRequest();
} catch (HttpException $exception) {
if ($this->expectsJson()) {
return $this->sendJsonErrorResponse($exception->getStatusCode(), $exception->getMessage());
}

throw $exception;
}
}

protected function handleRequest(): HtmlResponse
protected function handleRequest(): Response
{
$pagePath = $this->request->data['page'] ?? $this->abort(400, 'Must provide page path');
$content = $this->request->data['markdown'] ?? $this->abort(400, 'Must provide content');
$currentContentHash = $this->request->data['currentContentHash'] ?? $this->abort(400, 'Must provide content hash');
$force = $this->request->data['force'] ?? false;

$page = Hyde::pages()->getPage($pagePath);

if (! $page instanceof BaseMarkdownPage) {
$this->abort(400, 'Page is not a markdown page');
}

if (! $force && hash('sha256', $page->markdown()->body()) !== $currentContentHash) {
$this->abort(409, 'Content has changed in another window');
}

$page->markdown = new Markdown($content);
$page->save();

$this->writeToConsole("Updated file '$pagePath'", 'hyde@live-edit');

if ($this->expectsJson()) {
return new JsonResponse(200, 'OK', [
'message' => 'Page saved successfully.',
]);
}

return $this->redirectToPage($page->getRoute());
}

Expand Down
Loading