我有以下的
我正在尝试让我在
如果用户未登录,请提供注册选项;如果用户已登录,请告知他们已经“登录”。我将函数添加到了
感谢任何帮助。
谢谢!
编辑:index.js
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');
});
};
User.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);
user
设置为模板变量,但尝试使用session.user
访问它。也许只需尝试if(user)
? - loganfsmythsession.user
相同的响应,即user 未定义
。 - germainelol