我已经发布了重要的代码片段。没有任何错误。但事实是它显示了所有创建的用户。我希望查看者只显示由注册用户创建的用户。但是如果添加了另一个用户,即使他可以使用其凭据登录,例如:如果A已使用我的代码的注册选项进行了注册,则它会打开一个仪表板,可以选择注销或添加其他用户。添加另一个用户“ B”后,它将我重定向到一个列表,该列表显示了已创建的两个用户。即:A和B。但是现在,如果我注销并使用“ B”凭据登录,它将登录并在视图部分中显示A也和B也创建的所有用户。但是,如果我用A登录,我希望服务器仅显示A所添加的用户。我知道我输入的问题过多,可能会使一半的读者感到困惑,但是我正在尽我最大的努力来解释我的困难
users.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
//Register
router.get('/register', function(req, res){
res.render('register');
});
//Login
router.get('/login', function(req, res){
res.render('login');
});
//register user
router.post('/register', function(req, res){
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
//validation
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is NOT valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords DO NOT match!').equals(req.body.password);
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors: errors
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'You are registered and can now log in!');
res.redirect('/users/login');
}
});
router.post('/addOrEdit', function(req, res){
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
//validation
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is NOT valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords DO NOT match!').equals(req.body.password);
var errors = req.validationErrors();
if(errors){
res.render('addOrEdit',{
errors: errors
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'User created and can now be used for logins!');
res.redirect('/users/list');
}
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login', failureFlash: true}),
function(req, res) {
res.redirect('/');
});
router.get('/addOrEdit', (req, res) => {
res.render("addOrEdit",{
viewTitle: "Insert User"
});
});
router.get('/list', (req, res) => {
User.find((err, docs) => {
if (!err) {
res.render('list', {
list: docs
});
}
else {
console.log('Error in retrieving user list :' + err);
}
});
});
router.post('/list', (req, res) => {
User.find((err, docs) => {
if (!err) {
res.render('list', {
list: docs
});
}
else {
console.log('Error in retrieving user list :' + err);
}
});
});
router.get('/:id', (req, res) => {
User.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("addOrEdit", {
viewTitle: "Update User",
employee: doc
});
}
});
});
router.get('/delete/:id', (req, res) => {
User.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/users/list');
}
else { console.log('Error in user delete :' + err); }
});
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success_msg', 'You Have Logged Out');
res.redirect('/users/login');
});
module.exports = router;
Register.handlebars
<h2 class="page-header">Account Register</h2>
{{#if errors}}
{{#each errors}}
<div class="alert alert-danger">{{msg}}</div>
{{/each}}
{{/if}}
<form method="post" action="/users/register">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>E-mail ID</label>
<input type="text" class="form-control" placeholder="Email" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="text" class="form-control" placeholder=" Re-enter Password" name="password2">
</div>
<button type="submit" class="btn btn-grey">Submit</button>
</form>
addoredit.handlebars
<h3>{{viewTitle}}</h3>
{{#if errors}}
{{#each errors}}
<div class="alert alert-danger">{{msg}}</div>
{{/each}}
{{/if}}
<form action="/users/addOrEdit" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{user._id}}">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>E-mail ID</label>
<input type="text" class="form-control" placeholder="Email" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="text" class="form-control" placeholder="Re-enter Password" name="password2">
</div>
<div class="form-group">
<button type="submit" class="btn btn-info"><i class="fa fa-database"></i> Submit</button>
<a class="btn btn-secondary" href="/users/list"><i class="fa fa-list-alt"></i> View All</a>
</div>
</form>
user.js(schema)
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var db = mongoose.connection;
//User schema
var UserSchema = mongoose.Schema({
username:{
type: String,
index: true
},
password:{
type: String
},
email:{
type: String,
index: true
},
name:{
type: String,
index: true
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
console.log(newUser);
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByUsername= function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.getUserById= function(id, callback){
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
}
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStratergy = require('passport-local').Stratergy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/Experiment-1', { useNewUrlParser: true }, (err)=>{
if (!err) { console.log('MongoDB Connection Succeeded.') }
else { console.log('Error in DB connection : ' + err) }
});
mongoose.set('useCreateIndex', true);
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//init app
var app = express();
//view engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars',exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
//bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session middleware
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport init
app.use(passport.initialize());
app.use(passport.session());
//Express validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//connect flash
app.use(flash());
//global Vars
app.use(function(req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
//set port
app.set('port', (process.env.PORT || 7070));
app.listen(app.get('port'), function(){
console.log('Server started at PORT '+app.get('port'));
});
我正在创建一个注册用户的应用程序,然后让他们登录并查看仪表板。我正在使用快递,蒙古币和护照(用于用户身份验证)。我想要的是,当用户注册并登录后,他可以查看自己创建的其他用户的数据。另外,创建的其他用户也可以登录该页面,然后他可以创建更多用户,该用户只能由他自己查看,而不能由其他任何用户查看。这可能吗?