Advanced JavaScript: Environment Setup, DB integration and Securing Client in MeteorJS

This tutorial is in continuation with previous tutorial. If you are new here, read first chapter of this series Advanced JavaScript: Introduction To Server Side JavaScript Using Meteor before reading this tutorial.

I will be skipping traditional TO DO app tutorial here, as you can find it anywhere on web. Rather, I will try to explain few scenarios that developers come across while developing apps using JavaScript frameworks in real-time.

In this tutorial we will be covering

  • Setting up development environment for Meteor?
  • How to integrate your Meteor application with Mongo DB?
  • How to secure your Meteor application?

Setting up development environment for Meteor
Most popular IDEs like Sublime, Webstorm and on-cloud IDE- Cloud 9 integrates seamlessly with Meteor. I am a fan of Sublime so I will explain how to set up autocomplete engine into Sublime Text 3. You can visit Meteor website and setup your own IDE.
Open Sublime Text-

  1. From menu bar select preferences-> Settings -Users
  2. If you have not made any changes from time you installed Sublime replace contents of file with following code-
  3. {
    	"color_scheme": "Packages/Color Scheme - Default/Sunburst.tmTheme",
    	"font_size": 12,
    	"ignored_packages":
    	[
    	], 
    	"auto_complete_triggers": [ { "characters": "<", "selector": "text.html" }, { "characters": ".", "selector": "source.js" } ]
    }
    
  4. Now press Cmd/Ctrl+Shift+P and type Install. You will see ‘Package Control: Install Package’ in menu. Select it and press Enter. Now search for TernJS and click on it. Package will install automatically. Restart Sublime and you will see your Sublime just got smarter and it can autocomplete Meteor code for you.

loading-library-sublime

How to integrate your Meteor application with Mongo DB?
We already have Meteor code running on local server. Now let’s add DB support. Meteor comes bundled with MongoDB so you don’t need to include it again, still if you wish you can do custom setup but let’s not discuss it in this tutorial as pre bundle itself is self-sufficient to create end-end application.

  1. Lets create Fishes collection.
    Fishes = new Mongo.Collection("fishes");
    

    It creates a MongoDB collection called Fishes and creates a cache connected to server.

  2. Replace if (Meteor.isClient) with this code
    if (Meteor.isClient) {
      // This code only runs on the client
      Template.body.helpers({
        fishes: function () {
          return Fishes.find({});
        }
      });
    }
    }
  3. From terminal type
    meteor mongo
  4. meteor-mongo-terminal

  5. Now write this insert query to add a new fish

    db.fishes.insert({ text: "pygmy angelfish",imageurl:"http://www.seascapestudio.net/reference/fishes/centropyge_argi.jpg", createdAt: new Date() });
  6. check-db-for-fishes
    mongo-insert-singleton

  7. Now go to http://localhost:3000 and check if you are can see live fish coming from live data. If yes, you just added DB connectivity to your meteor application.

Now add some more blue fishes to grow your list-

db.fishes.insert({ text: "pygmy angelfish",imageurl:"http://www.seascapestudio.net/reference/fishes/centropyge_argi.jpg", createdAt: new Date() });
db.fishes.insert({ text: "blue dot grouper",imageurl:"http://www.richard-seaman.com/Underwater/Egypt/Highlights/PeacockGrouper.jpg", createdAt: new Date() });
db.fishes.insert({ text: "blue line grouper",imageurl:"http://www.aquariumdomain.com/images/fish_marine/grouper_blueline2.jpg", createdAt: new Date() });
db.fishes.insert({ text: "teira batfish",imageurl:"http://www.aquariumdomain.com/images/fish_marine/tieraBatfish8.jpg", createdAt: new Date() });
db.fishes.insert({ text: "convict blenny",imageurl:"http://www.roslyndakin.com/wp-content/uploads/2011/01/convictadult.jpg", createdAt: new Date() });

How to secure your application?
One of main concern while using JavaScript for both server and client side code is security. Try running following code from console:

Fishes.insert({ text: "Fighter",imageurl:"http://bongotimes.com/wp-content/uploads/2014/11/beautiful-fish.png", createdAt: new Date() });

From MongoDB console run

db.fishes.find()

and you will see both client and server have a new beautiful red fighter fish. If you noticed, you were able to alter DB using Javascript without authenticating with server which is a security breach. This is beacause Meteor has insecure package selected by default.

  1. To remove insecure package navigate to your project folder in Command Line /Terminal and run-
  2. meteor remove insecure
    

    meteor-remove-unsecure

  3. Now enable the accounts system and UI using following command from root directory of project-
  4. meteor add accounts-ui accounts-password

    accounts-addition
    I find package control really useful. They make your life lot easier by taking care of entire setup for useful technical modules, as in this example entire user management. Few years back implementing secured login module was estimated around 100 hours which came down to 1 minute with recent advancement in web technologies.

  5. Now add login buttons to your app. Paste following blaze template anywhere in code. I will paste it in header.
  6. {{> loginButtons}}
    
  7. Now signup for new account and run this command from console-
  8. if (! Meteor.userId()) {
          throw new Meteor.Error("not-authorized");
        }
    Fishes.insert({ text: "Fighter",imageurl:"http://bongotimes.com/wp-content/uploads/2014/11/beautiful-fish.png", createdAt: new Date() });
    

    meteor-not-authenticated

    You will notice you are not able to insert data any more. Meteor.user() will return user data to you.

We will discuss security, Blaze templates and routing in detail in next chapter of this tutorial. Till then Happy Coding!

Now you can follow this tutorial on GitHub.

References-
https://github.com/Slava/tern-meteor-sublime

Images credits-
http://bongotimes.com/

Advertisements

Quickguide- Setting up Apache, PHP and MySQL on Linux servers

Login to server from terminal using ssh-

ssh root@serverip (run this in terminal)

Password- ******

To install Apache server:

At a terminal prompt enter the following command:

sudo apt-get install apache2

To install PHP5:

sudo apt-get install php5 libapache2-mod-php5

Enable PHP5 command prompt client:

sudo apt-get install php5-cli

Install cgi for PHP5-execute PHP5 scripts without installing PHP5 Apache module:

sudo apt-get install php5-cgi

Install MySQL

sudo apt-get install php5-mysql

To check if server is running-

Add a phpinfo.php file to /www folder. To add files use sftp-

Content of phpinfo.php

<?php

phpinfo();

?>

and try to access- http://serverip/phpinfo.php, if you see php information for your server, it means your server is up and running.

Some useful links and commands-

Modify default Apache server settings-

nano /etc/apache2/sites-available/default

Restart Apache Service-

sudo service apache2 restart

Test Server Details-

Welcome to Ubuntu 12.10 (GNU/Linux 3.5.0-17-generic x86_64)

* Documentation:  https://help.ubuntu.com/

 System information as of Fri Jan  4 10:23:00 UTC 2013

 System load:  0.0               Processes:           64

 Usage of /:   6.0% of 19.68GB   Users logged in:     1

 Memory usage: 37%               IP address for eth0: ip

 Swap usage:   1%                IP address for eth1: ip

 Graph this data and manage this system at https://landscape.canonical.com/