Temporary add role by token for a particular page to anonymous user I have a specific task: I need to give a temporary access to particular unpublished nodes for anonymous users using access token. Anonymous is a key feature, so I can't create a limited user account by some reasons.

I found a rough temporary solution by adding a field "access token" to my node type, creating a role with access to unpublished nodes (using view unpublished module) and by changing user_access function. I added the following strings:

 if ($_GET['access_token'] &amp;&amp; arg(0) == 'node' &amp;&amp; is_numeric(arg(1)) &amp;&amp; !arg(2)) {

        $node = node_load(arg(1));

        if (isset($node-&gt;field_access_token['und'][0]['value']) &amp;&amp; $node-&gt;field_access_token['und'][0]['value'] == $_GET['access_token']) {

            $account-&gt;roles[6] = 'unpublishedaccess';
        }
    }


How can I do similar but without changing Drupal core files?
Assuming that this question is about D7, you could use the Rules module for this, combined with enforcing the usage of an URL argument which must include the correct token.

Here is an example of a relative path you could use/enforce: /node/123?SomeUrlArg=456, which would be for the node with node id = 123 and which uses an URL argument named SomeUrlArg and with the value of that URL argument 456 (obviously, each node can have its own argument value).

To implement this, you would create a custom rule that looks like so:


Rules Event: Drupal is initializing (you must use this event, otherwise you're too late).
Rules Condition: NOT (Check if the URL argument (=SomeUrlArg) is present and that its value matches the value of your field_access_token).

Note the NOT in this Rules Condition: you only want to perform the Rules Action below if either the argument is absent OR if its value doesn't match with the field_access_token value.

To be able to specify these Rules Conditions, you can use the Rules URL argument module. For more details about this module, refer to my answer to "How to use Rules to redirect a user based on URL argument?".
Rules Action: perform a redirect to whatever relative path that fits your needs (but not to /node/123 of course).