gpt4 book ai didi

javascript - Node.js 将参数传递给express.js/passport.js 中的 require 函数?明白为什么吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:52 24 4
gpt4 key购买 nike

大家好,我需要一些帮助来理解 node.js 语法。应用程序已将参数放在需要另一个文件(而不是模块)的路径的 require 函数上。让我给你一个我正在讨论的语法示例,该语法位于名为 server.js 的主 javascript 文件中。

require('./config/passport')(passport);

require('./app/routes.js')(app, passport);

我需要知道为什么这些“app”和“passport”参数被传递给我的 require 函数。 app是express,passport是 Passport 模块。

完整的相关文件如下。干杯

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
require('./app/models/user');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var configDB = require('./config/database.js');

mongoose.connect(configDB.url);

require('./config/passport')(passport);

app.use(morgan('dev')); //http request logger
app.use(cookieParser()); //reads cookies (needed for authentication)
app.use(bodyParser()); //gets information from html forms

app.set('view engine', 'ejs');

//required for passport
app.use(session({secret: 'jonathanisawesome'}));
app.use(passport.initialize());
app.use(passport.session()); //persistent login sessions
app.use(flash()); //connect-flash for flash messages stored in sessions


//routes
require('./app/routes.js')(app, passport); //loads our routes and passes in our app and fully configured passport

app.listen(port);
console.log('the magix happens on port ' + port);

app.get('/logout', function(req,res){
req.logout();
res.redirect('/');
});




//processing of the form
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash : true
}));



app.post('/signup', passport.authenticate('local-signup', {

successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash : true
}));


// route for facebook authentication and login
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/profile',
failureRedirect : '/'
}));

app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

// the callback after google has authenticated the user
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile',
failureRedirect : '/'
}));




};



//route middleware to make sure a user is logged in
function isLoggedIn(req,res,next){
//if user is authenticated in the session, carry on
if(req.isAuthenticated())
return next();

//if they are not, redirect them to the homepage
res.redirect('/');
};

var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('mongoose').model('User');
var configAuth = require('./auth');
var crypto = require('crypto');
module.exports = function(passport){
//passport session setup
//persistent login sessions
//passport needs ability to serialize and unserialize users out of sessions


//use to serialize the user for the session
passport.serializeUser(function(user,done){
done(null, user.id);
});


//deserialize user
passport.deserializeUser(function(id,done){
User.findById(id, function(err, user){
done(err, user);
});
});

//local signup
//using named strategies one for login and one for signup
//by default if there was no name it would be called 'local'

passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {

// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {


// create the user
var newUser = new User();

// set the user's local credentials
newUser.email = email;
newUser.password = password; //password is hashed on the model layer

// save the user
newUser.save(function(err,user) {
if(err || !user){

//error handling

if(err.code===11000){ //email taken
return done(null, false, req.flash('signupMessage', 'Sorry, the email '+newUser.email+' has been taken'));
}else{ //its a hacker
return done(null, false, req.flash('signupMessage', JSON.stringify(err)));

}

}else{
return done(null, newUser);
}
});


});

}));

passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form

// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);

// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

// if the user is found but the password is wrong
if (!user.authenticate(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

// all is well, return successful user
return done(null, user);
});

}));


//facebook
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
User.findOne({'facebook.id': profile.id}, function(err, user){
if(err)
return done(err);
if(user)
return done(null, user);
else {
var newUser = new User();
newUser.email = profile.emails[0].value;
newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
newUser.socialLogin.facebook.id = profile.id;
newUser.socialLogin.facebook.token = accessToken;
newUser.socialLogin.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.socialLogin.facebook.email = profile.emails[0].value;

newUser.save(function(err){
if(err) console.log(err)

return done(null, newUser);
})
console.log(profile);
}
});
});
}

));


passport.use(new GoogleStrategy({

clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL,

},
function(token, refreshToken, profile, done) {

// make the code asynchronous
// User.findOne won't fire until we have all our data back from Google
process.nextTick(function() {

// try to find the user based on their google id
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);

if (user) {

// if a user is found, log them in
return done(null, user);
} else {
// if the user isnt in our database, create a new user
var newUser = new User();
newUser.email = profile.emails[0].value;
newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
newUser.socialLogin.google.id = profile.id;
newUser.socialLogin.google.token = token;
newUser.socialLogin.google.name = profile.displayName;
newUser.socialLogin.google.email = profile.emails[0].value; // pull the first email

// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});

}));



};

最佳答案

这个:

require('./config/passport')(passport);

大致相当于:

var pp = require('./config/passport');
pp(passport);

解释一下,require('./config/passport') 返回一个需要一个参数的函数。您可以直接在上面的第一种形式中调用该函数,也可以将其分配给一个变量然后调用它。

关于javascript - Node.js 将参数传递给express.js/passport.js 中的 require 函数?明白为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com