How to skip node access issues during a cron process

Few days ago in Ymbra we had a challenge about how to load Drupal 7 entities during a cron job. The main issue here is that cron doesn't run with enough credentials and we need higher permissions to perform some operations.

Those entities had user access restrictions in place and when cron runs as anonymous user (even if you trigger it logged in as the user with id=1) those restrictions were respected and we weren't able to load our entity content to be later sent in an email.

So what can we do to run cron as Drupal admin?

In a hook_cron() we can do:

 * Implements hook_cron().
function mymodule_cron() { 
  global $user;
  $user = user_load(1);

And also be sure to have this hook running before the hook(in this case another hook_cron) that needs higher permissions by modifying the weight field of mymodule in the system table.

We must say that if you are running Drupal cron on browser hits (what was previously known as poorman's cron) is not a very good practice and might cause problems with this workaround. You should be running cron with Drush on a system cron on your server.

Additionally you can restore the global $user variable to anonymous again after you run the code in need for it to minimize the impact.

You can read more about that in this related issue.