Skip to content

Commit

Permalink
[5.x] Allow accessing drafts via the REST API with Live Preview (#10229)
Browse files Browse the repository at this point in the history
Co-authored-by: duncanmcclean <[email protected]>
Co-authored-by: Jason Varga <[email protected]>
  • Loading branch information
3 people authored Jun 25, 2024
1 parent d795c89 commit d55ad71
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Http/Controllers/API/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class ApiController extends Controller
*/
protected function abortIfUnpublished($item)
{
if (request()->isLivePreview()) {
return;
}

throw_if($item->published() === false, new NotFoundHttpException);
}

Expand Down
47 changes: 47 additions & 0 deletions tests/API/APITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPUnit\Framework\Attributes\Test;
use Statamic\Facades;
use Statamic\Facades\Blueprint;
use Statamic\Facades\Token;
use Statamic\Facades\User;
use Tests\PreventSavingStacheItemsToDisk;
use Tests\TestCase;
Expand Down Expand Up @@ -425,6 +426,44 @@ public function it_replaces_entries_using_live_preview_token()
]);
}

#[Test]
public function live_preview_token_bypasses_entry_status_check()
{
Facades\Config::set('statamic.api.resources.collections', true);
Facades\Collection::make('pages')->save();
$entry = tap(Facades\Entry::make()->collection('pages')->id('dance')->published(false)->set('title', 'Dance')->slug('dance'))->save();

$this->get('/api/collections/pages/entries/dance')->assertJson([
'message' => 'Not found.',
]);

LivePreview::tokenize('test-token', $entry);

$this->get('/api/collections/pages/entries/dance?token=test-token')->assertJson([
'data' => [
'title' => 'Dance',
],
]);
}

#[Test]
public function non_live_preview_tokens_doesnt_bypass_entry_status_check()
{
Facades\Config::set('statamic.api.resources.collections', true);
Facades\Collection::make('pages')->save();
$entry = tap(Facades\Entry::make()->collection('pages')->id('dance')->published(false)->set('title', 'Dance')->slug('dance'))->save();

$this->get('/api/collections/pages/entries/dance')->assertJson([
'message' => 'Not found.',
]);

Token::make('test-token', FakeTokenHandler::class)->save();

$this->get('/api/collections/pages/entries/dance?token=test-token')->assertJson([
'message' => 'Not found.',
]);
}

#[Test]
public function it_replaces_terms_using_live_preview_token()
{
Expand Down Expand Up @@ -544,3 +583,11 @@ private function assertEndpointNotFound($endpoint)
->assertJson(['message' => 'Not found.']);
}
}

class FakeTokenHandler
{
public function handle(\Statamic\Contracts\Tokens\Token $token, \Illuminate\Http\Request $request, \Closure $next)
{
return $next($token);
}
}

0 comments on commit d55ad71

Please sign in to comment.