2014-02-19 56 views
0

道歉它是用coffeescript(不是純js)編寫的。 我一直在看passport.js,並試圖將其包含到一個項目中,這裏是它的一個簡化版本,只是認證的東西。Passport.js本地策略如何確保路線

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' 

這是非常基本的,在本地策略僅僅檢查用戶名是「管理員」,密碼爲「密碼」,但我不知道如何保護「/管理員」和「/設備」路線?我想這樣的事情:

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

但是,這似乎並沒有工作..

回答

3

如果用戶登錄後成功通過驗證,你可以這樣做:

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' 
+0

優秀,謝謝! – gratz

相關問題