Search code examples
javascriptcoffeescriptpassport.js

Passport.js local strategy how to secure route


Apologies it's written in coffeescript (not pure js). I've been looking at passport.js and am trying to include it into a project, here's a cut-down version of it with just the auth stuff.

express = require 'express'
passport = require 'passport'
LocalStrategy = require 'passport-local'
.Strategy
BasicStrategy = require 'passport-http'

app = express()
server = require 'http'
.createServer app
server.listen 3000

app.use express.cookieParser()
app.use express.session
  secret: 'abc'
app.use express.json()
app.use express.urlencoded()
app.set 'views', "#{__dirname}/views"
app.set 'view engine', 'jade'
app.locals.pretty = true
app.use passport.initialize()
app.use passport.session()

passport.use new LocalStrategy (username, password, done) ->
  if username is 'admin' and password is 'password'
    return done null, user =
      username: 'admin'
  else
    return done null, false, message: 'Incorrect username / password'

passport.serializeUser (user, done) ->
  done null, user.username

passport.deserializeUser (username, done) ->
  done null, user =
    username: username

app.get '/login', (req, res) ->
  res.render 'login',
    title: 'Login'

app.post '/login', passport.authenticate 'local',
  successRedirect: '/admin'
  failureRedirect: '/login'

app.get '/admin', (req, res) ->
  res.render 'admin',
    title: 'Admin'

app.get '/devices', (req, res) ->
  res.render 'devices',
    title: 'Devices'

It's very basic, in that the local strategy just checks that the username is 'admin' and password is 'password' but I'm not sure how to secure the '/admin' and '/devices' routes? I tried this sort of thing:

app.get '/devices', passport.authenticate('local', {
  failureRedirect: '/login'
}, (req, res) ->
  res.render 'devices',
    title: 'Devices'

But this didn't seem to work..


Solution

  • If users are successfully authenticated after login, you could do something like:

    ensureAuthenticated = (req, res, next) ->
      if req.isAuthenticated() then return next() else res.send 401
    
    app.get "/devices", ensureAuthenticated, (req, res) ->
      res.render 'devices',
      title: 'Devices'