Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Express simple authentication example
node_modules
*.swp
var express = require('express');
var port = 8999;
var app = express.createServer();
function checkAuth (req, res, next) {
console.log('checkAuth ' + req.url);
// don't serve /secure to those not logged in
// you should add to this list, for each and every secure url
if (req.url === '/secure' && (!req.session || !req.session.authenticated)) {
res.render('unauthorised', { status: 403 });
return;
}
next();
}
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({ secret: 'example' }));
app.use(express.bodyParser());
app.use(checkAuth);
app.use(app.router);
app.set('view engine', 'jade');
app.set('view options', { layout: false });
});
require('./lib/routes.js')(app);
app.listen(port);
console.log('Node listening on port %s', port);
!!! 5
html(lang='en')
head
title Express authentication example
body
h1 Express authentication example
p Navigate to
ul
li: a(href="/secure") Secure content
li: a(href="/welcome") Welcome page
li: a(href="/logout") Logout
!!! 5
html(lang='en')
head
title Express authentication example
body
h1 Sign-in to this Express authentication example
p Use <i>user</i> for the username and <i>pass</i> for the password.
form(method='post')
p
label(for='username') Username
input(type='text', name='username')
p
label(for='password') Password
input(type='password', name='password')
input(type='submit')
- each message in flash
h4(style="color: red;") #{message}
{
"author": "Scott Mebberson (http://www.scottmebberson.com/)",
"name": "gist-expressauthentication",
"description": "Simple Express authentication example",
"version": "0.0.0",
"homepage": "https://gist.github.com/1581536",
"repository": {
"type": "git",
"url": "git@gist.github.com:1581536.git"
},
"scripts": {
"start": "node app.js"
},
"engines": {
"node": "~0.4.12"
},
"dependencies": {
"express": "2.2.x",
"jade": "0.20.x"
},
"devDependencies": {}
}
var util = require('util');
module.exports = function (app) {
app.get('/', function (req, res, next) {
res.render('index');
});
app.get('/welcome', function (req, res, next) {
res.render('welcome');
});
app.get('/secure', function (req, res, next) {
res.render('secure');
});
app.get('/login', function (req, res, next) {
res.render('login', { flash: req.flash() } );
});
app.post('/login', function (req, res, next) {
// you might like to do a database look-up or something more scalable here
if (req.body.username && req.body.username === 'user' && req.body.password && req.body.password === 'pass') {
req.session.authenticated = true;
res.redirect('/secure');
} else {
req.flash('error', 'Username and password are incorrect');
res.redirect('/login');
}
});
app.get('/logout', function (req, res, next) {
delete req.session.authenticated;
res.redirect('/');
});
};
!!! 5
html(lang='en')
head
title Express authentication example
body
h1 Hi, secure user.
p Navigate to
ul
li: a(href="/secure") Secure content
li: a(href="/welcome") Welcome page
li: a(href="/logout") Logout
!!! 5
html(lang='en')
head
title Express authentication example
body
h1 Unathorised
p You're unathorised to view this page.
p Please <a href="/login">login</a> to continue
!!! 5
html(lang='en')
head
title Express authentication example
body
h1 Welcome
@smebberson

This comment has been minimized.

Copy link
Owner Author

@smebberson smebberson commented Jan 11, 2012

To download

  1. Clone the repository with git clone git://gist.github.com/1581536.git gist-expressauthentication
  2. cd into the directory cd gist-expressauthentication

To run

  1. first install the required dependencies with npm install
  2. then run the example with npm start
  3. then view http://localhost:8999/ in your browser
@ajdrew

This comment has been minimized.

Copy link

@ajdrew ajdrew commented Dec 28, 2015

Just wanted to say that this was really helpful to get my feet wet! Much appreciated!

@jessireedev

This comment has been minimized.

Copy link

@jessireedev jessireedev commented Aug 31, 2016

Thank you. This was very helpful.

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Oct 31, 2016

Thanks so much ^^!

@alecfullofmer

This comment has been minimized.

Copy link

@alecfullofmer alecfullofmer commented Dec 9, 2016

This is great. Thanks so much.

@johnsendaniel8974

This comment has been minimized.

Copy link

@johnsendaniel8974 johnsendaniel8974 commented Jan 5, 2017

Veru useful.

@dgabrahams

This comment has been minimized.

Copy link

@dgabrahams dgabrahams commented Jan 19, 2017

Thanks! Really useful, one thing - req.body.username and req.body.password are checked twice in the same line:
req.body.username && req.body.username === 'user'
Is this intended?

@guumo

This comment has been minimized.

Copy link

@guumo guumo commented Mar 7, 2017

Thanks! another thing:

var util = require('util');

It's not necessary, right?

@roccomuso

This comment has been minimized.

Copy link

@roccomuso roccomuso commented Mar 13, 2017

@guumo right.

@BearJS

This comment has been minimized.

Copy link

@BearJS BearJS commented Mar 30, 2017

Excellent. Just what I needed

@dagoss

This comment has been minimized.

Copy link

@dagoss dagoss commented May 5, 2017

Why do you check req.body.username && req.body.username === 'user' (same with password)? Is there any reason to that instead of just checking req.body.username ==='user'? If username doesn't existing, wouldn't it fail anyway?

@ggalihpp

This comment has been minimized.

Copy link

@ggalihpp ggalihpp commented Sep 25, 2017

I can't run it...
"TypeError: mime.lookup i not a function"
why is that?

@clucas3991

This comment has been minimized.

Copy link

@clucas3991 clucas3991 commented Sep 28, 2017

@ggalihpp I had the same issue. I fixed by: npm install mime@^1
@smebberson: Great project!

@Holle-K

This comment has been minimized.

Copy link

@Holle-K Holle-K commented Nov 19, 2017

Perfect! DANKE!
I changed line 12 in app.js from
req.url === '/secure'
to
req.url.indexOf("/secure")===0

Now every request inside /secure ( '/secure/foo' or '/secure/johndoe') requires authentication without the need to add additional urls to the list in the checkAuth-function

@mertd

This comment has been minimized.

Copy link

@mertd mertd commented Dec 7, 2017

@dgabrahams, @dagoss: Imagine req.body.username was undefined. If you accessed the variable's value without checking whether it is truthy, you would be confronted with an exception.

@Nedson202

This comment has been minimized.

Copy link

@Nedson202 Nedson202 commented Mar 4, 2018

is the use of next in (req, res, next) necessary as next is reserved for middlewares

@smhk

This comment has been minimized.

Copy link

@smhk smhk commented Jun 26, 2019

This is fantastic!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment