Search code examples
phpwordpressgoogle-calendar-apiwordpress-rest-api

How to store a file in a Wordpress Plugin without exposing it online?


I'm developing a Wordpress plugin that talks to the Google Calendar API through a Google Service Account.

Such a service account comes with a JSON file, which holds its OAuth2 credentials (client_id, public key & private key for example).

For the plugin to work for others, I need them to upload their own JSON credentials file within the plugin. This way the plugin will be able to talk to the Google API and access/modify their personal calendars.

Here's the thing:

Wordpress plugin files have no protection, they are publicly accessible. How do I store a JSON file within a plugin, without exposing the credentials it contains?

"Hey man, you can save JSON in the database..."

I know, but Google's API client requires a string to the credential file, instead of straight JSON:

$client = new Google\Client();
$client->setAuthConfig('./credentials.json');

Solution

  • This doesn't seem to be super well documented by Google, but it looks like setAuthConfig can also take an array instead of a string. So you should be able to allow the user to store the JSON in the database, then json_decode it yourself and pass that to setAuthConfig.

    // retrieve $jsonString from database somehow
    $configArray = json_decode($jsonString, true);
    $client->setAuthConfig($configArray);
    

    Note that json_decode needs that second parameter set to true, so that it decodes as an associative array, which is what the Google library wants.

    (and if you're curious, you can see the setAuthConfig code here: https://github.com/googleapis/google-api-php-client/blob/81696e6206322e38c643cfcc96c4494ccfef8a32/src/Client.php#L956 Notice how it checks that $config is a string, and if it isn't, it just uses it directly. Also, the comment above the function mentions that $config can be an array.)