我是NodejS的新手,并尝试将PassportJS应用到我使用postgresql作为数据存储区的现有rest api中。
我的代码基于本教程:http://mherman.org/blog/2016/03/13/designing-a-restful-api-with-node-and-postgres/#.WMBV9BLhBR1
我的app.js看起来像这样:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var log4js = require('log4js');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var app = express();
//For logging
var httpLogFormat = ':remote-addr - - [:date] ":method :url ' + 'HTTP/:http-version" :status :res[content-length] ' + '":referrer" ":user-agent" :response-time';
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/access.log'), 'access');
var logger = log4js.getLogger('access');
app.use(log4js.connectLogger(logger, { level: 'auto', format: httpLogFormat }));
//Passport security
app.use(passport.initialize());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//For CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "https://example.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, DELETE");
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
var callerIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
logger.debug("development message");
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
var callerIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
logger.debug("production message");
});
module.exports = app;
在我的queries.js中,我尝试执行以下操作:
function getAllUsers(req, res, next) {
db.any('select * from users')
.then(function (data) {
res.status(200)
.json({
users: data
});
})
.catch(function (err) {
return next(err);
});
}
passport.use(new LocalStrategy(options, (username, password, done) => {
db.one('select * from users where id = $1', username)
.then(function (data) {
if(!data){
return done(null, user);
}else{
//Generete a jwt token and return it.
}
})
.catch((err) => { return done(err); });
});
我的问题是:
我是否在app.js中正确实施了护照? 我的queries.js中的代码也在编译时崩溃,我面临的问题之一是如何在现有查询周围使用护照功能,例如现有的getAllUsers函数和失败的函数我尝试在尝试时查找用户名登录。
我的路线放在index.js文件中:
router.get('/api/users', db.getAllUsers);
router.get('/api/user/:id', db.getSingleUser);
router.post('/api/users', db.createUser);
router.delete('/api/user/:id', db.deleteUser);
如何将它们封装在护照方法中,以便只有在调用它们的用户有效时才能调用它们中的一些?