我有以下app.js
代码
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.enable('jsonp callback');
app.set('view engine', 'jade');
app.set('view options', {layout : false});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
secret : 'abcdefg'
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.use(function(req, res, next){
res.locals.user = req.session.user;
next();
})
});
我正在努力做到这一点,以便我.jade
视图中的以下代码可以正常工作
- if(session.user)
div#logoutsection.pull-right
a#logout-btn.btn.btn-info.pull-right.top-bar-form-button(href='logout/') Logout
p#loginprompt.pull-right.login-prompt #{session.user.username} logged In
- else
ul.pull-right
li
a#signup-btn.btn.pull-right.top-bar-form-button(href='#signup-modal', data-toggle="modal") Sign Up
因此,如果他们未登录,请提供注册选项,如果他们已登录,请告诉他们“已登录”。我在代码末尾添加了函数,app.configure
就像它使用之前一样,dynamicHelpers()
我被告知这cookieParser()
是要走的路,但是我将如何编码,以便我可以检查我的用户是否已登录并提供他们的用户名我想在上面吗?
任何帮助表示赞赏。
谢谢!
编辑:index.js
'use strict'
var util = require('util');
var Logger = require('devnull');
var logger = new Logger({namespacing : 0});
var User = require('../schemas/User');
var Post = require('../schemas/Post');
/**
* Get Meta information about all the Post's
*/
var getAllMeta = function(req, res, next){
Post.getAllMeta(function(err, postsList){
if(!err && postsList){
req.postsList = postsList;
}
next(err);
});
};
/**
* validate the signup credentials entered by the user
* @param {String} username
* @param {String} pass1 : first password
* @param {String} pass2 : verification password
*/
var validateUserData = function(username, pass1, pass2){
if(pass1.trim() !== pass2.trim()){
util.log('Passwords not Matching ' + pass1 + ' ' + pass2);
return 'Passwords not Matching';
}
return '';
//put any other validations here
};
/*
* GET home page.
*/
module.exports = function(app){
/**
* Map the URL '/' to the callback
*/
app.get('/', function(req, res){
logger.log('Serving request for url [GET]' + req.route.path)
Post.getAll(function(err, allPosts){
if(!err && allPosts){
res.render('index', {'allPosts' : allPosts});
}else{
util.log('Error fetching posts from database : ' + err);
res.render('error');
}
});
});
/**
* Map the URL '/login' to the callback
*/
app.post('/login', function(req, res){
logger.log('Serving request for url [POST] ' + req.route.path);
var username = req.body.User;
var password = req.body.Password;
User.validateUser(username, password, function(err, user){
if(err && !user){
res.json({
retStatus : 'failure'
});
}else{
console.log(user);
req.session.user = user;
res.json({
retStatus : 'success',
user : user ,
});
}
});
});
/**
* Logout the current user and clear the session
*/
app.get('/logout', function(req, res){
logger.log('Serving request for url [GET] ' + req.route.path);
req.session.user = undefined;
res.redirect('/');
});
/**
* Add a new User to database
*/
app.post('/signup', function(req, res){
util.log('Serving request for url [POST] ' + req.route.path);
var signupForm = req.body.signupForm;
var username = signupForm.username;
var pass1 = signupForm.pass1;
var pass2 = signupForm.pass2;
var validateMsg = validateUserData(username, pass1, pass2);
if(validateMsg !== ''){
res.json({
'retStatus' : 'failure',
'message' : validateMsg
});
}else{
var newUser = new User();
newUser.username = username;
newUser.password = pass1;
newUser.save(function(err, savedUser){
var message = '';
var retStatus = '';
if(!err){
util.log('Successfully created new user with Username : ' + username);
message = 'Successfully created new user : ' + username;
retStatus = 'success';
req.session.user = savedUser;
}else{
util.log('Error while creating user : ' + username + ' error : ' + util.inspect(err));
if(err.code === 11000){
message = "User already exists";
}
retStatus = 'failure';
}
res.json({
'retStatus' : retStatus,
'message' : message
});
});
}
});
app.get('/admin', getAllMeta, function(req, res){
util.log('Serving request for url [GET] ' + req.route.path);
if(req.session.user){
res.render('post', {'postsList' : req.postsList});
}else{
res.redirect('/');
}
});
/**
* Save the post to database
*/
app.post('/admin/save/post', function(req, res){
var postContent = req.body.postContent;
if(postContent.postKey === '' || postContent.postKey === undefined){
var post = new Post();
post.subject = postContent.postSubject;
post.content = postContent.postContent;
post.author = req.session.user.username;
post.tags = postContent.postTags;
post.save(function(err, response){
if(!err && response){
util.log('Successfully saved Post with id : ' + response.id);
res.json({
'retStatus' : 'success',
'data' : response
})
}else{
util.log('Error saving the Post : ' + err);
res.json({
'retStatus' : 'failure',
'error' : err
});
}
});
}else{
var conditions = {'key' : postContent.postKey};
var update = {
'subject' : postContent.postSubject,
'content' : postContent.postContent,
'tags' : postContent.postTags
};
Post.update(conditions, update, null, function(err, numAffected){
if(!err && numAffected){
util.log('Successfully updated the Post with id : ' + postContent.postKey);
res.json({
'retStatus' : 'success',
'numAffected' : numAffected
});
}else{
util.log('Error updating the Post with id : ' + postContent.postKey + ' ' + err);
res.json({
'retStatus' : 'failure'
});
}
});
}
});
app.get('/post/show/:key', function(req, res){
Post.findByKey(req.params.key, function(err, postData){
if(!err && postData){
postData = postData[0];
res.json({
'retStatus' : 'success',
'postData' : postData
});
}else{
util.log('Error in fetching Post by key : ' + req.params.key);
res.json({
'retStatuts' : 'failure',
'msg' : 'Error in fetching Post by key ' + req.params.key
});
}
});
});
app.post('/admin/save/', function(req, res){
//container for saving a post
});
app.get('/admin/remove/:key', function(req, res){
//container for deleting a post
});
app.get('/contact', function(req, res){
util.log('Serving request for url[GET] ' + req.route.path);
res.render('contact');
});
};
用户.js
'use strict'
var util = require('util');
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var validatePresenceOf = function(value){
return value && value.length;
};
var toLower = function(string){
return string.toLowerCase();
};
var User = new Schema({
'username' : { type : String,
validate : [validatePresenceOf, 'a Username is required'],
set : toLower,
index : { unique : true }
},
'password' : String,
});
User.statics.findUser = function(username, password, cb){
return this.find({'username' : username}, cb);
};
User.statics.validateUser = function(username, password, cb){
this.find({'username' : username}, function(err, response){
var user = response[0];
if(!user || response.length === 0){
cb(new Error('AuthFailed : Username does not exist'));
}else{
if(password == user.password){
util.log('Authenticated User ' + username);
cb(null, user);
}else{
cb(new Error('AuthFailed : Invalid Password'));
}
}
});
};
module.exports = mongoose.model('User' , User);