If you're getting an error code instead of a chart, click here
25 | to find out what the code means.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/php/index.php:
--------------------------------------------------------------------------------
1 | =10 if you want the chart to autorefresh
12 |
13 | $charts = new Charts($baseUrl, $embeddingKey, $filter, $autoRefreshSeconds);
14 |
15 | ?>
16 |
17 |
18 |
19 |
20 |
21 |
MongoDB Charts Embedding Example (PHP)
22 |
23 |
24 |
If you're getting an error code instead of a chart, click here
25 | to find out what the code means.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/embedding-sdk/unauthenticated/assets/toggle.css:
--------------------------------------------------------------------------------
1 | /* The switch - the box around the slider */
2 | .switch {
3 | position: relative;
4 | display: inline-block;
5 | width: 60px;
6 | height: 34px;
7 | }
8 |
9 | /* Hide default HTML checkbox */
10 | .switch input {
11 | opacity: 0;
12 | width: 0;
13 | height: 0;
14 | }
15 |
16 | /* The slider */
17 | .slider {
18 | position: absolute;
19 | cursor: pointer;
20 | top: 0;
21 | left: 0;
22 | right: 0;
23 | bottom: 0;
24 | background-color: #c5e4f2;
25 | -webkit-transition: 0.4s;
26 | transition: 0.4s;
27 | box-shadow: #bdc3c7 0px 0px 10px 1px;
28 | }
29 |
30 | .slider:before {
31 | position: absolute;
32 | content: "";
33 | height: 26px;
34 | width: 26px;
35 | left: 4px;
36 | bottom: 4px;
37 | background-color: white;
38 | -webkit-transition: 0.4s;
39 | transition: 0.4s;
40 | }
41 |
42 | input:checked + .slider {
43 | background-color: #1a567e;
44 | box-shadow: #2c3e50 0px 0px 10px 1px;
45 | }
46 |
47 | input:focus + .slider {
48 | box-shadow: 0 0 1px #1a567e;
49 | box-shadow: #2c3e50 0px 0px 10px 1px;
50 | }
51 |
52 | input:checked + .slider:before {
53 | -webkit-transform: translateX(26px);
54 | -ms-transform: translateX(26px);
55 | transform: translateX(26px);
56 | }
57 |
58 | /* Rounded sliders */
59 | .slider.round {
60 | border-radius: 34px;
61 | }
62 |
63 | .slider.round:before {
64 | border-radius: 50%;
65 | }
66 |
--------------------------------------------------------------------------------
/c-sharp/ChartsEmbedding.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.421
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChartsEmbedding", "ChartsEmbedding\ChartsEmbedding.csproj", "{E3E2C32C-411E-4034-A8D7-F3F1CD1B39E2}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DE1B0CD2-8CD9-4B2C-98A0-14B80B346000}"
9 | ProjectSection(SolutionItems) = preProject
10 | README.md = README.md
11 | EndProjectSection
12 | EndProject
13 | Global
14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
15 | Debug|Any CPU = Debug|Any CPU
16 | Release|Any CPU = Release|Any CPU
17 | EndGlobalSection
18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
19 | {E3E2C32C-411E-4034-A8D7-F3F1CD1B39E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
20 | {E3E2C32C-411E-4034-A8D7-F3F1CD1B39E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
21 | {E3E2C32C-411E-4034-A8D7-F3F1CD1B39E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
22 | {E3E2C32C-411E-4034-A8D7-F3F1CD1B39E2}.Release|Any CPU.Build.0 = Release|Any CPU
23 | EndGlobalSection
24 | GlobalSection(SolutionProperties) = preSolution
25 | HideSolutionNode = FALSE
26 | EndGlobalSection
27 | GlobalSection(ExtensibilityGlobals) = postSolution
28 | SolutionGuid = {D84C32C1-15E9-4C5F-A604-A615B12F6C08}
29 | EndGlobalSection
30 | EndGlobal
31 |
--------------------------------------------------------------------------------
/embedding-sdk/unauthenticated/assets/styles.css:
--------------------------------------------------------------------------------
1 | html,
2 | body {
3 | height: 100%;
4 | font-family: "Heebo";
5 | transition: background-color 0.5s ease;
6 | }
7 |
8 | .chart-title {
9 | text-align: center;
10 | color: #89989b;
11 | }
12 |
13 | .body-content {
14 | display: flex;
15 | }
16 |
17 | th {
18 | font-weight: bold;
19 | color: #89989b;
20 | text-align: right;
21 | }
22 |
23 | .chartInfo {
24 | font-size: 20px;
25 | width: 520px;
26 | }
27 |
28 | td {
29 | padding-left: 20px;
30 | }
31 |
32 | .chartsContainer {
33 | display: flex;
34 | }
35 |
36 | main {
37 | box-sizing: border-box;
38 | padding: 1rem;
39 | height: 100%;
40 | display: flex;
41 | flex-direction: column;
42 | }
43 |
44 | #nav {
45 | flex-shrink: 0;
46 | padding: 1rem;
47 | display: flex;
48 | justify-content: space-between;
49 | align-items: center;
50 | font-weight: bold;
51 | color: #89989b;
52 | }
53 |
54 | #nav button,
55 | #nav select {
56 | font-size: 1.1rem;
57 | border-radius: 3px;
58 | box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
59 | }
60 |
61 | #chart {
62 | border-top: none;
63 | flex-grow: 1;
64 | height: 100%;
65 | width: 80%;
66 | }
67 |
68 | .theme-label {
69 | line-height: 35px;
70 | padding-left: 10px;
71 | }
72 |
73 | span {
74 | white-space: pre;
75 | }
76 |
77 | .dark-mode {
78 | background-color: #061621;
79 | color: #ffffff;
80 | }
81 |
82 | body span.theme-label::before {
83 | content: "☀️";
84 | }
85 |
86 | body.dark-mode span.theme-label::before {
87 | content: "🌙";
88 | }
89 |
--------------------------------------------------------------------------------
/c-sharp/ChartsEmbedding/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Builder;
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.AspNetCore.Mvc;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Logging;
11 | using Microsoft.Extensions.Options;
12 |
13 | namespace ChartsEmbedding
14 | {
15 | public class Startup
16 | {
17 | public Startup(IConfiguration configuration)
18 | {
19 | Configuration = configuration;
20 | }
21 |
22 | public IConfiguration Configuration { get; }
23 |
24 | // This method gets called by the runtime. Use this method to add services to the container.
25 | public void ConfigureServices(IServiceCollection services)
26 | {
27 | services.AddControllers();
28 | }
29 |
30 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
31 | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
32 | {
33 | if (env.IsDevelopment())
34 | {
35 | app.UseDeveloperExceptionPage();
36 | }
37 |
38 | app.UseRouting();
39 | app.UseDefaultFiles();
40 | app.UseStaticFiles();
41 |
42 | app.UseEndpoints(endpoints =>
43 | {
44 | endpoints.MapControllers();
45 | });
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/php/src/MongoDB/Charts.php:
--------------------------------------------------------------------------------
1 | chartsBaseUrl = $baseUrl;
18 | $this->embeddingSigningKey = $signingKey;
19 | $this->filter = $filter;
20 | $this->autoRefreshSeconds = $autoRefreshSeconds;
21 | }
22 |
23 | private function _genSignature(){
24 | $sig = hash_hmac('sha256', $this->payload, $this->embeddingSigningKey);
25 | $this->signature = $sig;
26 | }
27 |
28 | private function _buildPayload($chartId){
29 | $fmt = 'id=%s&tenant=%s×tamp=%d&expires-in=%d';
30 | $now = time();
31 | $this->payload = sprintf($fmt,$chartId,$this->tenantId,$now,$this->expiry);
32 | if ($this->filter !== NULL) {
33 | $this->payload .= '&filter=' . rawurlencode($this->filter);
34 | }
35 | if ($this->autoRefreshSeconds !== NULL) {
36 | $this->payload .= '&autorefresh=' . $this->autoRefreshSeconds;
37 | }
38 | }
39 |
40 | public function getChartUri($chartId){
41 | $this->_buildPayload($chartId);
42 | $this->_genSignature();
43 | $uri = '%s/embed/charts?%s&signature=%s';
44 | $this->chartUri = sprintf($uri,$this->chartsBaseUrl,$this->payload,$this->signature);
45 | return $this->chartUri;
46 | }
47 |
48 | public function setExpirey($expire){
49 | $this->expirey = $expire;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/stitch/stitch-functions/getEmbeddingUrl.js:
--------------------------------------------------------------------------------
1 | // Create a Stitch Application, choose Functions and create a new public Function called "getEmbeddingUrl".
2 | // Then paste in the following code, replacing the placeholders with appropriate values for you Charts instance.
3 |
4 | exports = function(chartId) {
5 |
6 | // Remember, in a real application, you should ensure your user is authenticated and authorized to view the chart before you return the signed URL.
7 |
8 | // Replace these constants with the correct values for your Charts instance
9 | const CHARTS_EMBEDDING_BASE_URL = '~REPLACE~CHARTS_EMBEDDING_BASE_URL'; // Replace with the base URL to your Charts instance, e.g. https://charts.mongodb.com/charts-foo-abcde (no trailing slash)
10 | const EMBEDDING_SIGNING_KEY = '~REPLACE~EMBEDDING_SIGNING_KEY'; // Replace with the Embedding Signing Key generated by your Charts admin
11 | const EXPIRY_TIME_SECONDS = 300; // Set to your preferred expiry period
12 | const FILTER_DOCUMENT = null; // Set to a MongoDB Query document if you want to filter the chart, e.g. { foo: { $gt: 10 }}
13 | const AUTOREFRESH_TIME_SECONDS = null; // Set to a number >=10 if you want the chart to autorefresh
14 |
15 | const timestamp = Math.floor(Date.now() / 1000);
16 | let payload = `id=${chartId}×tamp=${timestamp}&expires-in=${EXPIRY_TIME_SECONDS}`;
17 | if (FILTER_DOCUMENT) {
18 | payload += `&filter=${encodeURIComponent(JSON.stringify(FILTER_DOCUMENT))}`;
19 | }
20 | if (AUTOREFRESH_TIME_SECONDS) {
21 | payload += `&autorefresh=${AUTOREFRESH_TIME_SECONDS}`;
22 | }
23 | const signature = utils.crypto.hmac(payload, EMBEDDING_SIGNING_KEY, 'sha256', 'hex');
24 |
25 | return `${CHARTS_EMBEDDING_BASE_URL}/embed/charts?${payload}&signature=${signature}`;
26 | };
27 |
--------------------------------------------------------------------------------
/node/server.js:
--------------------------------------------------------------------------------
1 | // Remember, in a real application, you should ensure your user is authenticated and authorized to view the chart before you return the signed URL.
2 |
3 | // Replace these constants with the correct values for your Charts instance
4 | const CHARTS_EMBEDDING_BASE_URL = '~REPLACE~CHARTS_EMBEDDING_BASE_URL'; // Replace with the base URL to your Charts instance, e.g. https://charts.mongodb.com/charts-foo-abcde (no trailing slash)
5 | const EMBEDDING_SIGNING_KEY = '~REPLACE~EMBEDDING_SIGNING_KEY'; // Replace with the Embedding Signing Key generated by your Charts admin
6 | const EXPIRY_TIME_SECONDS = 300; // Set to your preferred expiry period
7 | const FILTER_DOCUMENT = null; // Set to a MongoDB Query document if you want to filter the chart, e.g. { foo: { $gt: 10 }}
8 | const AUTOREFRESH_TIME_SECONDS = null; // Set to a number >=10 if you want the chart to autorefresh
9 |
10 | const express = require('express');
11 | const crypto = require('crypto');
12 | const app = express();
13 | const port = 3000;
14 |
15 | app.get('/api/embeddedchart/:id', (req, res) => {
16 | const timestamp = Math.floor(Date.now() / 1000);
17 | let payload = `id=${req.params.id}×tamp=${timestamp}&expires-in=${EXPIRY_TIME_SECONDS}`;
18 | if (FILTER_DOCUMENT) {
19 | payload += `&filter=${encodeURIComponent(JSON.stringify(FILTER_DOCUMENT))}`;
20 | }
21 | if (AUTOREFRESH_TIME_SECONDS) {
22 | payload += `&autorefresh=${AUTOREFRESH_TIME_SECONDS}`;
23 | }
24 | const hmac = crypto.createHmac('sha256', EMBEDDING_SIGNING_KEY);
25 | hmac.update(payload);
26 | const signature = hmac.digest('hex');
27 | // generate url for iframe
28 | const url = `${CHARTS_EMBEDDING_BASE_URL}/embed/charts?${payload}&signature=${signature}`;
29 | res.send(url);
30 | });
31 |
32 | app.use(express.static('static'));
33 | app.listen(port, () => console.log(`Example app listening on port ${port}`));
34 |
--------------------------------------------------------------------------------
/java/charts-embedding/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.mongodb.charts
5 | charts-embedding
6 | jar
7 | 1.0
8 | charts-embedding
9 | http://maven.apache.org
10 |
11 |
12 | com.sparkjava
13 | spark-core
14 | 2.8.0
15 |
16 |
17 | org.apache.tomcat
18 | catalina
19 | 6.0.26
20 | provided
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-assembly-plugin
28 | 3.1.1
29 |
30 |
31 | jar-with-dependencies
32 |
33 | charts-embedding-1.0-with-deps
34 | false
35 |
36 |
37 | true
38 | com.mongodb.charts.App
39 |
40 |
41 |
42 |
43 |
44 | make-assembly
45 | package
46 |
47 | single
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | 1.8
56 | 1.8
57 | true
58 |
59 |
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Deprecated
2 |
3 | This repository contains samples for Verified Signature embedding which is now deprecated. For most new scenarios you should use the new Charts Embedding SDK. Examples on using the SDK can be found in this repo, [here](https://github.com/mongodb-js/charts-embed-sdk)
4 |
5 | ## MongoDB Charts Embedding Examples
6 |
7 | [MongoDB Charts](http://mongodb.com/charts) allows you to create visualizations of your MongoDB data using a simple web interface.
8 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render the charts in an external web
9 | application. When you embed a chart, you can choose whether you want it to be Unauthenticated (meaning anyone who has the embed code
10 | can view the chart), or to use "Verified Signature" authentication (which checks the integrity of a signature in the URL before the chart will render).
11 |
12 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site; no extra steps are required.
13 |
14 | The Verified Signature option requires a few more steps to implement but it is more secure — your app will generate the signature on the server side after
15 | first authenticating and authorizing the user, and the URL will stop working after a specified time period.
16 |
17 | This repo contains several versions of a simple sample app showing how to implement "Verified Signature" authentication. Each sample shows a different
18 | server-side language or platform. The languages currently included in this repository are:
19 |
20 | - [Node](node)
21 | - [C# (.NET core)](c-sharp)
22 | - [Java](java)
23 | - [Python 3](python)
24 | - [PHP](php)
25 | - [MongoDB Stitch](stitch)
26 |
27 | If you are using a server-side platform that we do not currently have a sample for, you will still be able to implement Verified Signature authentication
28 | as long as your language supports hashing of strings using the HMAC algorithm. You can use the included samples to understand the inputs to the hash
29 | function and how to constuct the required IFRAME URL.
30 |
31 | For further information on using MongoDB Charts and the Embedding capabilities, please see the [Charts documentation](https://docs.mongodb.com/charts).
32 |
--------------------------------------------------------------------------------
/c-sharp/ChartsEmbedding/Controllers/EmbeddedChartController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Security.Cryptography;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Microsoft.AspNetCore.Http;
8 | using Microsoft.AspNetCore.Mvc;
9 |
10 | namespace ChartsEmbedding.Controllers
11 | {
12 | [Route("api/[controller]")]
13 | [ApiController]
14 | public class EmbeddedChartController : ControllerBase
15 | {
16 | // Replace these constants with the correct values for your Charts instance
17 | private const string CHARTS_EMBEDDING_BASE_URL = "~REPLACE~CHARTS_EMBEDDING_BASE_URL"; // Replace with the base URL to your Charts instance, e.g. https://charts.mongodb.com/charts-foo-abcde (no trailing slash)
18 | private const string EMBEDDING_SIGNING_KEY = "~REPLACE~EMBEDDING_SIGNING_KEY"; // Replace with the Embedding Signing Key generated by your Charts admin
19 | private TimeSpan expiryTime = TimeSpan.FromMinutes(5); // Set to your preferred expiry period
20 | private const string FILTER_DOCUMENT = null; // Set to a MongoDB Query if you want to filter the chart, e.g. "{ foo: { $gt: 10 }}"
21 | private TimeSpan? autoRefreshTime = null; // Set to a number of seconds >=10 if you want the chart to autorefresh, eg. TimeSpan.FromSeconds(30);
22 |
23 |
24 | // GET api/embeddedchart/
25 | [HttpGet("{id}")]
26 | public ActionResult Get(string id)
27 | {
28 | // Remember, in a real application, you should ensure your user is authenticated and authorized to view the chart before you return the signed URL.
29 |
30 | int timestamp = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
31 | string payload = $"id={id}×tamp={timestamp}&expires-in={expiryTime.TotalSeconds}";
32 | if (FILTER_DOCUMENT != null) {
33 | payload += $"&filter={Uri.EscapeDataString(FILTER_DOCUMENT)}";
34 | }
35 | if (autoRefreshTime.HasValue) {
36 | payload += $"&autorefresh={autoRefreshTime.Value.TotalSeconds}";
37 | }
38 | var signature = GetHashAsHex(EMBEDDING_SIGNING_KEY, payload);
39 | return $"{CHARTS_EMBEDDING_BASE_URL}/embed/charts?{payload}&signature={signature}";
40 | }
41 |
42 | private static string GetHashAsHex(string key, string input)
43 | {
44 | var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key));
45 | var hashBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(input));
46 | return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/embedding-sdk/unauthenticated/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Charts Embedded SDK Demo
5 |
6 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
26 |
36 |
49 |
57 |
58 |
59 |
60 |
61 |
CHART DATA
62 |
63 |
64 |
Current Refresh Interval
65 |
None
66 |
67 |
68 |
Current Theme
69 |
light
70 |
71 |
72 |
Current Filter
73 |
None
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/python/server.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from http.server import BaseHTTPRequestHandler, HTTPServer
4 | from string import Template
5 | from math import floor
6 | import os
7 | import hmac
8 | import hashlib
9 | import time
10 | import urllib.parse
11 |
12 | # Create custom HTTPRequestHandler class
13 | class EmbeddedChartHTTPRequestHandler(BaseHTTPRequestHandler):
14 |
15 | def get_embedding_url(self, chartId):
16 | # remember, in a real application, you should ensure your user is authenticated and authorized to view the chart before you return the signed URL.
17 |
18 | # replace these constants with the correct values for your Charts instance
19 | CHARTS_EMBEDDING_BASE_URL = '~REPLACE~CHARTS_EMBEDDING_BASE_URL' # Replace with the base URL to your Charts instance, e.g. https://charts.mongodb.com/charts-foo-abcde (no trailing slash)
20 | EMBEDDING_SIGNING_KEY = '~REPLACE~EMBEDDING_SIGNING_KEY' # Replace with the Embedding Signing Key generated by your Charts admin
21 | EXPIRY_TIME_SECONDS = 300 # Set to your preferred expiry period
22 | FILTER_DOCUMENT = None; # Set to a MongoDB Query document if you want to filter the chart, e.g. '{ foo: { $gt: 10 }}'
23 | AUTOREFRESH_TIME_SECONDS = None; # Set to a number >=10 if you want the chart to autorefresh
24 |
25 | timestamp = int(floor(time.time()))
26 | payload = Template('id=$chartId×tamp=$timestamp&expires-in=$expiry').substitute(chartId=chartId, timestamp=timestamp, expiry=EXPIRY_TIME_SECONDS)
27 | if not FILTER_DOCUMENT is None:
28 | payload += '&filter=' + urllib.parse.quote(FILTER_DOCUMENT)
29 | if not AUTOREFRESH_TIME_SECONDS is None:
30 | payload += '&autorefresh=' + str(AUTOREFRESH_TIME_SECONDS)
31 | signature = hmac.new(EMBEDDING_SIGNING_KEY.encode('UTF-8'), msg=payload.encode('UTF-8'), digestmod=hashlib.sha256).hexdigest()
32 | url = Template('$baseUrl/embed/charts?$payload&signature=$signature').substitute(baseUrl=CHARTS_EMBEDDING_BASE_URL, payload=payload, signature=signature)
33 |
34 | return url
35 |
36 | # helper method to return 200 response header
37 | def send_headers(self):
38 | self.send_response(200)
39 | self.send_header('Content-type','text/html')
40 | self.end_headers()
41 |
42 | # handle GET command
43 | def do_GET(self):
44 | # serve embedding signature
45 | if self.path.startswith('/api/embeddedchart/'):
46 | self.send_headers()
47 | chartId = self.path.split('/')[-1]
48 | self.wfile.write(bytes(self.get_embedding_url(chartId), 'UTF-8'))
49 | return
50 |
51 | # serve index.html file
52 | elif self.path == '/':
53 | f = open('./index.html')
54 | self.send_headers()
55 | self.wfile.write(bytes(f.read(), 'UTF-8'))
56 | f.close()
57 |
58 |
59 |
60 | def run():
61 | server_address = ('127.0.0.1', 4567)
62 | httpd = HTTPServer(server_address, EmbeddedChartHTTPRequestHandler)
63 | print('http server is running at http://127.0.0.1:4567/')
64 | httpd.serve_forever()
65 |
66 | if __name__ == '__main__':
67 | run()
68 |
--------------------------------------------------------------------------------
/php/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in PHP
2 | =================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using PHP. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 |
47 | 1. Tested in PHP 7.x
48 |
49 | 2. php-mod-hash module is required
50 |
51 | 3. Open the *index.php* file (server-side code), and replace the
52 | `~REPLACE~` placeholders with the appropriate values:
53 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
54 | https://charts.mongodb.com/charts-foo-abcde
55 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
56 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
57 |
58 | 4. Optionally, set the following variables in the same file:
59 | - `$filter` if you want to apply an additional filter to the chart (e.g. "`{ foo: { $gt: 10 }}`")
60 | - `$autoRefreshSeconds` if you want the chart to automatically refresh at a predetermined interval. Note
61 | that the entire chart must be reloaded with a new token before the validity period expires.
62 |
63 | 5. Optionally, set the following variables in *src/MongoDB/Charts.php*:
64 | - `$expiry` to configure the period of validity for the token (if not set, the token lasts one day)
65 |
66 | 6. Run index.php from a PHP web service, for example: `php -S localhost:8000 -t ./` ran from this php examples directory
67 |
--------------------------------------------------------------------------------
/java/charts-embedding/src/main/java/com/mongodb/charts/App.java:
--------------------------------------------------------------------------------
1 | package com.mongodb.charts;
2 |
3 | import static spark.Spark.get;
4 | import static spark.Spark.staticFiles;
5 |
6 | import java.math.BigInteger;
7 | import java.security.InvalidKeyException;
8 | import java.security.NoSuchAlgorithmException;
9 | import java.time.Duration;
10 |
11 | import javax.crypto.Mac;
12 | import javax.crypto.spec.SecretKeySpec;
13 |
14 | import org.apache.catalina.util.URLEncoder;
15 |
16 |
17 | /**
18 | * A simple web server which returns a signed embedding url for a given chart.
19 | *
20 | * Server by default runs on port 4567.
21 | */
22 | public class App {
23 | // Replace these constants with the correct values for your Charts instance
24 |
25 | // Replace with the base URL to your Charts instance, e.g.
26 | // https://charts.mongodb.com/charts-foo-abcde (no trailing slash)
27 | private final static String CHARTS_EMBEDDING_BASE_URL = "~REPLACE~CHARTS_EMBEDDING_BASE_URL";
28 |
29 | // Replace with the Embedding Signing Key generated by your Charts admin
30 | private final static String EMBEDDING_SIGNING_KEY = "~REPLACE~EMBEDDING_SIGNING_KEY";
31 |
32 | // Set to your preferred expiry period
33 | private final static Duration expiryTime = Duration.ofMinutes(5);
34 |
35 | // Set to a MongoDB Query if you want to filter the chart, e.g. "{ foo: { $gt: 10 }}"
36 | private final static String FILTER_DOCUMENT = null;
37 |
38 | // Set to a number of seconds >=10 if you want the chart to autorefresh, eg. Duration.ofSeconds(30)
39 | private final static Duration autoRefreshTime = null;
40 |
41 | public static void main(String[] args) {
42 | staticFiles.location("www");
43 |
44 | get("/api/embeddedchart/:id", (request, response) -> {
45 | response.type("text/plain");
46 | final String id = request.params(":id");
47 | return generateSecureUrl(id);
48 | });
49 | }
50 |
51 | private static String generateSecureUrl(String id) {
52 | // Remember, in a real application, you should ensure your user is authenticated
53 | // and authorized to view the chart before you return the signed URL.
54 |
55 | long timestamp = System.currentTimeMillis() / 1000;
56 |
57 | StringBuilder payload = new StringBuilder()
58 | .append("id=").append(id)
59 | .append("×tamp=").append(timestamp)
60 | .append("&expires-in=").append(expiryTime.toMillis() / 1000);
61 |
62 | if (FILTER_DOCUMENT != null) {
63 | // Using URLEncoder as it converts spaces to %20 which is required for the signature to be validated
64 | payload.append("&filter=").append(new URLEncoder().encode(FILTER_DOCUMENT));
65 | }
66 | if (autoRefreshTime != null) {
67 | payload.append("&autorefresh=").append(autoRefreshTime.getSeconds());
68 | }
69 |
70 | String signature = generateSignedPayload(EMBEDDING_SIGNING_KEY, payload.toString());
71 |
72 | StringBuilder url = new StringBuilder(CHARTS_EMBEDDING_BASE_URL)
73 | .append("/embed/charts?")
74 | .append(payload)
75 | .append("&signature=").append(signature);
76 | return url.toString();
77 | }
78 |
79 | private static String generateSignedPayload(String key, String payload) {
80 | try {
81 | Mac hasher = Mac.getInstance("HmacSHA256");
82 | hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
83 | byte[] hashedBytes = hasher.doFinal(payload.getBytes());
84 |
85 | return new BigInteger(1, hashedBytes).toString(16);
86 | } catch (NoSuchAlgorithmException e) {
87 | e.printStackTrace();
88 | throw new RuntimeException("Could not get algorithm for HmacSHA256");
89 |
90 | } catch (InvalidKeyException e) {
91 | e.printStackTrace();
92 | throw new RuntimeException("Provided key was invalid, possibly null");
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/embedding-sdk/unauthenticated/src/index.js:
--------------------------------------------------------------------------------
1 | import "regenerator-runtime/runtime";
2 | import ChartsEmbedSDK from "@mongodb-js/charts-embed-dom";
3 |
4 | const sdk = new ChartsEmbedSDK({
5 | baseUrl: "https://charts.mongodb.com/charts-embedding-examples-wgffp" // Optional: ~REPLACE~ with the Base URL from your Embed Chart dialog
6 | });
7 |
8 | const chart = sdk.createChart({
9 | chartId: "735cfa75-15b8-483a-bc2e-7c6659511c7c", // Optional: ~REPLACE~ with the Chart ID from your Embed Chart dialog
10 | height: "700px"
11 | });
12 |
13 | async function renderChart() {
14 | await chart.render(document.getElementById("chart"));
15 |
16 | /*
17 | chart.refresh()
18 | Manually fetches the latest data for the chart
19 | */
20 | document.getElementById("refresh").addEventListener("click", () => {
21 | chart.refresh();
22 | });
23 |
24 | /*
25 | chart.setRefreshInterval(interval: number)
26 | The default rate is to never refresh after rendering.
27 | The minimum rate is every 10 seconds.
28 | Setting to 0 returns the chart to the default setting.
29 |
30 | chart.getRefreshInterval()
31 | Returns a number pertaining to the charts current
32 | refresh interval.
33 | */
34 | document
35 | .getElementById("refresh-interval")
36 | .addEventListener("change", async e => {
37 | var refreshInterval = e.target.value;
38 | refreshInterval
39 | ? chart.setRefreshInterval(Number(refreshInterval))
40 | : chart.setRefreshInterval(0);
41 |
42 | var currentRefreshInterval = await chart.getRefreshInterval();
43 | document.getElementById(
44 | "currentRefreshInterval"
45 | ).innerText = currentRefreshInterval;
46 | });
47 |
48 | /*
49 | chart.setFilter(filter: object)
50 | Filters the chart with the given filter string.
51 | It's important to manually whitelist fields you want users
52 | to be able to filter on. Do this in the Embedded settings of
53 | your chart.
54 |
55 | chart.getFilter()
56 | Returns the current filter object. The key is the field,
57 | and the value the query.
58 | */
59 | document
60 | .getElementById("country-filter")
61 | .addEventListener("change", async e => {
62 | const country = e.target.value;
63 | const currentFilterDOM = document.getElementById("currentFilter");
64 | if (country) {
65 | await chart.setFilter({ "address.country": country }); // Optional: ~REPLACE~ with the your own whitelisted field
66 | const filter = await chart.getFilter();
67 | currentFilterDOM.innerText = JSON.stringify(filter);
68 | } else {
69 | await chart.setFilter({});
70 | const filter = await chart.getFilter();
71 | currentFilterDOM.innerText = JSON.stringify(filter);
72 | }
73 | });
74 |
75 | /*
76 | chart.setTheme(theme: 'dark' | 'light');
77 | When the chart is set to dark, it's background becomes transparent.
78 | It is important when activating this setting you set the background of
79 | the body to an appropriate colour.
80 |
81 | chart.getTheme()
82 | The current state of the charts theme is maintained by the chart.
83 | Returns a string.
84 | */
85 | document
86 | .getElementById("themeSwitch")
87 | .addEventListener("change", async function() {
88 | if (this.checked) {
89 | await chart.setTheme("dark");
90 | document.body.classList.toggle("dark-mode", true);
91 | } else {
92 | await chart.setTheme("light");
93 | document.body.classList.toggle("dark-mode", false);
94 | }
95 |
96 | var currentTheme = await chart.getTheme();
97 | document.getElementById("currentTheme").innerText = currentTheme;
98 | });
99 | }
100 |
101 | renderChart().catch(e => window.alert(e.message));
102 |
--------------------------------------------------------------------------------
/c-sharp/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in C#
2 | ================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using C# on .NET Core. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 | 1. Ensure you have .NET Core installed and an editor such as Visual Studio or Visual Studio Code
47 |
48 | 2. Clone the Git repository or download the code to your computer.
49 |
50 | 3. Open the *Controllers\EmbeddedChartController.cs* file (server-side code), and replace the
51 | `~REPLACE~` placeholders with the appropriate values:
52 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
53 | https://charts.mongodb.com/charts-foo-abcde
54 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
55 |
56 | 4. Optionally, set the following variables in the same file:
57 | - `expiryTime` to configure the period of validity for the token (if not set, the token lasts one day)
58 | - `FILTER_DOCUMENT` if you want to apply an additional filter to the chart (e.g. "`{ foo: { $gt: 10 }}`")
59 | - `autoRefreshTime` if you want the chart to automatically refresh at a predetermined interval. Note
60 | that the entire chart must be reloaded with a new token before the validity period expires.
61 |
62 | 5. Open the *wwwroot\index.html* file (client-side code), and replace:
63 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
64 |
65 | 6. Launch the application to access the page in your browser. You should see the chart embedded
66 | within the sample page.
67 |
68 | Next Steps
69 | ----------
70 | Once you're ready to embed charts in your own applications, keep the following in mind:
71 |
72 | * Always keep the Embedding Signing Key secure, and never put it inside client code. Anyone who
73 | has this key will be able to embed charts in any application.
74 |
75 | * Always authenticate users and perform any required authorization checks before generating the
76 | signed embedding URLs. The value of this mechanism is that you can restrict who can view the
77 | embedded charts, but this won't work if you give the signed URLs out to anonymous users!
78 |
79 | * Consider what expiration period is appropriate. The signed URLs include a timestamp, which
80 | Charts will compare against the current time, within the tolerance of the specified expiry period.
81 | Depending on the architecture of your application, you may want a very short expiry period
82 | (e.g. if you generate a new signature on every request) or a longer one (if the URL needs to
83 | be cached).
84 |
--------------------------------------------------------------------------------
/python/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in Python
2 | ================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using Python 3. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 | 1. Ensure you have a Python 3.x installed. You can confirm with `python --version`. On some
47 | operating systems, Python 3 is available as the `python3` binary instead.
48 |
49 | 2. Clone the Git repository or download the code to your computer.
50 |
51 | 3. Open the *server.py* file (server-side code), and replace the
52 | `~REPLACE~` placeholders with the appropriate values:
53 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
54 | https://charts.mongodb.com/charts-foo-abcde
55 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
56 |
57 | 4. Optionally, set the following variables in the same file:
58 | - `EXPIRY_TIME_SECONDS` to configure the period of validity for the token (if not set, the token lasts one day)
59 | - `FILTER_DOCUMENT` if you want to apply an additional filter to the chart (e.g. `'{ foo: { $gt: 10 }}'`)
60 | - `AUTOREFRESH_TIME_SECONDS` if you want the chart to automatically refresh at a predetermined interval. Note
61 | that the entire chart must be reloaded with a new token before the validity period expires.
62 |
63 | 5. Open the *index.html* file (client-side code), and replace:
64 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
65 |
66 | 6. Run `python server.py` to start the web server.
67 |
68 | 7. You should see the chart embedded within the sample page on [http://localhost:4567](http://localhost:4567).
69 |
70 | Next Steps
71 | ----------
72 | Once you're ready to embed charts in your own applications, keep the following in mind:
73 |
74 | * Always keep the Embedding Signing Key secure, and never put it inside client code. Anyone who
75 | has this key will be able to embed charts in any application.
76 |
77 | * Always authenticate users and perform any required authorization checks before generating the
78 | signed embedding URLs. The value of this mechanism is that you can restrict who can view the
79 | embedded charts, but this won't work if you give the signed URLs out to anonymous users!
80 |
81 | * Consider what expiration period is appropriate. The signed URLs include a timestamp, which
82 | Charts will compare against the current time, within the tolerance of the specified expiry period.
83 | Depending on the architecture of your application, you may want a very short expiry period
84 | (e.g. if you generate a new signature on every request) or a longer one (if the URL needs to
85 | be cached).
86 |
--------------------------------------------------------------------------------
/java/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in Java
2 | ================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using Java. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 | 1. Ensure you have a JDK installed, and Maven
47 |
48 | 2. Clone the Git repository or download the code to your computer.
49 |
50 | 3. Open the *src/main/java/com/mongodb/charts/App.java* file (server-side code), and replace the
51 | `~REPLACE~` placeholders with the appropriate values:
52 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
53 | https://charts.mongodb.com/charts-foo-abcde
54 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
55 |
56 | 4. Optionally, set the following variables in the same file:
57 | - `expiryTime` to configure the period of validity for the token (if not set, the token lasts one day)
58 | - `FILTER_DOCUMENT` if you want to apply an additional filter to the chart (e.g. "`{ foo: { $gt: 10 }}`")
59 | - `autoRefreshTime` if you want the chart to automatically refresh at a predetermined interval. Note
60 | that the entire chart must be reloaded with a new token before the validity period expires.
61 |
62 | 5. Open the *src/main/resources/www/index.html* file (client-side code), and replace:
63 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
64 |
65 | 6. Run `mvn install` within *charts-embedding*
66 |
67 | 7. Launch the application by running `java -jar target/charts-embedding-1.0-with-deps.jar`
68 |
69 | 8. You should see the chart embedded within the sample page on [http://localhost:4567](http://localhost:4567).
70 |
71 | Next Steps
72 | ----------
73 | Once you're ready to embed charts in your own applications, keep the following in mind:
74 |
75 | * Always keep the Embedding Signing Key secure, and never put it inside client code. Anyone who
76 | has this key will be able to embed charts in any application.
77 |
78 | * Always authenticate users and perform any required authorization checks before generating the
79 | signed embedding URLs. The value of this mechanism is that you can restrict who can view the
80 | embedded charts, but this won't work if you give the signed URLs out to anonymous users!
81 |
82 | * Consider what expiration period is appropriate. The signed URLs include a timestamp, which
83 | Charts will compare against the current time, within the tolerance of the specified expiry period.
84 | Depending on the architecture of your application, you may want a very short expiry period
85 | (e.g. if you generate a new signature on every request) or a longer one (if the URL needs to
86 | be cached).
87 |
--------------------------------------------------------------------------------
/node/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in Node
2 | ==================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using Node js. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 | 1. Ensure you have Node installed. You can confirm with `node --version`. On some
47 | operating systems, Node available as the `nodejs` binary instead.
48 |
49 | 2. Clone the Git repository or download the code to your computer.
50 |
51 | 3. Open the *server.js* file (server-side code), and replace the
52 | `~REPLACE~` placeholders with the appropriate values:
53 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
54 | https://charts.mongodb.com/charts-foo-abcde
55 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
56 |
57 | 4. Optionally, set the following variables in the same file:
58 | - `EXPIRY_TIME_SECONDS` to configure the period of validity for the token (if not set, the token lasts one day)
59 | - `FILTER_DOCUMENT` if you want to apply an additional filter to the chart (e.g. `{ foo: { $gt: 10 }}`)
60 | - `AUTOREFRESH_TIME_SECONDS` if you want the chart to automatically refresh at a predetermined interval. Note
61 | that the entire chart must be reloaded with a new token before the validity period expires.
62 |
63 | 5. Open the *static/index.html* file (client-side code), and replace:
64 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
65 |
66 | 6. Run `npm install` to install the package dependencies
67 |
68 | 7. Run `npm start` to start the server
69 |
70 | 8. You should see the chart embedded within the sample page on [http://localhost:3000](http://localhost:3000).
71 |
72 | Next Steps
73 | ----------
74 | Once you're ready to embed charts in your own applications, keep the following in mind:
75 |
76 | * Always keep the Embedding Signing Key secure, and never put it inside client code. Anyone who
77 | has this key will be able to embed charts in any application.
78 |
79 | * Always authenticate users and perform any required authorization checks before generating the
80 | signed embedding URLs. The value of this mechanism is that you can restrict who can view the
81 | embedded charts, but this won't work if you give the signed URLs out to anonymous users!
82 |
83 | * Consider what expiration period is appropriate. The signed URLs include a timestamp, which
84 | Charts will compare against the current time, within the tolerance of the specified expiry period.
85 | Depending on the architecture of your application, you may want a very short expiry period
86 | (e.g. if you generate a new signature on every request) or a longer one (if the URL needs to
87 | be cached).
88 |
--------------------------------------------------------------------------------
/stitch/README.md:
--------------------------------------------------------------------------------
1 | MongoDB Charts Embedding Example - Verified Signature Auth in Stitch
2 | ====================================================================
3 |
4 | Background
5 | ----------
6 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface.
7 | You can view the visualizations within the Charts UI, or you can use the Embedding feature to render
8 | the charts in an external web application. When you embed a chart, you can choose whether you want
9 | it to be Unauthenticated (meaning anyone who has the embed code can view the chart), or to use
10 | "Verified Signature" authentication (which checks the integrity of a signature in the URL before the
11 | chart will render).
12 |
13 | For the "Unauthenticated" option, you can copy the provided snippet and include it in any web site;
14 | no extra steps are required.
15 |
16 | The Verified Signature option requires a few more steps to implement but it is
17 | more secure — your app will generate the signature on the server side after first authenticating
18 | and authorizing the user, and the URL will stop working after a specified time period.
19 |
20 | This project contains a simple sample app showing how to implement "Verified Signature" authentication
21 | using a MongoDB Stitch app. Samples for other languages and platforms are provided elsewhere in this
22 | repository.
23 |
24 | Preparing your Chart for Embedding
25 | ----------------------------------
26 |
27 | 1. Log onto MongoDB Charts
28 |
29 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
30 |
31 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose
32 | *Embedding Options* from the *...* menu. Make sure that embedding is enabled for this data source,
33 | using either authentication mode.
34 |
35 | 4. Find the chart you want to embed, click the *...* menu and select Embed Chart.
36 |
37 | 5. Select the *Verified Signature* tab and turn on embedding.
38 |
39 | 6. Copy the IFRAME embed code from this dialog and keep it handy
40 |
41 | 7. Get the Embedding Signing Key from the Admin Settings page. If you are not a Charts Admin you
42 | will need to request this info from someone with this role.
43 |
44 | Running this Sample
45 | -------------------
46 | 1. Go to https://cloud.mongodb.com, sign in and create a new Stitch app.
47 |
48 | 2. Enable Anonymous Authentication on the Stitch App under *Getting Started*.
49 |
50 | 3. Click *Functions* and then *Create New Function*
51 |
52 | 4. Enter "getEmbeddingUrl" as the function name, leaving all other options as they are.
53 |
54 | 5. Click the *Function Editor" tab, and paste the contents of the `stitch-functions/getEmbeddingUrl.js` file
55 | into the editor.
56 |
57 | 6. Replace the `~REPLACE~` placeholders in the pasted code for the following variables:
58 | - `~REPLACE~CHARTS_EMBEDDING_BASE_URL` with the base URL of your charts instance, e.g.
59 | https://charts.mongodb.com/charts-foo-abcde
60 | - `~REPLACE~EMBEDDING_SIGNING_KEY` with the Embedding Signing key you obtained above
61 |
62 | 7. Optionally, set the following variables in the same file:
63 | - `EXPIRY_TIME_SECONDS` to configure the period of validity for the token (if not set, the token lasts one day)
64 | - `FILTER_DOCUMENT` if you want to apply an additional filter to the chart (e.g. `{ foo: { $gt: 10 }}`)
65 | - `AUTOREFRESH_TIME_SECONDS` if you want the chart to automatically refresh at a predetermined interval. Note
66 | that the entire chart must be reloaded with a new token before the validity period expires.
67 |
68 | 8. Save the Stitch function.
69 |
70 | 9. Open the *index.html* file (client-side code), and replace the `~REPLACE~` placeholders:
71 | - `~REPLACE~STITCH_APP_ID` with the Stitch App ID, shown in the top left of the Stitch console
72 | - `~REPLACE~CHART_ID` with the value of the *id* parameter from the IFRAME snippet you copied from Charts
73 |
74 | 10. Open *index.html* from your local computer in a web browser. (Alternatively you can use the Stitch Hosting
75 | feature to host this file once you have made the above modifications).
76 |
77 | Next Steps
78 | ----------
79 | Once you're ready to embed charts in your own applications, keep the following in mind:
80 |
81 | * Always keep the Embedding Signing Key secure, and never put it inside client code. Anyone who
82 | has this key will be able to embed charts in any application.
83 |
84 | * Always authenticate users and perform any required authorization checks before generating the
85 | signed embedding URLs. The value of this mechanism is that you can restrict who can view the
86 | embedded charts, but this won't work if you give the signed URLs out to anonymous users!
87 |
88 | * Consider what expiration period is appropriate. The signed URLs include a timestamp, which
89 | Charts will compare against the current time, within the tolerance of the specified expiry period.
90 | Depending on the architecture of your application, you may want a very short expiry period
91 | (e.g. if you generate a new signature on every request) or a longer one (if the URL needs to
92 | be cached).
93 |
--------------------------------------------------------------------------------
/embedding-sdk/unauthenticated/readme.md:
--------------------------------------------------------------------------------
1 | # MongoDB Charts Embedding Example - Unauthenticated Embedded Chart
2 |
3 | ## Background
4 |
5 | 📄 _[See the MongoDB Charts Embedding Docs for more details](https://docs.mongodb.com/charts/saas/embedding-charts/)_
6 |
7 | 🎮 _[Play with a live demo of this sample here](https://codesandbox.io/s/github/mongodb/charts-embedding-examples/tree/master/embedding-sdk/unauthenticated)_
8 |
9 | MongoDB Charts allows you to create visualizations of your MongoDB data using a simple web interface. You can view the visualizations within the Charts UI, or you can use the Embedding feature to render the charts in an external web application.
10 |
11 | Charts can be embedded either using a simple IFRAME snippet, or by using the Charts Embedding SDK from your JavaScript code. When using the SDK, embedded charts can be either unauthenticated (meaning anyone who has the embed code can view the chart), or authenticated (whereby the user can only view the chart if they have an active authentication session linked to a Charts authentication provider).
12 |
13 | This sample shows how to use the JavaScript Embedding SDK to render unauthenticated embedded charts, along with showing off the various ways your application can interact with charts using the SDK.
14 |
15 | #### The features included in this demo are as follows:
16 |
17 | - Render an embedded chart on a web page
18 | - Set the charts theme to either `'light'` or `'dark'`
19 | - Get the charts current theme
20 | - Set the charts refresh interval
21 | - Note, the default interval is 0, implying that after rendering, the chart will never refresh.
22 | - The minimum refresh interval is 10 seconds.
23 | - Get the charts current refresh interval
24 | - Manually refresh the chart
25 | - Set the charts current filter
26 | - Note, filtering on a chart requires setting up white listed fields in MongoDB Charts. We have done this for our sample data.
27 | - Get the current filter on a chart
28 |
29 | ## Preparing your Chart for Embedding
30 |
31 | This sample is preconfigured to render a specific chart. You can run the sample as-is, or you can modify it to render your own chart by completing the following steps:
32 |
33 | 1. Log onto MongoDB Charts
34 |
35 | 2. If you haven't done so already, create a chart on any dashboard that you would like to embed.
36 |
37 | 3. Go to the Data Sources tab, find the data source that you are using on the chart, and choose External Sharing Options from the ... menu. Make sure that embedding is enabled for this data source and select '**Unauthenticated or Verified Signature**'
38 |
39 | 4. Find the chart you want to embed, click the **...** menu and select **Embed Chart**
40 |
41 | 5. Ensure the Unauthenticated tab is selected and turn on '**Enable unauthenticated access**'
42 |
43 | 6. Select the **Javascript SDK** option
44 |
45 | 7. Note the Chart ID and the Chart Base URL, as you will need them for running the demo.
46 |
47 | 8. **Optional**
48 | In the same menu, note the **User Specified Filters** option. If you wish to try out filtering on your own dataset, you will need to whitelist a field by which to filter on. For example, our sample AirBnB dataset filters on `address.country`.
49 | Furthermore, the filter related code in `src/index.js` will need to be updated to conform to the filter query you wish to run, and the options provided in `index.html` will need to be updated too. To be clear,
50 | - Update the query **field** in `src/index.js`
51 | - Update the query **values** in `index.html`
52 |
53 | ## Running this Sample
54 |
55 | _The following steps presume the use of npm, though yarn works as well._
56 |
57 | 1. Ensure you have Node installed. You can confirm with `node --version`. On some operating systems, Node available as the `nodejs` binary instead.
58 |
59 | 2. Clone the Git repository or download the code to your computer.
60 |
61 | 3. **Optional**
62 | If you do not wish to use our sample data and have completed the above steps to prepare your own chart for embedding,
63 | - Open the _index.js_ file (`src/index.js`)
64 | - Replace the `baseUrl` string on with the base URL you copied from the MongoDB Charts Embedded Chart menu (look for "\~REPLACE\~" in the comments)
65 | - Replace the `chartId` string on with the chart ID you copied from the MongoDB Charts Embedded Chart menu (look for "\~REPLACE\~" in the comments)
66 | - Replace `address.country` in the `setFilter` code with your whitelisted field (look for "\~REPLACE\~" in the comments)
67 | 4. Run `npm install` to install the package dependencies.
68 | 5. Run `npm install -g parcel-bundler` to install Parcel. You may need to run `sudo npm install -g parcel-bundler` if you lack permissions.
69 | - Optional Parcel.js documentation https://parceljs.org/ for more information on what this is
70 | 6. Run `parcel index.html` to launch the sample application
71 |
72 | This should create a local server running the Charts demo. Open a web browser and navigate to `http://localhost:1234` in the url bar to see the sample.
73 |
74 | ## Next Steps
75 |
76 | Once you gain an understanding of the API, consider the following
77 |
78 | - Take on the optional steps to prepare and manipulate your own data source rather than the sample.
79 | - Think whether an unauthenticated chart is the feature you're after. Embedding iframes from Charts is a great way to showcase your data if you don't need the user to interact with the chart.
80 | - Consider the data you're making available, and the queries you're allowing. If the data is sensitive and you need to ensure the charts can only be accessed by authorized people, you should look at using authenticated embedding.
81 |
82 | Happy Charting! 🚀📈
83 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and
10 | distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright
13 | owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities
16 | that control, are controlled by, or are under common control with that entity.
17 | For the purposes of this definition, "control" means (i) the power, direct or
18 | indirect, to cause the direction or management of such entity, whether by
19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity exercising
23 | permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications, including
26 | but not limited to software source code, documentation source, and configuration
27 | files.
28 |
29 | "Object" form shall mean any form resulting from mechanical transformation or
30 | translation of a Source form, including but not limited to compiled object code,
31 | generated documentation, and conversions to other media types.
32 |
33 | "Work" shall mean the work of authorship, whether in Source or Object form, made
34 | available under the License, as indicated by a copyright notice that is included
35 | in or attached to the work (an example is provided in the Appendix below).
36 |
37 | "Derivative Works" shall mean any work, whether in Source or Object form, that
38 | is based on (or derived from) the Work and for which the editorial revisions,
39 | annotations, elaborations, or other modifications represent, as a whole, an
40 | original work of authorship. For the purposes of this License, Derivative Works
41 | shall not include works that remain separable from, or merely link (or bind by
42 | name) to the interfaces of, the Work and Derivative Works thereof.
43 |
44 | "Contribution" shall mean any work of authorship, including the original version
45 | of the Work and any modifications or additions to that Work or Derivative Works
46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
47 | by the copyright owner or by an individual or Legal Entity authorized to submit
48 | on behalf of the copyright owner. For the purposes of this definition,
49 | "submitted" means any form of electronic, verbal, or written communication sent
50 | to the Licensor or its representatives, including but not limited to
51 | communication on electronic mailing lists, source code control systems, and
52 | issue tracking systems that are managed by, or on behalf of, the Licensor for
53 | the purpose of discussing and improving the Work, but excluding communication
54 | that is conspicuously marked or otherwise designated in writing by the copyright
55 | owner as "Not a Contribution."
56 |
57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58 | of whom a Contribution has been received by Licensor and subsequently
59 | incorporated within the Work.
60 |
61 | 2. Grant of Copyright License.
62 |
63 | Subject to the terms and conditions of this License, each Contributor hereby
64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65 | irrevocable copyright license to reproduce, prepare Derivative Works of,
66 | publicly display, publicly perform, sublicense, and distribute the Work and such
67 | Derivative Works in Source or Object form.
68 |
69 | 3. Grant of Patent License.
70 |
71 | Subject to the terms and conditions of this License, each Contributor hereby
72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73 | irrevocable (except as stated in this section) patent license to make, have
74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75 | such license applies only to those patent claims licensable by such Contributor
76 | that are necessarily infringed by their Contribution(s) alone or by combination
77 | of their Contribution(s) with the Work to which such Contribution(s) was
78 | submitted. If You institute patent litigation against any entity (including a
79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80 | Contribution incorporated within the Work constitutes direct or contributory
81 | patent infringement, then any patent licenses granted to You under this License
82 | for that Work shall terminate as of the date such litigation is filed.
83 |
84 | 4. Redistribution.
85 |
86 | You may reproduce and distribute copies of the Work or Derivative Works thereof
87 | in any medium, with or without modifications, and in Source or Object form,
88 | provided that You meet the following conditions:
89 |
90 | You must give any other recipients of the Work or Derivative Works a copy of
91 | this License; and
92 | You must cause any modified files to carry prominent notices stating that You
93 | changed the files; and
94 | You must retain, in the Source form of any Derivative Works that You distribute,
95 | all copyright, patent, trademark, and attribution notices from the Source form
96 | of the Work, excluding those notices that do not pertain to any part of the
97 | Derivative Works; and
98 | If the Work includes a "NOTICE" text file as part of its distribution, then any
99 | Derivative Works that You distribute must include a readable copy of the
100 | attribution notices contained within such NOTICE file, excluding those notices
101 | that do not pertain to any part of the Derivative Works, in at least one of the
102 | following places: within a NOTICE text file distributed as part of the
103 | Derivative Works; within the Source form or documentation, if provided along
104 | with the Derivative Works; or, within a display generated by the Derivative
105 | Works, if and wherever such third-party notices normally appear. The contents of
106 | the NOTICE file are for informational purposes only and do not modify the
107 | License. You may add Your own attribution notices within Derivative Works that
108 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
109 | provided that such additional attribution notices cannot be construed as
110 | modifying the License.
111 | You may add Your own copyright statement to Your modifications and may provide
112 | additional or different license terms and conditions for use, reproduction, or
113 | distribution of Your modifications, or for any such Derivative Works as a whole,
114 | provided Your use, reproduction, and distribution of the Work otherwise complies
115 | with the conditions stated in this License.
116 |
117 | 5. Submission of Contributions.
118 |
119 | Unless You explicitly state otherwise, any Contribution intentionally submitted
120 | for inclusion in the Work by You to the Licensor shall be under the terms and
121 | conditions of this License, without any additional terms or conditions.
122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
123 | any separate license agreement you may have executed with Licensor regarding
124 | such Contributions.
125 |
126 | 6. Trademarks.
127 |
128 | This License does not grant permission to use the trade names, trademarks,
129 | service marks, or product names of the Licensor, except as required for
130 | reasonable and customary use in describing the origin of the Work and
131 | reproducing the content of the NOTICE file.
132 |
133 | 7. Disclaimer of Warranty.
134 |
135 | Unless required by applicable law or agreed to in writing, Licensor provides the
136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138 | including, without limitation, any warranties or conditions of TITLE,
139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140 | solely responsible for determining the appropriateness of using or
141 | redistributing the Work and assume any risks associated with Your exercise of
142 | permissions under this License.
143 |
144 | 8. Limitation of Liability.
145 |
146 | In no event and under no legal theory, whether in tort (including negligence),
147 | contract, or otherwise, unless required by applicable law (such as deliberate
148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
149 | liable to You for damages, including any direct, indirect, special, incidental,
150 | or consequential damages of any character arising as a result of this License or
151 | out of the use or inability to use the Work (including but not limited to
152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153 | any and all other commercial damages or losses), even if such Contributor has
154 | been advised of the possibility of such damages.
155 |
156 | 9. Accepting Warranty or Additional Liability.
157 |
158 | While redistributing the Work or Derivative Works thereof, You may choose to
159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160 | other liability obligations and/or rights consistent with this License. However,
161 | in accepting such obligations, You may act only on Your own behalf and on Your
162 | sole responsibility, not on behalf of any other Contributor, and only if You
163 | agree to indemnify, defend, and hold each Contributor harmless for any liability
164 | incurred by, or claims asserted against, such Contributor by reason of your
165 | accepting any such warranty or additional liability.
166 |
167 | END OF TERMS AND CONDITIONS
168 |
169 | Copyright 2019, MongoDB
170 |
171 | Licensed under the Apache License, Version 2.0 (the "License");
172 | you may not use this file except in compliance with the License.
173 | You may obtain a copy of the License at
174 |
175 | http://www.apache.org/licenses/LICENSE-2.0
176 |
177 | Unless required by applicable law or agreed to in writing, software
178 | distributed under the License is distributed on an "AS IS" BASIS,
179 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180 | See the License for the specific language governing permissions and
181 | limitations under the License.
182 |
--------------------------------------------------------------------------------