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'
但是,這似乎並沒有工作..
優秀,謝謝! – gratz