2

In my application, I want anonymous users to be able to view an unpublished node but only if they append a special code to the URL. For example:

www.mysite.com/node/123?code=Hx23ufG38

I figure I can do something in a preprocess function to check if the code is appended to the URL and, if so, allow the user to view the unpublished node. (This clearly is not for a use case where the content is sensitive, because anyone visiting the page at the URL with the code appended will be able to see the page.)

How can I programmatically grant the current (anonymous) user permission to view unpublished content, provided the condition is met in the URL?

This is for a Drupal 9 website.

11
  • 2
    Broad strokes you'd probably use hook_entity_access (or hook_ENTITY_TYPE_access), and add a query string cache context to the AccessResult you return from there
    – Clive
    Commented Apr 24, 2023 at 16:20
  • 1
    Little bit similar to this maybe drupal.stackexchange.com/a/313783/15055
    – leymannx
    Commented Apr 24, 2023 at 18:35
  • 1
    Yes, but then you need to add ->addCacheContexts(['url.query_args:code']). Otherwise the first anonymous user with query string will grant access for all other anonymous users following.
    – 4uk4
    Commented Apr 25, 2023 at 9:12
  • 1
    @leymannx, cachePerUser() is a shortcut for the user context.
    – 4uk4
    Commented Apr 25, 2023 at 11:21
  • 1
    This cache setting is only for the headers sent out to the browser. Drupal has two page cache modules. The anonymous page cache varies by the entire URL including query string, the dynamic page cache varies by route and contexts. As long as the anonymous page cache has cached the correct results all things are fine, but starting with a cleared cache certain combinations of node request should reproduce wrong answers.
    – 4uk4
    Commented Apr 25, 2023 at 15:09

1 Answer 1

2

You can use https://www.drupal.org/project/access_unpublished or look at its code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.