我的路径文件中有一种情况,我需要将实例化的passportjs变量导入到路径中。
const api = express.Router();
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.json({ error: 'user is not logged in', status : 404 });
}
api.route('/signup')
.post(passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})
);
export default api;
我想将主要index.js文件中的护照变量导入到api模块,在那里我可以访问passportjs来执行注册或登录操作。
import passport from 'passport';
import mongoose from 'mongoose';
import api from './routes/api';
app.server = http.createServer(app);
mongoose.connect(db);
// 3rd party middleware
require('./config/passport')(passport);
app.use(compression());
app.use(cors({
exposedHeaders: ['Link']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(logger('dev'));
app.use(cookieParser());
app.use(session({ proxy: true,
resave: true,
saveUninitialized: true,
secret: 's3kr3tk3y'
})
);
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(express.static(__dirname + '/../public'));
//router rules
app.set('views', __dirname + '/../public/views');
app.set('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index');
});
app.use('/api', api);
app.server.listen(port, function () {
console.log(' Application started on port ' + port);
});
export default app;
如何以当前给定的格式实现这一目标?
答案 0 :(得分:0)
我可能会喜欢这个
/** ./routes/api */
...
function apiBuilder(passport){
api.route('/signup')
.post(passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})
);
}
export default apiBuilder;
/** index.js */
import passport from 'passport';
import apiBuilder from './routes/api';
...
app.use('/api', apiBuilder(passport));
一旦您的应用程序变得更复杂,您可能希望进一步将护照库模块化为身份验证模块:
/** ./routes/api */
...
function apiBuilder(auth){
api.route('/signup')
.post(auth.authForSignup);
}
export default apiBuilder;
/** ./path/to/authModule.js */
import passport from 'passport';
...
const auth = {
authForSignup: passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})
// more authentication scenarios can be put here
};
export default auth;
/** index.js */
import auth from './path/to/authModule';
import apiBuilder from './routes/api';
...
app.use('/api', apiBuilder(auth));
我将这种模式用作我的应用的seed,希望这对您有所帮助。