我按照了 Mean Stack 这本书,当我开始this教程与auth进行身份验证时出现问题,我在开始时进行本地身份验证而没有任何社交时刻。
文件夹结构
基本上我将服务器设置为:
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongoose');
var express = require('./config/express');
var db = mongoose();
var app = express();
app.listen(3000);
module.exports = app;
console.log("running at port 3000");
这是./config/mongoose
var config = require('./config');
var mongoose = require('mongoose');
var connectionString = "mongodb://localhost:27017/ShareIdea"
module.exports = function(){
mongoose.Promise = global.Promise;
var db = mongoose.connect(connectionString);
require('../app/models/user.server.model');
return db;
};
所需的user.server模型
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
/*firstname:String,
lastname:String,
email:String,
username:String,
password:String,
userChoice: {type: String, possibleValues: ['programmer','inovator']}*/
});
UserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
mongoose.model('User',UserSchema);
这里是快速配置
var config = require('./config');
var express = require('express');
var passport = require('passport');
var flash = require('connect-flash');
var compress = require('compression');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var methodOverride = require('method-override');
var expressLayouts = require('express-ejs-layouts');
module.exports = function(){
var app = express();
**require('./passport')(passport);**
if(process.env.NODE_ENV === 'development')
{
app.use(morgan('dev'));
}
else if(process.env.NODE_ENV === 'production')
{
app.use(compress());
}
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(session({
saveUninitialized: true,
resave: true,
secret: 'aaaaaaa'
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
app.set('views', './app/views');
app.set('view engine','ejs');
app.use(expressLayouts);
require('../app/routes/index.server.routes.js')(app,passport);
require('../app/routes/register.server.routes.js')(app,passport);
require('../app/routes/login.server.routes.js')(app,passport);
require('../app/routes/profile.server.routes.js')(app,passport);
app.use(express.static('./public'));
return app;
}
这里的快递是出现问题的地方,这一行是目前的主要问题:`要求(' ./ passport')(护照);
如果我把这个代码给了我在标题中提到的问题,如果不是当我用我的表单发表POST请求时它从不发布,我有这个麻烦因为我将我的代码的结构设置为MVC像书一样的结构,并希望将教程中的身份验证调整到我的代码中学习一点,
所以基本上我将护照传递给我的路线:`
注册路线
var register = require('../../app/controllers/register.server.controller');
module.exports = function(app,passport) {
app.route('/register')
.post(function(req,res){
console.log("HY");
passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/register', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})})
.get(register.getPage);
};
注册控制器
var User = require('mongoose').model('User');
module.exports = {
getPage: function(req,res){
res.render('./pages/register',{ message: req.flash('signupMessage') });
}
};
并在此结束是护照代码:
// config/passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../app/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just 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() {
// 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({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
Ps:很抱歉这篇长篇文章,我希望我能得到一个解释,因为我想了解更多,当我读到这本书时,我觉得由autor改编的mvc结构很难,但无论如何非常感谢。< / p>
如果你们不想看这个我理解,这里是gitProject:git project
答案 0 :(得分:0)
在user.server.model.js文件中尝试此操作。而不仅仅是
mongoose.model('User',UserSchema);
请尝试以下方法将其设为可访问。
module.exports = {
User : mongoose.model('User', UserSchema)
}