Commit 08b0c7d5 authored by Vadim's avatar Vadim

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

parent b7814c0d
const User = require('../models/User');
const auth = async (req, res, next) => {
const token = req.get("Authorization");
if(!token) {
return res.status(401).send({error: "No token present"});
}
const user = await User.findOne({token});
if (!user) {
return res.status(401).send({error: "Wrong token"});
}
req.user = user;
next();
};
module.exports = auth;
\ No newline at end of file
......@@ -10,6 +10,17 @@ const UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true,
validate: {
validator: async value => {
const user = await User.findOne({username: value});
if (user) return false;
},
message: 'User is already registered!'
}
},
email: {
type: String,
required: true
},
password: {
......
......@@ -6,6 +6,7 @@ const {nanoid} = require('nanoid');
const config = require('./config');
const Product = require('./models/Products');
const User = require("./models/User");
const auth = require('./middleware/auth');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
......@@ -40,14 +41,7 @@ const createRouter = () => {
}
});
router.post('/', upload.single('image'), async (req, res) => {
const token = req.get("Authorization");
const user = await User.findOne({token});
if (!user) {
return res.status(401).send({error: "Wrong token"});
}
router.post('/', auth, upload.single('image'), async (req, res) => {
const product = new Product(req.body);
if(req.file) {
product.image = req.file.filename;
......
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