Share Tweet Reccomend

Express.js Authentication

Now we will discuss how to implement authentication in Express.js. Express.js was discussed previously in the Introduction to Express.js. In the discussion there, we looked at how Express is a web-application framework just like CodeIgniter, Django, or Laravel except instead of running on something like Apache or Ngnix, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. Before looking at the following section, it might be a good idea to be familiar with Express.js by reading the introduction to Express and be familiar with Node.js as well. A Node.js Primer will help you with that.

When you think authentication in web development, you think logging in and logging out. Note that this is a little bit different from authorization, which has more to do with whether a logged in user has the permissions to do a certain action on a website. This the reason that you have different roles such as “Administrator,” “Editor,” and “User” defined within different systems. For this section we’ll focus more on authentication, but a lot of the ways that you handle authentication can also be extended upon to implement authorization.

Session-Based Authentication

When you speak of authentication in modern web applications, there are a number of different implementations you could be talking about. One of the more traditional approaches is the use of sessions. Sessions go back as far as anyone can remember with anything having to do with the web. Express.js supports sessions and you can use them just as you would in other languages like PHP.

Place the following code in a file called server.js. Obviously, in a real application we’d want to separate the markup we’re returning out into views and use a templating language to render them like we did in the introduction to Express. But for now, this will do just to serve for purpose of example…

var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());
function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}
app.get('/', function(request, response) {
   response.send('This is the homepage');
});
app.get('/login', function(request, response) {
   response.send('<form method="post" action="/login">' +
  '<p>' +
    '<label>Username:</label>' +
    '<input type="text" name="username">' +
  '</p>' +
  '<p>' +
    '<label>Password:</label>' +
    '<input type="text" name="password">' +
  '</p>' +
  '<p>' +
    '<input type="submit" value="Login">' +
  '</p>' +
  '</form>');
});
app.post('/login', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if(username == 'demo' && password == 'demo'){
        request.session.regenerate(function(){
        request.session.user = username;
        response.redirect('/restricted');
        });
    }
    else {
       res.redirect('login');
    }	
});
app.get('/logout', function(request, response){
    request.session.destroy(function(){
        response.redirect('/');
    });
});
app.get('/restricted', restrict, function(request, response){
  response.send('This is the restricted area! Hello ' + request.session.user + '! click <a href="/logout">here to logout</a>');
});
app.listen(8124, function(){
    console.log('Server running...');
});

Now if you run the following command in the same directory as server.js…

node server

and then open up your browser to http://localhost:8124 you can see the homepage as defined by the default route.

Read More »

Share Tweet Reccomend

Introduction to Express.js

Express is one of the more popular solutions for running a web-server and creating web applications using Node.js. If you are not familiar with Node.js and what it is all about, this primer has an introductory discussion on some of the concepts behind Node.js and some of the potential benefits it offers for certain solutions in certain environments. I highly recommend reading that first before reading what follows if you are not yet acquainted with Node.js. Express is even mentioned a bit in there as well.

Express is a web-application framework just like Django, CodeIgniter, or Laravel. The only difference is that instead of running on something like Apache, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. There are other web application frameworks that run on top of Node.js (like Hapi) but Express is one of the more popular ones.

Below is a link to what we will be building in this section…

Demo Files

Express, like other Node.js installations, comes in the form of a module. You can use a utility called “npm” to install it using the command line. To install Express we just have to type the following into our Node.js command line…

$ npm install express

This will download all of the files that Express requires (dependencies) and will place them in a folder called “node_modules”.

Now that we have Express installed we can get started. Create a file named server.js and add the following…

var express = require('express');
var app = express();
app.get('/', function(request, response) {
   response.send("<h1>Our Express App</h1>");
});
app.listen(8124);

Then open up your favorite terminal (like BASH) and type the following…

$ node server.js

If you open a browser and type in http://127.0.0.1:8124/ you should see the text appear. The great thing about Express is that right out-of-the-box we can use it to define some routes and build an entire web application. If you have used Lavavel or the Slim PHP Framework or something similar this might look familiar. We can also define routes for the other HTTP verbs: POST, PUT, and DELETE. We can return HTML or we can use it to create an API that returns XML or JSON. The possibilities for what we can do with it are all there.

Read More »

Share Tweet Reccomend

A Node.js Primer

Moving into the second decade of the 21st century, if you have been immersed in the web development community — and more specifically, the JavaScript community — in any capacity, then you likely remember hearing something about Node.js discussed somewhere. Maybe you already know all about it, maybe you know a little, or maybe you’re not yet familiar with it. In what follows, we’re going to take a brief look at some of the components of Node.js, what it is, and why people have gotten excited about it.

Node.js Introduction

What is Node.js? Before we get into that, let’s back up a minute and start by talking about web servers. You know about web servers, right? They’re computers that have software running on them that are able to respond to HTTP requests from clients (which most of the time means browsers like Chrome, Firefox, Safari, and Internet Explorer… either desktop or mobile). They’re written in languages like Perl, C, and C++. Then they have other code like Python or PHP that runs on top of them so that when a client connects to a server, all the code runs, works it’s magic (hopefully in a semi-functional way) and returns a web page of HTML to the browser… or if the endpoint is a web service: XML or a JSON payload. This is a pretty standard interaction that occurs billions of times each day across the world. If you do anything on the Internet, you participate in this process most often without even thinking about what is going on behind the scenes in the client-server interaction.

So where does Node.js come into the picture? Basically Node.js is an implementation where, instead of responding to HTTP requests, processing them, and returning web pages using the aforementioned languages, you use JavaScript instead! Node.js becomes a web server written in JavaScript. And it doesn’t just stop there. You can also run Node.js right in your own desktop environment and use utilities to perform file processes and other tasks just as you could do if you were using an installed application that was written in Java or something else. So Node.js could perhaps be better described as “JavaScript running outside of the browser.” Local applications are definitely a very useful component of Node.js, but we’re going to specifically focus on the aspect of using Node.js as a web server. But I’d definitely recommend looking at a number of different utilities available for installation to see if you can use Node.js in your development processes or just as something that makes your life easier in some way.

Read More »

Share Tweet Reccomend

JavaScript Modules

When programming with more advanced implementations of JavaScript, such as projects using Backbone.js, Node.js, RequireJS, or often some sort of combination of these, you will inevitably come across discussion about the concept of JavaScript modules. Modules are small pieces of decoupled code — code containing no or very few dependencies — that exist as standalone components. These modules can be used by an application to solve a particular problem. The use of modules is not a requirement to create JavaScript applications. They’re just a way of organizing code to solve common problems that arise when creating applications. In that sense, modules can be thought of as a “design pattern.” There may be cases where you want to use the module pattern in combination with other design patterns. Or, there may be where you’d want to use a different design pattern altogether. It all depends on the nature of the app you are building.

That being said, the use of modules can be a very flexible and commonly used pattern for many different types applications — from games, to web apps, to script loaders, to just about everything else. So it is definitely something worth knowing if you’re in the business of creating large-scale JavaScript applications.

So let’s take a look at a module in native JavaScript…

var moduleNamespace = (function () {
    var privateVariable;
    var privateMethod;
    privateVariable = 0;
    privateMethod = function( foo ) {
        console.log( foo );
    };
    return {
        publicVariable: "foo", 
        publicFunction: function( bar ) {
            privateVariable++;
            privateMethod(bar);
        }
    };
})();

In the code above we have a variable named “moduleNamespace” that is assigned to an anonymous Immediately-invoked Function Expression (IIFE) — also sometimes refereed to as a self-executing function. It’s basically a function that will automatically run in your application when it’s declared. The end result is that there’s no need to write moduleNameSpace(); elsewhere in our program.

Read More »

Share Tweet Reccomend

Concatenate and Compress JavaScript with UglifyJS

The benefits of using something like RequireJS to asynchronously to load your project’s JavaScript was discussed previously. However, if you wish to load JavaScript in the more conventional way (that is, just sticking a script tag or tags in the browser) there are quick and lightweight ways to make this an efficient and viable option as well. These methods involve concatenating and compressing (minifying) your JavaScript files into one script file. At the end of the process you’ll only need to end up loading this one large script file (which is a lot quicker than loading numerous smaller scripts file) Additionally, if you concatenate your JavaScript files in a particular sequential order, you can easily make this a way to manage your dependencies… you just need to make sure that you load the dependency libraries before you load the libraries that require them. The tools we will look at in what follows makes this a fairly simple process.

To accomplish this in my workflow I use something called UglifyJS. It’s a simple package that runs in a Node.js environment. Node.js is a platform that allows you to run JavaScript system level applications on a server environment (or in this case, on our local machine). We can open our terminal and type something like “node myJavaScriptFile.js” and run some JavaScript we have written to do all kinds of neat stuff… all outside of the browser. So first things first, go and download and install Node.js if you haven’t already.

After that navigate to the directory where node is installed and run…

npm install uglify-js -g

nmp (which stands for Node Package Manager, is a way of quickly installing the latest version of Node applications). You may have seen this elsewhere with Python’s pip command or Ruby’s gems. The -g parameter stands for global, which will enable you to run UglifyJS from anywhere on your machine.

Now what you can do is simply run the command according to the following format in the directory where your JavaScript files are…

uglifyjs -o scripts.js javascript-file1.js javascript-file2.js javascript-file3.js

In the example above, javascript-file1.js, javascript-file2.js, and javascript-file3.js will all be concatenated and compressed into a file named scripts.js file in the order in which they were set. So following this convention, you can load your dependencies where they are important in your JavaScript projects. Backbone.js, for example, has a hard dependency on Underscore. So you’d want to add Underscore *before* you’d add Backbone if you were doing a Backbone project. Also, a lot of times developers like to have jQuery available to them in their Backbone models, collections and views. So we could add jQuery into our list of files as well resulting in something like the following…

uglifyjs -o scripts.js underscore.js jQuery.js backbone.js

** Note that all of these files (underscore.js, jQuery.js, backbone.js) have to exist within the directory that you’re running the command from. scripts.js will be created if it doesn’t exist and overwritten if it does.

But whatever JavaScript you decide you need to include, all you have to do once the UglifyJS build process is complete is load the scripts.js file in your HTML. You can name this file whatever you want (it doesn’t have to be scripts.js). What I usually do in my workflow is set up a .bat file (and call it build-js.bat or something) that has all of my files and their dependencies set in the order that I need them. Then when I need to deploy my JavaScript to production I just run the .bat file.

So whichever way you choose to do it (either using the asynchronous module definition (AMD) pattern using something like RequireJS or using a tool like UglifyJS or using another similar solution) there are definitely good ways to load your handle your project’s JavaScript JavaScript in an efficient and effective manner.