Я пытаюсь запустить загруженный Node.Js проект. Я хочу зарегистрировать нового администратора с помощью почтальона с помощью этого JSON почтового запроса {"username" : "admin", "password" : "123", "admin" : "true"}
отправки в точку https://localhost:3443/users/signup
(соответствующие коды находятся внутри файлов users.js
и authenticat.js
). Я могу зарегистрироваться и войти в систему с новым пользователем, но когда я хочу опубликовать ди sh, отправив, например, запрос в точку https://localhost:3443/dishes
(связанный код находится внутри dishrouter.js
), он говорит, что вы не авторизованы. выполнить это действие. Следующие файлы являются связанными файлами проекта:
user. js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
firstname: {
type: String,
default: ''
},
lastname: {
type: String,
default: ''
},
//facebookId: String,
admin: {
type: Boolean,
default: false
}
});
User.plugin(passportLocalMongoose);
module.exports = mon goose .model ('User', User);
пользователей. js:
var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser');
var User = require('../models/user');
var passport = require('passport');
var authenticate = require('../authenticate');
const cors = require('./cors');
router.use(bodyParser.json());
router.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } );
/* GET users listing. */
router.get('/', cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req,res,next) => {
User.find({})
.then((users) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(users);
}, (err) => next(err))
.catch((err) => next(err));
});
router.post('/signup', cors.corsWithOptions, (req, res, next) => {
User.register(new User({username: req.body.username}),
req.body.password, (err, user) => {
if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
if (req.body.firstname)
user.firstname = req.body.firstname;
if (req.body.lastname)
user.lastname = req.body.lastname;
user.save((err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return ;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
});
});
}
});
});
router.post('/login', cors.corsWithOptions, (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err)
return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: info});
}
req.logIn(user, (err) => {
if (err) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: 'Could not log in user!'});
}
var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Login Successful!', token: token});
});
}) (req, res, next);
});
router.get('/logout', cors.corsWithOptions, (req, res) => {
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
router.get('/checkJWTToken', cors.corsWithOptions, (req, res) => {
passport.authenticate('jwt', {session: false}, (err, user, info) => {
if (err)
return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
return res.json({status: 'JWT invalid!', success: false, err: info});
}
else {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
return res.json({status: 'JWT valid!', success: true, user: user});
}
}) (req, res);
});
module.exports = router;
аутентификации. js:
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models/user');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var FacebookTokenStrategy = require('passport-facebook-token');
var config = require('./config.js');
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
console.log("JWT payload: ", jwt_payload);
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));
exports.verifyUser = passport.authenticate('jwt', {session: false});
exports.verifyAdmin = function(req, res, next) {
User.findOne({_id: req.user._id})
.then((user) => {
console.log("User: ", req.user);
if (user.admin) {
next();
}
else {
err = new Error('You are not authorized to perform this operation!');
err.status = 403;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err))
}
config. js:
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl': 'mongodb://localhost:27017/conFusion'
}
тарелка. js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Dishes = require('../models/dishes');
var authenticate = require('../authenticate');
const dishRouter = express.Router();
const cors = require('./cors');
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Dishes.find(req.query)
.populate('comments.author')
.then((dishes) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dishes);
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
Dishes.create(req.body)
.then((dish) => {
console.log('Dish Created ', dish);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
}, (err) => next(err))
.catch((err) => next(err));
})
.put(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
res.statusCode = 403;
res.end('PUT operation not supported on /dishes');
})
.delete(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
Dishes.remove({})
.then((resp) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(resp);
}, (err) => next(err))
.catch((err) => next(err));
});
dishRouter.route('/:dishId')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Dishes.findById(req.params.dishId)
.populate('comments.author')
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
res.statusCode = 403;
res.end('POST operation not supported on /dishes/'+ req.params.dishId);
})
.put(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
Dishes.findByIdAndUpdate(req.params.dishId, {
$set: req.body
}, { new: true })
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
}, (err) => next(err))
.catch((err) => next(err));
})
.delete(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
Dishes.findByIdAndRemove(req.params.dishId)
.then((resp) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(resp);
}, (err) => next(err))
.catch((err) => next(err));
});
dishRouter.route('/:dishId/comments')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Dishes.findById(req.params.dishId)
.populate('comments.author')
.then((dish) => {
if (dish != null) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish.comments);
}
else {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
Dishes.findById(req.params.dishId)
.then((dish) => {
if (dish != null) {
req.body.author = req.user._id;
dish.comments.push(req.body);
dish.save()
.then((dish) => {
Dishes.findById(dish._id)
.populate('comments.author')
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
})
}, (err) => next(err));
}
else {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
.put(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
res.statusCode = 403;
res.end('PUT operation not supported on /dishes/'
+ req.params.dishId + '/comments');
})
.delete(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => {
Dishes.findById(req.params.dishId)
.then((dish) => {
if (dish != null) {
for (var i = (dish.comments.length -1); i >= 0; i--) {
dish.comments.id(dish.comments[i]._id).remove();
}
dish.save()
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
}, (err) => next(err));
}
else {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
});
dishRouter.route('/:dishId/comments/:commentId')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Dishes.findById(req.params.dishId)
.populate('comments.author')
.then((dish) => {
if (dish != null && dish.comments.id(req.params.commentId) != null) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish.comments.id(req.params.commentId));
}
else if (dish == null) {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
else {
err = new Error('Comment ' + req.params.commentId + ' not found');
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
.post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
res.statusCode = 403;
res.end('POST operation not supported on /dishes/'+ req.params.dishId
+ '/comments/' + req.params.commentId);
})
.put(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
Dishes.findById(req.params.dishId)
.then((dish) => {
if (dish != null && dish.comments.id(req.params.commentId) != null
&& dish.comments.id(req.params.commentId).author.equals(req.user._id)) {
if (req.body.rating) {
dish.comments.id(req.params.commentId).rating = req.body.rating;
}
if (req.body.comment) {
dish.comments.id(req.params.commentId).comment = req.body.comment;
}
dish.save()
.then((dish) => {
Dishes.findById(dish._id)
.populate('comments.author')
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
})
}, (err) => next(err));
}
else if (dish == null) {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
else if (dish.comments.id(req.params.commentId) == null) {
err = new Error('Comment ' + req.params.commentId + ' not found');
err.status = 404;
return next(err);
}
else {
err = new Error('you are not authorized to update this comment!');
err.status = 403;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
.delete(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
Dishes.findById(req.params.dishId)
.then((dish) => {
if (dish != null && dish.comments.id(req.params.commentId) != null
&& dish.comments.id(req.params.commentId).author.equals(req.user._id)) {
dish.comments.id(req.params.commentId).remove();
dish.save()
.then((dish) => {
Dishes.findById(dish._id)
.populate('comments.author')
.then((dish) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(dish);
})
}, (err) => next(err));
}
else if (dish == null) {
err = new Error('Dish ' + req.params.dishId + ' not found');
err.status = 404;
return next(err);
}
else if (dish.comments.id(req.params.commentId) == null) {
err = new Error('Comment ' + req.params.commentId + ' not found');
err.status = 404;
return next(err);
}
else {
err = new Error('you are not authorized to delete this comment!');
err.status = 403;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
});
module.exports = dishRouter;