所以我在这个问题上卡住了很长一段时间,所以我做了一个快速的设置文件,这样就不会有人再被这个垃圾卡住了
passportmgmt.js
const localStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require('./db-schemas/models').UserModel;
/*^^^^^^^^^^^ delete above import and modify below definition as needed
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/database_name");
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true
}
});
const UserModel = mongoose.model('collection_name', UserSchema);
^^^^^^^^^^^^^^^ Change UserModel to User */
const passport = require('passport');
function passportSetupUwU(app) {
const cookieParser = require('cookie-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
secret: "secret",
resave: false,
saveUninitialized: false,
store: new MongoDBStore({
uri: "mongodb://localhost:27017/database_name",
collection: "collection_name"
})
}));
// Passport.js
app.use(passport.initialize());
app.use(passport.session());
}
passport.serializeUser(function(user, cb) {
console.log("serializing user uwu:" + JSON.stringify(user))
process.nextTick(function() {
return cb(null, user.id)
})
})
passport.deserializeUser(function (id, cb) {
console.log("deserializing user owo:" + JSON.stringify(id))
User.findOne({id:id}, function (err, user) {
if (err) { return cb(err)}
return cb(null, user);
})
});
passport.use(new localStrategy(function (username, password, done) {
console.log("attempted login with %s:%s", username, password);
User.findOne({ username: username }, function (err, user) {
if (err) return done(err);
if (!user) return done(null, false, { message: 'No such user exists.' });
bcrypt.compare(password, user.password, function (err, res) {
if (err) return done(err);
if (res === false) return done(null, false, { message: 'Incorrect password.' });
return done(null, user);
});
});
}));
module.exports = {setup: passportSetupUwU}
现在只需导入并在app.js中运行passportSetupUwU函数,你就可以开始了:
app.js exerpt
// some example middleware and stuff i happened to have
const PPSetup = require('./passportmgmt').setup
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
//
// <- PUT IT LIKE HERE OR SOMETHING
//
PPSetup(app);
// some example routes and api endpoints i happened to have
app.use('/api/', apiRouter);
apiRouter.use('/', indexRouter);
apiRouter.use('/users', usersRouter);
apiRouter.post('/login', passport.authenticate('local', {