mongoose + tests

This commit is contained in:
Primakov Alexandr Alexandrovich
2024-10-16 11:06:23 +03:00
parent 2cfcd7347b
commit 4b0d9b4dbc
1295 changed files with 4579 additions and 1719 deletions

View File

@@ -1,147 +1,147 @@
const adminRouter = require('express').Router();
const fs = require('fs');
const path = require('path');
const { TOKEN } = require('../const');
require('dotenv').config();
const adminRouter = require('express').Router()
const fs = require('fs')
const path = require('path')
const { TOKEN } = require('../const')
require('dotenv').config()
const dataFilePath = path.join(__dirname, '../data.json');
let data = require('../data.json');
const dataFilePath = path.join(__dirname, '../data.json')
let data = require('../data.json')
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
const token = req.headers['authorization']
if (token === TOKEN) {
next();
next()
} else {
res.status(403).send({ 'status': 'Failed', 'data': 'Invalid token' });
res.status(403).send({ 'status': 'Failed', 'data': 'Invalid token' })
}
};
}
const saveData = (data) => {
fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf-8');
};
fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf-8')
}
adminRouter.post('/edit/nickname', verifyToken, (req, res) => {
const { name, colored } = req.body;
const { name, colored } = req.body
if (!name || !colored) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Nickname is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Nickname is required' })
}
data.nickname = { name, colored };
saveData(data);
data.nickname = { name, colored }
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Nickname updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Nickname updated successfully' })
})
adminRouter.post('/edit/tech-stack', verifyToken, (req, res) => {
const { techStack } = req.body;
const { techStack } = req.body
if (!techStack || !Array.isArray(techStack)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid tech stack is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid tech stack is required' })
}
data.techStack = techStack;
saveData(data);
data.techStack = techStack
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Tech stack updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Tech stack updated successfully' })
})
adminRouter.post('/edit/city', verifyToken, (req, res) => {
const { city } = req.body;
const { city } = req.body
if (!city) {
return res.status(400).send({ 'status': 'Failed', 'data': 'City is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'City is required' })
}
const isValid = typeof city === 'object' && 'name' in city && 'href' in city;
const isValid = typeof city === 'object' && 'name' in city && 'href' in city
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'City must contain href and name' });
return res.status(400).send({ 'status': 'Failed', 'data': 'City must contain href and name' })
}
data.city = city;
saveData(data);
data.city = city
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'City updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'City updated successfully' })
})
adminRouter.post('/edit/github-repo', verifyToken, (req, res) => {
const { github } = req.body;
const { github } = req.body
if (!github) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Github is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Github is required' })
}
const isValid = typeof github === 'object' && 'author' in github && 'repo' in github;
const isValid = typeof github === 'object' && 'author' in github && 'repo' in github
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Github must contain author and repo' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Github must contain author and repo' })
}
data.githubRepo = github;
saveData(data);
data.githubRepo = github
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Github updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Github updated successfully' })
})
adminRouter.post('/edit/nav-links', verifyToken, (req, res) => {
const { navLinks } = req.body;
const { navLinks } = req.body
if (!navLinks || !Array.isArray(navLinks)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid navLinks are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid navLinks are required' })
}
const isValid = navLinks.every(link =>
link && typeof link === 'object' && 'href' in link && 'title' in link
);
)
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Each navLink must contain href and title' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Each navLink must contain href and title' })
}
data.navLinks = navLinks;
saveData(data);
data.navLinks = navLinks
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Navigation links updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Navigation links updated successfully' })
})
adminRouter.post('/edit/links', verifyToken, (req, res) => {
const { links } = req.body;
const { links } = req.body
if (!links || !Array.isArray(links)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid links are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid links are required' })
}
const isValid = links.every(link =>
link && typeof link === 'object' && 'href' in link && 'title' in link
);
)
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Each link must contain href and title' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Each link must contain href and title' })
}
data.links = links;
saveData(data);
data.links = links
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Links updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Links updated successfully' })
})
adminRouter.post('/edit/projects', verifyToken, (req, res) => {
const { projects } = req.body;
const { projects } = req.body
if (!projects) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Projects are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Projects are required' })
}
const projectFields = ['id', 'title', 'description', 'link', 'techStack', 'image'];
const projectFields = ['id', 'title', 'description', 'link', 'techStack', 'image']
const isValidProject = (project) => {
return projectFields.every(field => field && field in project);
return projectFields.every(field => field && field in project)
}
const allProjectsValid = projects.every(project => isValidProject(project));
const allProjectsValid = projects.every(project => isValidProject(project))
if (!allProjectsValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'All projects must contain ' + projectFields.join(", ") });
return res.status(400).send({ 'status': 'Failed', 'data': 'All projects must contain ' + projectFields.join(", ") })
}
data.projects = projects;
saveData(data);
data.projects = projects
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Projects updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Projects updated successfully' })
})
module.exports = adminRouter;
module.exports = adminRouter

View File

@@ -1,16 +1,16 @@
const authRouter = require('express').Router();
const { TOKEN } = require('../const');
const authRouter = require('express').Router()
const { TOKEN } = require('../const')
module.exports = authRouter;
module.exports = authRouter
authRouter.post('/login', (req, res) => {
const { email, password } = req.body;
console.log(`Login with email=${email} and password=${password}`);
const { email, password } = req.body
console.log(`Login with email=${email} and password=${password}`)
if (email === 'admin@admin.admin' && password === 'admin') {
res.status(200).send({ 'status': 'OK', 'data': `${TOKEN}` });
res.status(200).send({ 'status': 'OK', 'data': `${TOKEN}` })
} else {
res.status(401).send({ 'status': 'Failed!', 'data': 'Invalid email or password' });
res.status(401).send({ 'status': 'Failed!', 'data': 'Invalid email or password' })
}
});
})

View File

@@ -1,3 +1,3 @@
const TOKEN = "ASDFGHJKLLKJHGFDSDFGHJKJHGF";
const TOKEN = "ASDFGHJKLLKJHGFDSDFGHJKJHGF"
module.exports = { TOKEN }

View File

@@ -1,11 +1,11 @@
const authRouter = require('./auth');
const adminRouter = require('./admin');
const rootRouter = require('./root');
const authRouter = require('./auth')
const adminRouter = require('./admin')
const rootRouter = require('./root')
const router = require('express').Router();
const router = require('express').Router()
module.exports = router;
module.exports = router
router.use(`/auth`, authRouter);
router.use(`/admin`, adminRouter);
router.use(`/`, rootRouter);
router.use(`/auth`, authRouter)
router.use(`/admin`, adminRouter)
router.use(`/`, rootRouter)

View File

@@ -1,44 +1,44 @@
const rootRouter = require('express').Router();
const data = require('../data.json');
const rootRouter = require('express').Router()
const data = require('../data.json')
rootRouter.get('/get/nickname', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.nickname });
});
res.status(200).send({ 'status': 'OK', 'data': data.nickname })
})
rootRouter.get('/get/tech-stack', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.techStack });
});
res.status(200).send({ 'status': 'OK', 'data': data.techStack })
})
rootRouter.get('/get/github-repo', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.githubRepo });
});
res.status(200).send({ 'status': 'OK', 'data': data.githubRepo })
})
rootRouter.get('/get/city', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.city });
});
res.status(200).send({ 'status': 'OK', 'data': data.city })
})
rootRouter.get('/get/nav-links', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.navLinks });
});
res.status(200).send({ 'status': 'OK', 'data': data.navLinks })
})
rootRouter.get('/get/links', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.links });
});
res.status(200).send({ 'status': 'OK', 'data': data.links })
})
rootRouter.get('/get/projects', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.projects });
});
res.status(200).send({ 'status': 'OK', 'data': data.projects })
})
rootRouter.get('/get/projects/:id', (req, res) => {
const { id } = req.params;
const project = data.projects.find(p => p.id === id);
const { id } = req.params
const project = data.projects.find(p => p.id === id)
if (project) {
res.status(200).send({ status: 'OK', data: project });
res.status(200).send({ status: 'OK', data: project })
} else {
res.status(404).send({ status: 'NOT_FOUND', message: 'Project not found' });
res.status(404).send({ status: 'NOT_FOUND', message: 'Project not found' })
}
});
})
module.exports = rootRouter;
module.exports = rootRouter

View File

@@ -1,11 +1,9 @@
const express = require('express');
const plantsRouter = require('./plants/getPlants')
const calendarRouter = require('./plants_calendar/index')
const plantsRouter = require('./plants/getPlants');
const calendarRouter = require('./plants_calendar/index');
const router = require('express').Router()
const router = require('express').Router();
module.exports = router;
module.exports = router
router.use('/plants',plantsRouter)
router.use('/plants_calendar',calendarRouter)

View File

@@ -1,6 +1,6 @@
const CONFIG = {
CLIENT_ID: 'kD2JXj1faSCYAWdT4B069wQAx89CZAkXmzTinRvH',
CLIENT_SECRET: 'bJq7Uiwua52tHiLP80N60hALNtQX2wcE4Mj6yNA9OzG2iZbgHuqyeAs6WSWX6MNJdfv0Nqzb7OHta8qPZr4zxWBLTauleaMfraln3xFEvbXLDpi1Lcrwe7DxfgsQQ1E4',
};
}
module.exports = CONFIG;
module.exports = CONFIG

View File

@@ -1,14 +1,14 @@
const express = require ('express');
const axios = require ('axios');
const plantsRouter = express.Router ();
const CONFIG = require ('./config');
const express = require ('express')
const axios = require ('axios')
const plantsRouter = express.Router ()
const CONFIG = require ('./config')
async function getAccessToken () {
const formData = new FormData ();
formData.append ('grant_type', 'client_credentials');
formData.append ('client_id', CONFIG.CLIENT_ID);
formData.append ('client_secret', CONFIG.CLIENT_SECRET);
const formData = new FormData ()
formData.append ('grant_type', 'client_credentials')
formData.append ('client_id', CONFIG.CLIENT_ID)
formData.append ('client_secret', CONFIG.CLIENT_SECRET)
try {
const response = await axios.post (
@@ -17,27 +17,27 @@ async function getAccessToken () {
{
headers: {'Content-Type': 'multipart/form-data'},
}
);
)
if (response.data && response.data.access_token) {
console.log ('Access token retrieved:', response.data.access_token);
return response.data.access_token;
console.log ('Access token retrieved:', response.data.access_token)
return response.data.access_token
} else {
console.error ('Error: access_token not found in response');
return null;
console.error ('Error: access_token not found in response')
return null
}
} catch (error) {
console.error (
'Error fetching access token:',
error.response ? error.response.data : error.message
);
return null;
)
return null
}
}
async function fetchPlantData (plantId) {
const accessToken = await getAccessToken ();
const accessToken = await getAccessToken ()
if (!accessToken) {
return null;
return null
}
try {
const response = await axios.get (
@@ -47,25 +47,25 @@ async function fetchPlantData (plantId) {
Authorization: `Bearer ${accessToken}`,
},
}
);
return response.data;
)
return response.data
} catch (error) {
console.error (
'Error fetching plant data:',
error.response ? error.response.data : error.message
);
return null;
)
return null
}
}
plantsRouter.get ('/list', async (req, res) => {
const accessToken = await getAccessToken ();
const accessToken = await getAccessToken ()
if (!accessToken) {
res.status (500).send ({message: 'Error obtaining access token'});
return;
res.status (500).send ({message: 'Error obtaining access token'})
return
}
try {
const alias = req.query.alias || 'monstera';
const alias = req.query.alias || 'monstera'
const response = await axios.get (
'https://open.plantbook.io/api/v1/plant/search',
{
@@ -76,13 +76,13 @@ plantsRouter.get ('/list', async (req, res) => {
alias: alias,
},
}
);
)
const plantsList = response.data.results;
const plantsList = response.data.results
const plants = await Promise.all (
plantsList.map (async plant => {
const plantDetails = await fetchPlantData (plant.pid);
const plantDetails = await fetchPlantData (plant.pid)
return {
id: plant.pid,
alias: plant.alias,
@@ -98,23 +98,23 @@ plantsRouter.get ('/list', async (req, res) => {
min_soil_moist: plantDetails ? plantDetails.min_soil_moist : null,
max_soil_ec: plantDetails ? plantDetails.max_soil_ec : null,
min_soil_ec: plantDetails ? plantDetails.min_soil_ec : null,
};
}
})
);
)
res.send ({results: plants});
res.send ({results: plants})
} catch (error) {
console.error (
'Error fetching plant list:',
error.response ? error.response.data : error.message
);
res.status (500).send ({message: 'Error fetching plant list'});
)
res.status (500).send ({message: 'Error fetching plant list'})
}
});
})
plantsRouter.get ('/:id', async (req, res) => {
const plantId = req.params.id;
const plantData = await fetchPlantData (plantId);
const plantId = req.params.id
const plantData = await fetchPlantData (plantId)
if (plantData) {
const detailedPlantData = {
@@ -132,12 +132,12 @@ plantsRouter.get ('/:id', async (req, res) => {
max_soil_ec: plantData.max_soil_ec,
min_soil_ec: plantData.min_soil_ec,
image_url: plantData.image_url,
};
}
res.send (detailedPlantData);
res.send (detailedPlantData)
} else {
res.status (404).send ({message: 'Plant not found'});
res.status (404).send ({message: 'Plant not found'})
}
});
})
module.exports = plantsRouter;
module.exports = plantsRouter

View File

@@ -1,4 +1,4 @@
const express = require('express');
const express = require('express')
const plantsRouter = express.Router()
@@ -15,28 +15,28 @@ const plants = [
frequency: 3,
startDate: "2024-10-05",
},
];
]
const calculateWateringDates = (startDate, frequency) => {
const dates = [];
const start = new Date(startDate);
const dates = []
const start = new Date(startDate)
for (let i = 0; i < 30; i += frequency) {
const nextWateringDate = new Date(start);
nextWateringDate.setDate(start.getDate() + i);
dates.push(nextWateringDate.toISOString().split('T')[0]);
const nextWateringDate = new Date(start)
nextWateringDate.setDate(start.getDate() + i)
dates.push(nextWateringDate.toISOString().split('T')[0])
}
return dates;
};
return dates
}
const plantsWithDates = plants.map(plant => ({
...plant,
wateringDates: calculateWateringDates(plant.startDate, plant.frequency),
}));
}))
plantsRouter.get('/api/plants', (req, res) => {
res.json(plantsWithDates);
});
res.json(plantsWithDates)
})
module.exports = plantsRouter;
module.exports = plantsRouter

View File

@@ -1,43 +1,43 @@
const authRouter = require('express').Router();
const authRouter = require('express').Router()
// For creating tokens
const jwt = require('jsonwebtoken');
const jwt = require('jsonwebtoken')
const { TOKEN_KEY } = require('../key')
module.exports = authRouter;
module.exports = authRouter
const { addUserToDB, getUserFromDB } = require('../db');
const { addUserToDB, getUserFromDB } = require('../db')
// Get a user by its id
authRouter.get('/:id', (req, res) => {
const user = getUserFromDB(req.params.id);
const user = getUserFromDB(req.params.id)
if (user) {
res.status(200).send({user});
res.status(200).send({user})
} else {
res.status(404).send({message: 'User was not found'});
res.status(404).send({message: 'User was not found'})
}
})
// For login (authorization)
authRouter.post('/login', (req, res) => {
const { name, password } = req.body;
const { name, password } = req.body
const user = getUserFromDB(name);
const user = getUserFromDB(name)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
// Invalid authentication
if (!password || password !== user.password) {
res.status(401).send({message: 'Invalid credentials (password)'});
return;
res.status(401).send({message: 'Invalid credentials (password)'})
return
}
// Now, authorization
@@ -45,29 +45,29 @@ authRouter.post('/login', (req, res) => {
expiresIn: '1h'
})
res.status(200).send({token});
res.status(200).send({token})
})
authRouter.post('/reg', (req, res) => {
const { name, password, nickname } = req.body;
const { name, password, nickname } = req.body
const user = getUserFromDB(name);
const user = getUserFromDB(name)
// Invalid identification
if (user) {
res.status(409).send({message: 'Such id already exists'});
return;
res.status(409).send({message: 'Such id already exists'})
return
}
if (!name || !password || !nickname) {
res.status(401).send({message: 'Empty or invalid fields'});
return;
res.status(401).send({message: 'Empty or invalid fields'})
return
}
// Add to 'DB'
const newUser = {id: name, password: password, nickname: nickname};
const newUser = {id: name, password: password, nickname: nickname}
addUserToDB(newUser)
res.status(200).send({user: newUser});
res.status(200).send({user: newUser})
})

View File

@@ -1,45 +1,45 @@
const changeRouter = require('express').Router();
const changeRouter = require('express').Router()
module.exports = changeRouter;
module.exports = changeRouter
const { getUserFromDB, deleteUserFromDB, addUserToDB } = require('../db');
const { getUserFromDB, deleteUserFromDB, addUserToDB } = require('../db')
changeRouter.post('/nickname', (req, res) => {
const { id, newNickname } = req.body;
const { id, newNickname } = req.body
const user = getUserFromDB(id);
const user = getUserFromDB(id)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
const updatedUser = {
"nickname": newNickname,
"password": user.password,
"id": user.id
};
}
// Delete the old one
deleteUserFromDB(id)
// Insert updated
addUserToDB(updatedUser);
addUserToDB(updatedUser)
res.status(200).send({});
});
res.status(200).send({})
})
changeRouter.post('/password', (req, res) => {
const { id, newPassword } = req.body;
const { id, newPassword } = req.body
const user = getUserFromDB(id);
const user = getUserFromDB(id)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
// Delete the old one
@@ -50,15 +50,15 @@ changeRouter.post('/password', (req, res) => {
"nickname": user.nickname,
"password": newPassword,
"id": user.id
};
addUserToDB(updatedUser);
}
addUserToDB(updatedUser)
res.status(200).send({});
});
res.status(200).send({})
})
changeRouter.delete('/:id', (req, res) => {
const { id } = req.params;
const { id } = req.params
deleteUserFromDB(id);
});
deleteUserFromDB(id)
})

View File

@@ -1,43 +1,43 @@
const chatRouter = require('express').Router();
const chatRouter = require('express').Router()
module.exports = chatRouter;
module.exports = chatRouter
const { getChatFromDB, getUsersChats, addChatToDB, getUserFromDB,
addMessageToChat} = require('../db');
addMessageToChat} = require('../db')
chatRouter.get('/item/:id1/:id2', (req, res) => {
const { id1, id2 } = req.params;
const { id1, id2 } = req.params
if (id1 === id2) {
res.status(400).send({message: 'Ids should be different'});
return;
res.status(400).send({message: 'Ids should be different'})
return
}
const chat = getChatFromDB(id1, id2);
const chat = getChatFromDB(id1, id2)
if (chat) {
res.status(200).send({chat});
res.status(200).send({chat})
} else {
res.status(404).send({message: 'Chat was not found'});
res.status(404).send({message: 'Chat was not found'})
}
})
chatRouter.post('/item/:id1/:id2', (req, res) => {
const { id1, id2 } = req.params;
const { id1, id2 } = req.params
if (id1 === id2) {
res.status(400).send({message: 'Ids should be different'});
return;
res.status(400).send({message: 'Ids should be different'})
return
}
const chat = getChatFromDB(id1, id2);
const chat = getChatFromDB(id1, id2)
if (chat) {
// Chat already exists
res.status(200).send({chat});
res.status(200).send({chat})
} else {
if (!getUserFromDB(id1) || !getUserFromDB(id2)) {
res.status(404).send({message: 'Such interlocutor does not exist'});
res.status(404).send({message: 'Such interlocutor does not exist'})
} else {
// Creating new chat
const newChat = {
@@ -46,41 +46,41 @@ chatRouter.post('/item/:id1/:id2', (req, res) => {
messages: []
}
addChatToDB(newChat);
addChatToDB(newChat)
res.status(200).send({newChat});
res.status(200).send({newChat})
}
}
})
chatRouter.get('/list/:id', (req, res) => {
const { id } = req.params;
const { id } = req.params
const userChats = getUsersChats(id);
const userChats = getUsersChats(id)
if (!userChats) {
res.status(404).send({message: 'Error with retrieving chats'});
res.status(404).send({message: 'Error with retrieving chats'})
} else {
res.status(200).send({chats: userChats});
res.status(200).send({chats: userChats})
}
})
chatRouter.post('/message/:sender/:receiver', (req, res) => {
const { sender, receiver } = req.params;
const { message } = req.body;
const { sender, receiver } = req.params
const { message } = req.body
const chat = getChatFromDB(sender, receiver);
const chat = getChatFromDB(sender, receiver)
if (!chat) {
// Chat already exists
res.status(400).send({message: "Such chat does not exist"});
res.status(400).send({message: "Such chat does not exist"})
} else {
if (!getUserFromDB(sender) || !getUserFromDB(receiver)) {
res.status(404).send({message: 'Such people do not exist'});
res.status(404).send({message: 'Such people do not exist'})
} else {
// Add new message
addMessageToChat(chat, message);
res.status(200).send({});
addMessageToChat(chat, message)
res.status(200).send({})
}
}
})

View File

@@ -1,72 +1,72 @@
// Read already defined users (pseudo-DB)
const users = require('./auth/users.json');
const chats = require('./chat/chats.json');
const users = require('./auth/users.json')
const chats = require('./chat/chats.json')
const getUserFromDB = (userID) => {
if (!userID) {return false;}
if (!userID) {return false}
// Accessing 'DB'
const user = users.find((user) => user.id === userID);
const user = users.find((user) => user.id === userID)
if (user) {
return user;
return user
} else {
return false;
return false
}
}
const deleteUserFromDB = (userID) => {
const index = users.findIndex(item => item.id === userID);
const index = users.findIndex(item => item.id === userID)
if (index !== -1) {
users.splice(index, 1);
users.splice(index, 1)
}
}
const addUserToDB = (user) => {
users.push(user);
users.push(user)
}
const getChatFromDB = (firstID, secondID) => {
if (!firstID || !secondID) {return false;}
if (!firstID || !secondID) {return false}
// Accessing 'DB'
const chat = chats.find((item) =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID))
if (chat) {
return chat;
return chat
} else {
return false;
return false
}
}
const getUsersChats = (userID) => {
if (!userID) {return false;}
if (!userID) {return false}
const userChats = chats.filter((chat) => (chat.id1 === userID || chat.id2 === userID));
const userChats = chats.filter((chat) => (chat.id1 === userID || chat.id2 === userID))
if (userChats) {
return userChats;
return userChats
} else {
return false;
return false
}
}
const addMessageToChat = (chat, msg) => {
chat.messages.push(msg);
chat.messages.push(msg)
}
const deleteChatFromDB = (firstID, secondID) => {
const index = chats.findIndex(item =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID))
if (index !== -1) {
chats.splice(index, 1);
chats.splice(index, 1)
}
}
const addChatToDB = (chat) => {
chats.push(chat);
chats.push(chat)
}

View File

@@ -1,17 +1,17 @@
const changeRouter = require("./change");
const authRouter = require("./auth");
const chatRouter = require("./chat");
const changeRouter = require("./change")
const authRouter = require("./auth")
const chatRouter = require("./chat")
const router = require('express').Router();
const router = require('express').Router()
const delay = require('./middlewares/delay');
const verify = require('./middlewares/verify');
const delay = require('./middlewares/delay')
const verify = require('./middlewares/verify')
module.exports = router;
module.exports = router
// router.use(delay(300));
// router.use('/books', delay, booksRouter);
router.use('/auth', authRouter);
router.use('/change', verify, changeRouter);
router.use('/auth', authRouter)
router.use('/change', verify, changeRouter)
router.use('/chat', verify, chatRouter)

View File

@@ -1,3 +1,3 @@
const TOKEN_KEY = '5frv12e4few3r';
const TOKEN_KEY = '5frv12e4few3r'
module.exports = { TOKEN_KEY }

View File

@@ -1,22 +1,22 @@
const jwt = require('jsonwebtoken');
const jwt = require('jsonwebtoken')
const { TOKEN_KEY } = require('../key')
function verifyToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];
const token = req.headers['authorization']?.split(' ')[1]
if (!token) {
return res.status(401).send({ message: 'No token provided' });
return res.status(401).send({ message: 'No token provided' })
}
// Verify token
jwt.verify(token, TOKEN_KEY, (err, decoded) => {
if (err) {
return res.status(401).send({ message: 'Unauthorized' });
return res.status(401).send({ message: 'Unauthorized' })
}
next(); // Proceed to the next middleware or route
});
next() // Proceed to the next middleware or route
})
}
module.exports = verifyToken;
module.exports = verifyToken

View File

@@ -1,5 +1,5 @@
const express = require('express')
const router = express.Router()
const { Router } = require('express')
const router = Router()
router.use('/enterfront', require('./enterfront/index'))

View File

@@ -1,19 +0,0 @@
const router = require('express').Router()
const first = router.get('/first', (req, res) => {
res.send({
success: true,
warnings: [{
title: 'Внимание',
text: 'Данный api создан для примера!',
}],
})
/**
* Этот эндпоинт будет доступен по адресу http://89.223.91.151:8080/multystub/example/first
*/
})
router.use('/example-api', first)
module.exports = router

View File

@@ -1,7 +1,7 @@
const ObjectId = require('mongodb').ObjectID
const getHash = require('pbkdf2-password')()
const { getDB } = require('../../utils/mongo')
const { getDB } = require('../../../utils/mongo')
const USERS_COLLECTION = 'users'
const LISTS_COLLECTION = 'lists'

View File

Before

Width:  |  Height:  |  Size: 377 B

After

Width:  |  Height:  |  Size: 377 B

View File

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 470 B

View File

Before

Width:  |  Height:  |  Size: 578 B

After

Width:  |  Height:  |  Size: 578 B

View File

Before

Width:  |  Height:  |  Size: 481 B

After

Width:  |  Height:  |  Size: 481 B

View File

Before

Width:  |  Height:  |  Size: 368 B

After

Width:  |  Height:  |  Size: 368 B

View File

Before

Width:  |  Height:  |  Size: 593 B

After

Width:  |  Height:  |  Size: 593 B

View File

Before

Width:  |  Height:  |  Size: 539 B

After

Width:  |  Height:  |  Size: 539 B

View File

Before

Width:  |  Height:  |  Size: 414 B

After

Width:  |  Height:  |  Size: 414 B

View File

Before

Width:  |  Height:  |  Size: 414 B

After

Width:  |  Height:  |  Size: 414 B

View File

Before

Width:  |  Height:  |  Size: 739 B

After

Width:  |  Height:  |  Size: 739 B

View File

Before

Width:  |  Height:  |  Size: 686 B

After

Width:  |  Height:  |  Size: 686 B

View File

Before

Width:  |  Height:  |  Size: 750 B

After

Width:  |  Height:  |  Size: 750 B

View File

Before

Width:  |  Height:  |  Size: 687 B

After

Width:  |  Height:  |  Size: 687 B

View File

Before

Width:  |  Height:  |  Size: 706 B

After

Width:  |  Height:  |  Size: 706 B

View File

Before

Width:  |  Height:  |  Size: 776 B

After

Width:  |  Height:  |  Size: 776 B

View File

Before

Width:  |  Height:  |  Size: 628 B

After

Width:  |  Height:  |  Size: 628 B

View File

Before

Width:  |  Height:  |  Size: 742 B

After

Width:  |  Height:  |  Size: 742 B

View File

Before

Width:  |  Height:  |  Size: 853 B

After

Width:  |  Height:  |  Size: 853 B

View File

Before

Width:  |  Height:  |  Size: 911 B

After

Width:  |  Height:  |  Size: 911 B

View File

Before

Width:  |  Height:  |  Size: 601 B

After

Width:  |  Height:  |  Size: 601 B

View File

Before

Width:  |  Height:  |  Size: 648 B

After

Width:  |  Height:  |  Size: 648 B

View File

Before

Width:  |  Height:  |  Size: 709 B

After

Width:  |  Height:  |  Size: 709 B

View File

Before

Width:  |  Height:  |  Size: 442 B

After

Width:  |  Height:  |  Size: 442 B

View File

Before

Width:  |  Height:  |  Size: 858 B

After

Width:  |  Height:  |  Size: 858 B

View File

Before

Width:  |  Height:  |  Size: 718 B

After

Width:  |  Height:  |  Size: 718 B

View File

Before

Width:  |  Height:  |  Size: 1015 B

After

Width:  |  Height:  |  Size: 1015 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 811 B

After

Width:  |  Height:  |  Size: 811 B

View File

Before

Width:  |  Height:  |  Size: 872 B

After

Width:  |  Height:  |  Size: 872 B

View File

Before

Width:  |  Height:  |  Size: 767 B

After

Width:  |  Height:  |  Size: 767 B

View File

Before

Width:  |  Height:  |  Size: 719 B

After

Width:  |  Height:  |  Size: 719 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 812 B

After

Width:  |  Height:  |  Size: 812 B

View File

Before

Width:  |  Height:  |  Size: 760 B

After

Width:  |  Height:  |  Size: 760 B

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 955 B

After

Width:  |  Height:  |  Size: 955 B

View File

Before

Width:  |  Height:  |  Size: 908 B

After

Width:  |  Height:  |  Size: 908 B

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1016 B

After

Width:  |  Height:  |  Size: 1016 B

View File

Before

Width:  |  Height:  |  Size: 997 B

After

Width:  |  Height:  |  Size: 997 B

View File

Before

Width:  |  Height:  |  Size: 856 B

After

Width:  |  Height:  |  Size: 856 B

View File

Before

Width:  |  Height:  |  Size: 693 B

After

Width:  |  Height:  |  Size: 693 B

View File

Before

Width:  |  Height:  |  Size: 711 B

After

Width:  |  Height:  |  Size: 711 B

View File

Before

Width:  |  Height:  |  Size: 766 B

After

Width:  |  Height:  |  Size: 766 B

View File

Before

Width:  |  Height:  |  Size: 952 B

After

Width:  |  Height:  |  Size: 952 B

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 843 B

After

Width:  |  Height:  |  Size: 843 B

View File

Before

Width:  |  Height:  |  Size: 951 B

After

Width:  |  Height:  |  Size: 951 B

View File

Before

Width:  |  Height:  |  Size: 967 B

After

Width:  |  Height:  |  Size: 967 B

View File

Before

Width:  |  Height:  |  Size: 923 B

After

Width:  |  Height:  |  Size: 923 B

View File

Before

Width:  |  Height:  |  Size: 725 B

After

Width:  |  Height:  |  Size: 725 B

View File

Before

Width:  |  Height:  |  Size: 935 B

After

Width:  |  Height:  |  Size: 935 B

View File

Before

Width:  |  Height:  |  Size: 820 B

After

Width:  |  Height:  |  Size: 820 B

View File

Before

Width:  |  Height:  |  Size: 841 B

After

Width:  |  Height:  |  Size: 841 B

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Some files were not shown because too many files have changed in this diff Show More