Skip to content

Commit

Permalink
Google Maps: Require passing in a constant for apiKey
Browse files Browse the repository at this point in the history
This is more appropriate than hardcoding keys for specific sites, since this block will be reused on multiple sites.
  • Loading branch information
iandunn committed Oct 18, 2023
1 parent eb5eba4 commit a6027d6
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
3 changes: 3 additions & 0 deletions mu-plugins/blocks/google-map/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Place something like the following in a block or pattern. If you're pulling even

$map_options = array(
'id' => 'all-upcoming-events',
'apiKey' => 'MY_API_KEY_CONSTANT',
'markers' => get_all_upcoming_events(),
);

Expand All @@ -24,6 +25,8 @@ $map_options = array(
<!-- wp:wporg/google-map <?php echo wp_json_encode( $map_options ); ?> /-->
```

`apiKey` should be the _name_ of a constant, not the value. It's not private because it'll be exposed in the HTTP request to Google Maps, but it should still be stored in a constant in a config file instead of `post_content`. That allows for centralization, documentation, and tracking changes over time. It should be restricted in Google Cloud Console to only the sites where it will be used, to prevent abuse.

`markers` should be an array of objects with the fields in the example below. The `timestamp` field should be a true Unix timestamp, meaning it assumes UTC. The `wporg_events` database table is one potential source for the events, but you can pass anything.

```php
Expand Down
9 changes: 3 additions & 6 deletions mu-plugins/blocks/google-map/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,9 @@ function init() {
function render( $attributes, $content, $block ) {
$attributes['id'] = 'wp-block-wporg-google-map-' . $attributes['id'];

if ( empty( $attributes['apiKey'] ) ) {
$default_key = 'production' === wp_get_environment_type() ? 'WORDCAMP_PROD_GOOGLE_MAPS_API_KEY' : 'WORDCAMP_DEV_GOOGLE_MAPS_API_KEY';

if ( defined( $default_key ) ) {
$attributes['apiKey'] = constant( $default_key );
}
if ( ! empty( $attributes['apiKey'] ) ) {
// See README for why this has to be a constant.
$attributes['apiKey'] = constant( $attributes['apiKey'] );
}

$attributes['searchIcon'] = plugins_url( 'images/search.svg', __FILE__ );
Expand Down

0 comments on commit a6027d6

Please sign in to comment.