Navigation

Dashboard

This tutorial demonstrates how to use MongoDB Stitch to create a realtime dashboard that displays simple Point-of-Sale data. The dashboard can be extended to use Telemetry, IoT, or log data that might be regularly encountered.

The tutorial uses the following Stitch features:

  • JavaScript SDK
  • Integrated HTTP Service
  • Data access rules (read/write)
  • Email/password, API Key, and anonymous authentication

This tutorial starts with all users being able to read and write any data, but transitions to a model where:

  • An API can be used to access a specific, aggregated subset of data.
  • Data can only be loaded using an API key.
  • Authenticated users can view a realtime dashboard, but do not have access to personally identifiable information.

Prerequisites

For this app, you need the following:

This app writes to the Receipts collection in the SalesReporting database. Ensure this collection is empty before starting this procedure.

Stitch Access to MongoDB

Each MongoDB Stitch app contains a default user with the necessary permissions to read and write to the Receipts collection on the linked Atlas MongoDB deployment. Do not modify this user’s permissions, or you may prevent the application from running correctly.

Additionally, MongoDB Stitch cannot override any document validation rules configured on the linked Atlas MongoDB deployment. Do not create any document validation rules for the SalesReporting database, or you may prevent the application from running correctly.

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes

1

Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.

2

Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.

Important

You must deploy the Atlas cluster with MongoDB version 3.4 or greater.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier), M2, and M5 Limitations.

3

Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

B. Get Started in MongoDB Stitch

Estimated Time to Complete: ~5 minutes

From the homepage of the MongoDB Stitch console, go to Getting Started and perform the following steps:

  1. Turn on Anonymous Authentication.

  2. Initialize a MongoDB Collection.

    Note

    For each MongoDB collection that your Stitch application accesses, you must specify the namespace in Stitch and the appropriate rules.

    • For Database, enter SalesReporting.
    • For Collection, enter Receipts.

Each document in the SalesReporting.Receipts represents an order for a pizza. Each document has the following form:

{
    "timestamp": <int>,       // time of order
    "customerName": <string>, // customer name
    "cardNumber": <string>,   // credit card number
    "location": <string>,     // store name
    "size": <string>,         // pizza size
    "toppings": <string>,     // topping choice
    "total": <float>          // total cost
}

Update Read and Write Rules for the Collection

You must set the appropriate rules for your MongoDB collection.

  1. Under the Atlas Clusters, click on the Atlas service mongodb-atlas to view the collections accessible by your Stitch application. The view defaults to the Rules tab.

  2. To review and update the rules for a collection, click on the collection SalesReporting.Receipts. The view defaults to Field Rules.

  3. Click Top-Level Document to review rules set at the document-level.

  4. Change the read rule for the Top-Level Document to {} and click Save.

    The new rule specifies that all the fields in the documents are always readable. For more information on Stitch read rules, see MongoDB Read Rules.

  5. Change the write rule for the Top-Level Document to {} and click Save.

    The new rule specifies that all the fields in the documents are always writable. For more information on Stitch write rules, see MongoDB Write Rule.

  6. For this collection, the owner_id field does not exist. Delete the owner_id field by hovering over it and clicking the x on the right-hand side.

  7. By default, Allow All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents.

  8. Delete the filter for SalesReporting.Receipts.

    1. Click on the Filters tab.
    2. Click Delete to delete the default filter and click Save.
    3. For more information on filters, see MongoDB Filters.

MongoDB Authorization

MongoDB Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, MongoDB Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.

Similarly, MongoDB Stitch validation rules do not override document validation rules set up separately in MongoDB.

C. Download the Dashboard Application Source

Estimated Time to Complete: ~3 minutes

Download the code for the dashboard from the MongoDB Stitch GitHub example repository. The source code for the dashboard application can be found in the dashboard directory.

D. Start Loading Data through MongoDB Stitch

Estimated Time to Complete: ~7 minutes

Use the data_generator.js script to periodically generate random data and insert into the SalesReporting.Receipts collection using the Stitch Javascript SDK.

Navigate to the downloaded example directory and go to the dashboard directory.

  1. To use the Stitch Javascript SDK, add your App ID to the script. a. Edit the data_generator.js file.

    1. Replace <YOUR APP ID> with the App ID for your app. Your App ID can be found on the Clients page.
  2. Install the dependencies. From a terminal, go to the dashboard directory and run the command:

    npm install
    
  3. Run the data_generator.js file. In the same directory, run the command:

    node data_generator.js
    

    Important

    Keep the script running for the remainder of the tutorial. Terminate after finishing the tutorial.

E. Creating Simple API Access with MongoDB Stitch

Create a public HTTP endpoint that allows anyone with a secret key to get the toppings on the last 100 pizzas.

  1. In Stitch, click Add Service and click HTTP. Enter ToppingsAPI for the Service Name.

  2. Create an incoming webhook to serve the necessary data. Click the Incoming Webhooks tab and then click New Webhook then enter the following properties:

    Property Value
    Name ToppingsAPI
    Respond With Result Select this so that API users will receive documents in their response.
    HTTP Method Leave this as POST.
    Request Validation Select Require Secret As Query Param
    Secret Set to a short string. Clients must specify the secret as a query parameter when making the API call.
  3. Click Save to save these settings.

  4. Open the function editor for the webhook and add the following:

    exports = function() {
        var atlas = context.services.get('mongodb-atlas');
        var coll = atlas.db('SalesReporting').collection('Receipts');
        return coll.aggregate([
            {"$sort": {"timestamp": -1}},
            {"$sortByCount": "$toppings"},
            {"$limit": 100}]).toArray();
    }
    
  5. Click Save. See HTTP Service for more information.

  6. Test the data by calling the webhook from the terminal.

    curl -X POST [WEBHOOK_URL]?secret=[SECRET] | python -m json.tool
    

    Where the WEBHOOK_URL is the URL provided in the webhook configuration and SECRET is the secret you entered into the webhook. As long as documents were inserted into SalesReporting.Receipts, the output of the curl command should resemble the following:

    [
        {
            "_id": "Pineapple",
            "count": {
                "$numberInt": "18"
            }
        },
        {
            "_id": "Pepperoni",
            "count": {
                "$numberInt": "12"
            }
        },
        {
            "_id": "Bacon",
            "count": {
                "$numberInt": "12"
            }
        },
    ...
    

The next example shows how to serve this data through a web application.

F. Setting up your Dashboard

Estimated Time to Complete: ~10 minutes

Create a realtime dashboard of the data in SalesReporting.Receipts using the rest of the code provided.

Create a New Function

  1. In Stitch console, click Functions and then click Create New Function.

  2. Enter the following properties for the function:

    Property Value
    Name SalesTimeline
    Private Leave unselected. If selected, the function is inaccessible by a client and is only accessible in other Stitch definitions, such as webhooks and other functions.
    Can Evaluate Leave as {}. The Can Evaluate condition determines whether the function can be run. An empty document {} always evaluates to true, indicating that the function can always be run.
  3. Paste the following code in the functions editor:

    exports = function(start, end) {
        var atlas = context.services.get('mongodb-atlas');
        var coll = atlas.db('SalesReporting').collection('Receipts');
    
        return coll.find({ "timestamp": {"$gt": start, "$lt": end }},
            {"_id": 0,"timestamp": 1, "total": 1})
            .sort({"timestamp": 1})
            .limit(100)
            .toArray();
    }
    
  4. Click Save to save the function.

Run the Dashboard Example

  1. Navigate to the downloaded example directory and go to the dashboard directory.

  2. To run the code, add your App ID to the example.

    1. Edit the index.html file.
    2. Replace <YOUR APP ID> with the App ID for your app. Your App ID can be found on the Clients page.
  3. Run the dashboard example. From a terminal, go to the dashboard directory and run the command:

    npm start
    
  4. To view the dashboard, go to the local server address shown in the terminal.

The dashboard continuously graphs sales data occurring in the most recent 5 minutes.

If the graph is not updated, ensure that the data_generator.js script is still running.

G. Adding Authentication

Estimated Time to Complete: ~10 minutes

To secure the dashboard application, specify which MongoDB Stitch functions and services are accessible to authorized users using MongoDB Stitch rules.

Configure Authentication Methods

To start, use the integrated API Key and e-mail/password authentication that MongoDB Stitch offers.

  1. To start, go to the Stitch console and find Authentication in the left hand menu.

  2. Find API Keys under the Providers tab and click Edit

    1. Toggle the switch to enable API Key authentication.
    2. Click Create API Key, assign the API Key a name, and click Save.
    3. Click Copy to copy the key.
  3. Find Email/Password under the Providers tab and click Edit

    1. Toggle the switch to enable e-mail/password authentication.
    2. Set Email Confirmation URL to http://localhost:3000/#/confirm.
    3. Set Password Reset URL to http://localhost:3000/#/reset.
    4. Click Save.
  4. Now add a user with an email and password

    1. Go to the Users tab.

    2. Click + Add User.

    3. Enter an email address and password of your choosing and click Create.

      Note

      Remember the login information. It is needed later.

Update Data Generator Script

The authentication methods are set up. The next step is to update the data_generator.js and index.html to use these authentication methods.

data_generator.js should authenticate with the API token. This represents a point-of-sale device that has an API key to authenticate back to Stitch. While this is only one “device” and API key, these steps can be similarly followed to have multiple keys, each with the ability to write data for a single store location.

  1. Open the data_generator.js file in an editor.
  2. Go to the bottom of the file, comment out line 38 (adding ‘//’) and uncomment line 41 (removing ‘//’).
  3. Replace <YOUR API KEY> with the API key copied and save the file.
  4. Restart data_generator.js.

Add Function to Check Authentication Method

Next, add rules to tie everything together. To do this, add another function that checks the type of authentication that a user is logged in with. This enables the application to scope writes to only users with API key validation and reads to only users logged in with an e-mail/password.

  1. In Stitch, click Functions, and then click New Function.

  2. Enter the following properties for the function:

    Property Value
    Name CheckAuth
    Private Leave unselected.
    Can Evaluate Leave as {}. The Can Evaluate condition determines whether the function can be run. An empty document {} always evaluates to true, indicating that the function can always be run.
  3. Then, paste the following code in the function editor:

    exports = function (auth_type) {
        var user_type = context.user.type;
        var identities = context.user.identities;
    
        return user_type === auth_type || identities.some(function(id) {
            return id.provider_type === auth_type;
        });
    }
    
  4. Click Save to save the function.

Update Rules

Tie everything together with a set of comprehensive rules.

  1. Navigate to the MongoDB service in the Stitch UI by clicking mongodb-atlas on the left hand menu.

  2. Then click the Rules tab and the SalesReporting.Receipts namespace to edit its rules.

  3. Start by removing the text for the Read rule in the Top-Level Document.

  4. Define a write rule on Top-level Document to allow API Key authenticated user to write to this namespace. In the text box that appears, enter the following rule:

    {
        "%%true": {
            "%function": {
                "name": "CheckAuth",
                "arguments": ["server"]
            }
        }
    }
    
  5. Make only the timestamp and total fields readable by SDKs (any only by users that have authenticated with a username/password). To start, use the + Add button to to add the fields timestamp and total.

  6. In both of these fields, add the following read rule to check that a user is authenticated with username/password. In the text box that appears, enter the following aggregation:

    {
        "%%true": {
            "%function": {
                "name": "CheckAuth",
                "arguments": ["local-userpass"]
            }
        }
    }
    

Update Dashboard

Finally, add authentication to index.html (covering our dashboard):

  1. Open index.html file in an editor
  2. Near the top of the file, comment out line 15 and uncomment line 16
  3. Refresh your web browser. Now a prompt will appear asking to authenticate.
    1. To authenticate, use the e-mail and password created before.

Note

index.html uses a simple way to collect authentication data as it shows your password in clear text. In a production setting this would use a more robust method of collecting user name and password, but it is simplified for this example.

After completing these steps you have created a system where:

  • Data can only be loaded using an API key
  • Authenticated users can view a realtime dashboad, but only have access to specific, non-PII data
  • A public API may be used to access a specific, aggregated subset of data

Next Steps

This tutorial can be expanded beyond the scope of what is provided above. Some possibilities include:

  • Building a more robust public API to access the data by adding more functions and webhooks
  • Adding functions and using the data to create more graphs in your realtime dashboard
  • Using one of our integrations to build extra features like e-mail receipts for customers.
  • Taking the ideas here and building an API or dashboard with your own data