Fixing Up Passport.js ‘passport-http’ for Express v4

Even though it isn’t in the primary trunk of code for the ‘passport-http’ Passport.js Strategy, I’ve upgraded the packages.json and app.js file for the basic username and passport authentication to Express.js v4. If you’re using Express.js and are looking to migrate to v4 from v3 or earlier a great starting place is to check out the “Migrating from 3.x to 4.x” wiki page. As for the passport-http strategy, here’s the updated example I put together in a commit here with my own fork here, with the code changes below.

First step was to bump to the latest Express.js v4 Module. I did this with a simple edit to the packages.json file. The original looked like this

[sourcecode language=”javascript”]
{
"name": "passport-http-examples-basic",
"version": "0.0.0",
"dependencies": {
"express": ">= 0.0.0",
"passport": ">= 0.0.0",
"passport-http": ">= 0.0.0"
}
}
[/sourcecode]

which I changed the depedency from >= 0.0.0 to >= 4.0.0 so that it would require something above v4.

[sourcecode language=”javascript”]
{
"name": "passport-http-examples-basic",
"version": "0.0.0",
"dependencies": {
"express": ">= 4.0.0",
"passport": ">= 0.0.0",
"passport-http": ">= 0.0.0"
}
}
[/sourcecode]

Technically the old file would have pulled the latest (which as of today I believe is 4.1.1) but it would also not do anything if you’d already pulled the example down. It just make sit more specific that the version is v4+ now.

After changing that dependency I added Morgan. Morgan is a replacement middleware for the logger. The final packages.json file looked like this when I was done.

[sourcecode language=”javascript”]
{
"name": "passport-http-examples-basic",
"version": "0.0.0",
"dependencies": {
"express": ">= 4.0.0",
"passport": ">= 0.0.0",
"passport-http": ">= 0.0.0",
"morgan": "~1.0.0"
}
}
[/sourcecode]

Once that was done I nuked my node_modules directory and ran npm install to pull down the latest bits. Once I did that, starting with the app.js I made a few changes. Below is what the app.js file looked like when I started with.

[sourcecode language=”javascript”]
var express = require(‘express’)
, passport = require(‘passport’)
, util = require(‘util’)
, BasicStrategy = require(‘passport-http’).BasicStrategy;

var users = [
{ id: 1, username: ‘bob’, password: ‘secret’, email: ‘bob@example.com’ }
, { id: 2, username: ‘joe’, password: ‘birthday’, email: ‘joe@example.com’ }
];

function findByUsername(username, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username) {
return fn(null, user);
}
}
return fn(null, null);
}

// Use the BasicStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new BasicStrategy({
},
function(username, password, done) {
// asynchronous verification, for effect…
process.nextTick(function () {

// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure. Otherwise, return the authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.password != password) { return done(null, false); }
return done(null, user);
})
});
}
));

var app = express.createServer();

// configure Express
app.configure(function() {
app.use(express.logger());
// Initialize Passport! Note: no need to use session middleware when each
// request carries authentication credentials, as is the case with HTTP Basic.
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(__dirname + ‘/public’));
});

// curl -v -I http://127.0.0.1:3000/
// curl -v -I –user bob:secret http://127.0.0.1:3000/
app.get(‘/’,
// Authenticate using HTTP Basic credentials, with session support disabled.
passport.authenticate(‘basic’, { session: false }),
function(req, res){
res.json({ username: req.user.username, email: req.user.email });
});

app.listen(3000);
[/sourcecode]

First changes, add some requires, remove some requires.

[sourcecode language=”javascript”]
var express = require(‘express’)
, passport = require(‘passport’)
, util = require(‘util’)
, BasicStrategy = require(‘passport-http’).BasicStrategy;
[/sourcecode]

and changed it to

[sourcecode language=”javascript”]
var express = require(‘express’)
, passport = require(‘passport’)
, util = require(‘util’)
, BasicStrategy = require(‘passport-http’).BasicStrategy
, morgan = require(‘morgan’)
, app = express();
[/sourcecode]

Then I deleted the entire section shown below.

[sourcecode language=”javascript”]
var app = express.createServer();

// configure Express
app.configure(function() {
app.use(express.logger());
// Initialize Passport! Note: no need to use session middleware when each
// request carries authentication credentials, as is the case with HTTP Basic.
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(__dirname + ‘/public’));
});
[/sourcecode]

I replace that with a nicely cleaned up Express.js v4 section of code and the replacement for logger, the morgan() library. Initializing passport however is still done in the same ole’ trusty way with initialize().

[sourcecode language=”javascript”]
app.use(morgan());
app.use(passport.initialize());
[/sourcecode]

Ordering of code has changed a bit for express.js, which meant I needed to have the app.use commands before the following section, which I moved right up underneath the two app.use statements.

[sourcecode language=”javascript”]
// curl -v -I http://127.0.0.1:3000/
// curl -v -I –user bob:secret http://127.0.0.1:3000/
app.get(‘/’,
// Authenticate using HTTP Basic credentials, with session support disabled.
passport.authenticate(‘basic’, { session: false }),
function(req, res){
res.json({ username: req.user.username, email: req.user.email });
});
[/sourcecode]

Finished app.js File

After those changes the app.js file should look like this.

[sourcecode language=”javascript”]
var express = require(‘express’)
, passport = require(‘passport’)
, util = require(‘util’)
, BasicStrategy = require(‘passport-http’).BasicStrategy
, morgan = require(‘morgan’)
, app = express();

app.use(morgan());
app.use(passport.initialize());

// curl -v -I http://127.0.0.1:3000/
// curl -v -I –user bob:secret http://127.0.0.1:3000/
app.get(‘/’,
// Authenticate using HTTP Basic credentials, with session support disabled.
passport.authenticate(‘basic’, { session: false }),
function(req, res){
res.json({ username: req.user.username, email: req.user.email });
});

var users = [
{ id: 1, username: ‘bob’, password: ‘secret’, email: ‘bob@example.com’ }
, { id: 2, username: ‘joe’, password: ‘birthday’, email: ‘joe@example.com’ }
];

function findByUsername(username, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username) {
return fn(null, user);
}
}
return fn(null, null);
}

// Use the BasicStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new BasicStrategy({
},
function(username, password, done) {
// asynchronous verification, for effect…
process.nextTick(function () {

// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure. Otherwise, return the authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.password != password) { return done(null, false); }
return done(null, user);
})
});
}
));

app.listen(3000);
[/sourcecode]

If you execute either of the curl commands shown in the comments in the app.js code you should see the respective response when running the application.

[sourcecode language=”bash”]
curl -v -I http://127.0.0.1:3000/
curl -v -I –user bob:secret http://127.0.0.1:3000/
[/sourcecode]

…and that should get you running with Passport.js and Express.js v4.

Configuring Node.js Web Applications… Manually || Convict.js

There’s more than a few ways to configure node.js applications. I’ll discuss a few of them in this blog entry, so without mincing work, to configuring apps!

Solution #1: Build Your Own Configuration

Often this is a super easy solution when an application just needs a single simple configuration. Here’s an example I found that’s pretty clean that Noli posted on Stackoverflow to the question “How to store Node.js deployment settings/configuration files?“.

[sourcecode language=”javascript”]
var config = {}

config.twitter = {};
config.redis = {};
config.web = {};

config.default_stuff = [‘red’,’green’,’blue’,’apple’,’yellow’,’orange’,’politics’];
config.twitter.user_name = process.env.TWITTER_USER || ‘username’;
config.twitter.password= process.env.TWITTER_PASSWORD || ‘password’;
config.redis.uri = process.env.DUOSTACK_DB_REDIS;
config.redis.host = ‘hostname’;
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;

module.exports = config;
[/sourcecode]

…then load that in with a require…

[sourcecode language=”javascript”]
var config = require(‘./config’)
[/sourcecode]

The disadvantage is when the application gets a little bigger the configuration can become unwieldy without very specific, strictly enforced guidelines.

Solution #2: Use a Library/Framework Like Convict.js

The use of a library provides some baseline in which to structure configuration. In the case of convict.js it uses a baseline schema that then can be used to extend or override based on configurations needed for alternate environments. A first steps in setting up convict.js for the fueler project looks like this.

Setup a convict.js file:

[sourcecode language=”javascript”]
var convict = require(‘convict’);

// Schema
var conf = convict({
env: {
doc: "The App Environment.",
format: ["production", "development", "test"],
default: "development",
env: "NODE_ENV"
},
port: {
doc: "The port to bind.",
format: "port",
default: 3000,
env: "PORT"
},
database: {
host: {
default: "someplace:cool",
env: "DB_HOST"
}
}
});

// perform validation
conf.validate();

module.exports = conf;
[/sourcecode]

The main two configuration values are the environment and port values. Others will be added as more of the application is put together, but immediately I just wanted something to put in the project to insure it works.

Next get the convict.js library in the project.

[sourcecode language=”bash”]
npm install convict –save
[/sourcecode]

The save gets it put into the package.json file as a dependency. Once this is installed I opened up the app.js file of the project and added a require at the top of the file after the path require and before the express() call.

[sourcecode language=”javascript”]
var path = require(‘path’);
var config = require(‘./config’);

var app = express();
[/sourcecode]

In the app.set line for the port I changed the setting of the port to be the configuration parameter.

[sourcecode language=”javascript”]
app.set(‘port’, process.env.PORT || config.get(‘port’));
[/sourcecode]

Now when I run the application, the port will be derived from the config.js file setting.

Now What Did I Do?

I’ll write more about this in the near future, but for now I’ve run into something not being setup right. I’m still working through various parts of customizing my setup. In the instructions for convict.js, which aren’t very thorough beyond the most basic use, is how to insure that the other environments are setup with *.json files. What I mean by this is…

I’ve setup a directory with three json files. It looks like this.

My Config Directory
My Config Directory

Each of these files (or at least one of the files) I would think, based on the instructions, get loaded and merged into configuration based on the code in my app.js as shown below.

[sourcecode language=”javascript”]
var env = conf.get(‘env’);
conf.loadFile(‘./config/’ + env + ‘.json’);
[/sourcecode]

The order of override for the configuration values starts with the base config.js, then any *.json files override those config.js settings and any environment variables override the *.json set configuration variables. Based on that, unless of course I’ve missed something for this snippet of code, I should be getting the configuration settings from the *.json files.

My config file data looks like this. Since it is using cjson I went ahead and stuck comments in there too.

[sourcecode language=”javascript”]
/**
* Created by adron on 3/14/14.
* Description: Adding test configuration for the project.
*/

{
"port": {
"doc": "The port to bind.",
"format": "port",
"default": 1337,
"env": "PORT"
}
}
[/sourcecode]

Until later, happy coding, I’m going to dive into this and figure out what my issue is. In my next blog entry I’ll be sure to post an update to what the problem is.

Oh, and that fueler project. Feel free to ping me and jump into it.

Building a Node.js + Express.js + Jade CoderWall + Geekl.st Portfolio

If you’re looking for Part 2…

Alright, diving right in. First, get an express.js application setup and install all the dependencies.

Creating the Express.js Web Application

[sourcecode language=”bash”]
$ express codingWall

create : codingWall
create : codingWall/package.json
create : codingWall/app.js
create : codingWall/public
create : codingWall/public/javascripts
create : codingWall/public/images
create : codingWall/public/stylesheets
create : codingWall/public/stylesheets/style.css
create : codingWall/routes
create : codingWall/routes/index.js
create : codingWall/views
create : codingWall/views/layout.jade
create : codingWall/views/index.jade

dont forget to install dependencies:
$ cd codingWall && npm install

$ cd codingWall/
$ npm install
npm http GET https://registry.npmjs.org/express/2.5.8
npm http GET https://registry.npmjs.org/jade
npm http 200 https://registry.npmjs.org/express/2.5.8
npm http GET https://registry.npmjs.org/express/-/express-2.5.8.tgz
npm http 200 https://registry.npmjs.org/jade
npm http 200 https://registry.npmjs.org/express/-/express-2.5.8.tgz
npm http GET https://registry.npmjs.org/mime/1.2.4
npm http GET https://registry.npmjs.org/mkdirp/0.3.0
npm http GET https://registry.npmjs.org/qs
npm http GET https://registry.npmjs.org/connect
npm http GET https://registry.npmjs.org/commander/0.5.2
npm http 200 https://registry.npmjs.org/qs
npm http 200 https://registry.npmjs.org/mkdirp/0.3.0
npm http GET https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mime/1.2.4
npm http GET https://registry.npmjs.org/mime/-/mime-1.2.4.tgz
npm http 200 https://registry.npmjs.org/commander/0.5.2
npm http GET https://registry.npmjs.org/commander/-/commander-0.5.2.tgz
npm http 200 https://registry.npmjs.org/connect
npm http 200 https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mime/-/mime-1.2.4.tgz
npm http 200 https://registry.npmjs.org/commander/-/commander-0.5.2.tgz
npm http GET https://registry.npmjs.org/formidable
npm http 200 https://registry.npmjs.org/formidable
jade@0.26.0 ./node_modules/jade
├── commander@0.5.2
└── mkdirp@0.3.0
express@2.5.8 ./node_modules/express
├── qs@0.4.2
├── mime@1.2.4
├── mkdirp@0.3.0
└── connect@1.8.7
$
[/sourcecode]

Next get a basic app with a message built. This will make sure all the Jade, Express.js and of course Node.js bits are all installed and running.

[sourcecode language=”bash”]
$ node app.js
[/sourcecode]

Build The UI With Jade Templates

At this point you should be able to navigate to http://localhost:3000 in a browser and view the default express.js web app. So now let’s add something relevant to the page. First, I’m just going to stick my name on the page in the index.jade file. My method for editing the file is usually to just use a text editor such as TextMate.

[sourcecode language=”bash”]
$ mate views/index.jade
[/sourcecode]

There isn’t really a whole lot to the file yet. One thing you’ll notice though, is the Jade Templating.

[sourcecode language=”vb”]
h1= title
p Welcome to #{title}
[/sourcecode]

This might seem strange at first, but here’s an example of the HTML mess we normally see and then the same thing cleaned up. So here’s the some HTML goo…

[sourcecode language=”html”]
<header id="header" class="container">
<div id="socialLinks" class="span-24">
<ul class="right">
<li>Follow us:</li>
<li><a title="Twitter" href="http://www.twitter.com&quot; target="_blank"><img src="images/Twitter_32x32.png" alt="" /></a></li>
<li><a title="Facebook" href="http://www.facebook.com&quot; target="_blank"><img src="images/Facebook_32x32.png" alt="" /></a></li>
</ul>
</div>
<div id="titleContent" class="span-24">
<div id="textLogo">
<a title="GoldMind" href="/">
<span id="companyName">GoldMind</span>
</a>
</div>
<span id="textLogoSubtitle">What do you have to learn?</span></div>
</header>
[/sourcecode]

…and the Jade Template of the same.

[sourcecode language=”vb”]
header.container#header
div.span-24#socialLinks
ul.right
li Follow us:
li
a(href=’http://www.twitter.com&#8217;)
| <img src="images/Twitter_32x32.png" alt="" />
li
a(href=’http://www.facebook.com&#8217;)
| <img src="images/Facebook_32x32.png" alt="" />
div.span-24#titleContent
div#textLogo
a(href=’/’, title=’GoldMind’)
span#companyName GoldMind
span#textLogoSubtitle What do you have to learn?
[/sourcecode]

Much shorter, much cleaner, and lots less noise when one yanks away all the repetitive chevrons. Now that we’ve looked at an example of nasty HTML and clean Jade, let’s step through how to get certain markup with Jade.

The first thing to note is that each tag is indented below the tag it is included within. That’s how things are nested in Jade, and intelligently, no closing tag is needed. But what if you need the id or class added to the tag. That’s also extremely easy. To add the id just add a hash between the tag and the id parameter like this.

[sourcecode language=”vb”]
div#theIdName
[/sourcecode]

For a class added to the tag.

[sourcecode language=”vb”]
div.className
[/sourcecode]

To add both an id and a class.

[sourcecode language=”vb”]
div.className#theIdName
[/sourcecode]

If you open up the layout.jade file you’ll fine some other parts of the Jade Templating I haven’t covered, variables. In the layout.jade file you’ll find the following code.

[sourcecode language=”vb”]
!!!
html
head
title= title
link(rel=’stylesheet’, href=’/stylesheets/style.css’)
body!= body
[/sourcecode]

The title is set to title. Which is actually set in the index.js file. The index.js file has the routing functions that are called from the app.js file that launches the web application. Looking in the index.js file you’ll find the value that is passed in as the title. Change that to something custom for our app example. I changed mine as follows.

[sourcecode language=”javascript”]
exports.index = function(req, res){
res.render(‘index’, { title: "Adron’s Coder Portfolio Site" })
};
[/sourcecode]

Also, to get a little closer to the HTML5 Spec, I changed the layout.jade page as follows.

[sourcecode language=”html”]
doctype 5
html(lang="en")
head
title= title
link(rel=’stylesheet’, href=’/stylesheets/style.css’)
body!= body
[/sourcecode]

With those two changes we should have a custom message that is processed and also HTML5 compliance. Be sure to kill node.js if it is still running and restart it so all the changes are taken into account.

Mashing it Up!

Now it is time to mash this CoderWall & Geekli.st stuff up, but alas, that’s coming in the NEXT blog entry. Stay tuned, I’ll have it up in the morning!

Added: Part 2