Commit ac05badd authored by Vadim's avatar Vadim

конец занятия №89

parent 978516a0
......@@ -5,7 +5,7 @@ let client = null;
const connect = async () => {
client = await MongoClient.connect("mongodb://localhost");
client = await MongoClient.connect("mongodb://localhost", { useNewUrlParser: true });
db = client.db('shop')
};
......
const permit = (...roles) => {
return (req, res, next) => {
if(!req.user) {
return res.status(401).send({message: "Unauthenticated"});
}
if(!roles.includes(req.user.role)) {
return res.status(403).send({message: "Unauthorized"});
}
next();
}
};
module.exports = permit;
\ No newline at end of file
......@@ -30,6 +30,12 @@ const UserSchema = new Schema({
token: {
type: String,
required: true
},
role: {
type: String,
required: true,
enum: ['user', 'admin'],
default: 'user'
}
});
......
......@@ -7,6 +7,7 @@ const config = require('./config');
const Product = require('./models/Products');
const User = require("./models/User");
const auth = require('./middleware/auth');
const permit = require('./middleware/permit');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
......@@ -41,12 +42,12 @@ const createRouter = () => {
}
});
router.post('/', auth, upload.single('image'), async (req, res) => {
router.post('/', [auth, permit('admin'), upload.single('image')], async (req, res) => {
const product = new Product(req.body);
if(req.file) {
product.image = req.file.filename;
}
product.user = user._id;
product.user = req.user._id;
try {
await product.save();
res.send(product);
......
......@@ -10,7 +10,11 @@ const createRouter = () => {
});
router.post("/", async (req, res) => {
try {
const user = new User(req.body);
const user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.generateToken();
await user.save();
res.send(user);
......
......@@ -41,11 +41,13 @@ db.once('open', async () => {
username: 'admin',
email: 'admin@admin.com',
password: '123456',
role: 'admin',
token: nanoid()
}, {
username: 'user',
email: 'user@user.com',
password: '123456',
role: 'user',
token: nanoid()
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment