;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

This commit is contained in:
leca 2024-10-27 05:45:12 +03:00
parent 3388da7280
commit 09b5106538
20 changed files with 82 additions and 76 deletions

View File

@ -2,7 +2,7 @@ import AbstractProductService from '../services/abstractproduct.js';
import statuses from '../utils/status.js';
import log from '../utils/log.js';
const TAG = "/controllers/abstractproduct.js"
const TAG = "/controllers/abstractproduct.js";
class AbstractProductController {
async create(req, res) {
@ -15,8 +15,8 @@ class AbstractProductController {
case statuses.duplicate:
return res.status(400).send(e.message);
default:
log.error(e.original)
return res.status(500).send(e.message)
log.error(e.original);
return res.status(500).send(e.message);
}
}
}

View File

@ -1,6 +1,5 @@
import CategoryService from "../services/category.js";
import log
from "../utils/log.js";
import log from "../utils/log.js";
const TAG = "controllers/category.js";
class CategoryController {

View File

@ -5,7 +5,7 @@ import config from '../../config.json' with {type: "json"};
import statuses from '../utils/status.js';
import log from '../utils/log.js';
const TAG = "/controllers/group.js"
const TAG = "/controllers/group.js";
class GroupController {
async create(req, res) {

View File

@ -28,7 +28,7 @@ class AbstractProductController {
if (abstract_product_id) await ProductService.updateAbstractProductId(groupId, localId, abstract_product_id);
if (amount) await ProductService.updateAmount(groupId, localId, amount)
if (amount) await ProductService.updateAmount(groupId, localId, amount);
if (date_of_production) await ProductService.updateDateOfProduction(groupId, localId, date_of_production);

View File

@ -15,7 +15,7 @@ class UserController {
await UserService.create(username, password);
log.info(`New user with name ${username} has just registered`);
return res.status(200).send("Successfull register")
return res.status(200).send("Successfull register");
} catch (e) { res.status(500).send(log.unknownError(`${TAG}/register: ${e}`)); }
}
@ -35,10 +35,10 @@ class UserController {
try {
const { groupId } = req.params;
let result = {}
let result = {};
result.abstract_products = await AbstractProductService.getAll(groupId);
result.products = await ProductService.getAll(groupId);
// result.categories = await CategoryService.getAll(groupId);
result.categories = await CategoryService.getAll(groupId);
return res.status(200).json(result);
} catch (e) { res.status(500).send(log.unknownError(`${TAG}/synchronize: ${e}`)); }

View File

@ -2,7 +2,7 @@ import express from 'express';
import UserRouter from './routers/user.js';
import GroupRouter from './routers/group.js';
import AbstractProductRouter from './routers/abstractproduct.js';
import log from './utils/log.js'
import log from './utils/log.js';
import config from '../config.json' with {type: "json"};
import ProductRouter from './routers/product.js';
@ -21,4 +21,4 @@ app.use('/api/category', CategoryRouter);
app.listen(config.port, () => {
log.info(`Application has started on port ${config.port}`)
})
});

View File

@ -4,7 +4,7 @@ import config from '../../config.json' with {type: "json"};
import GroupService from '../services/group.js';
import UserService from '../services/user.js';
const TAG = "/middlewares/auth.js"
const TAG = "/middlewares/auth.js";
const requireUsername = async (req, res, next) => {
if (req.method == "OPTIONS") next();
@ -14,7 +14,7 @@ const requireUsername = async (req, res, next) => {
if (!username) return res.status(400).send("Username is required");
next();
} catch (e) { return res.status(500).send(unknownError(`${TAG}/requireUsername: ${e}`)); }
}
};
const requirePassword = async (req, res, next) => {
if (req.method == "OPTIONS") next();
@ -24,36 +24,36 @@ const requirePassword = async (req, res, next) => {
if (!password) return res.status(400).send("Password is required");
next();
} catch (e) { return res.status(500).send(unknownError(`${TAG}/requirePassword: ${e}`)); }
}
};
const authenticate = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
if (!req.headers.authorization) return res.status(403).send("No authorization header supplied");
const token = req.headers.authorization.split(' ')[1]
const token = req.headers.authorization.split(' ')[1];
if (!token) return res.status(403).send("No authorization token supplied");
if (!jwt.verify(token, config.secret)) return res.status(403).send("Authorization token is incorrect");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authenticate: ${e}`)); }
}
};
const authorizeGroupOwner = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
const token = req.headers.authorization.split(' ')[1]
const token = req.headers.authorization.split(' ')[1];
const { groupId } = req.params;
let user = jwt.decode(token, config.secret)
let user = jwt.decode(token, config.secret);
let adminId = await GroupService.getAdminId(groupId);
if (user.login.id != adminId) return res.status(403).send("Not your group");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authorizeGroupOwner: ${e}`)); }
}
};
const checkGroupPassword = async (req, res, next) => {
if (req.method == "OPTIONS") next();
@ -68,17 +68,24 @@ const checkGroupPassword = async (req, res, next) => {
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/checkGroupPassword: ${e}`)); }
}
};
const userIsInGroup = async (req, res, next) => {
if (req.method == "OPTIONS") next();
const groupId = req.body.groupId || req.params.groupId;
const token = req.headers.authorization.split(' ')[1]
let user = jwt.decode(token, config.secret)
const token = req.headers.authorization.split(' ')[1];
let user = jwt.decode(token, config.secret);
if (!await UserService.isInGroup(user.login.id, groupId)) return res.status(403).send("You are not a member of this group");
next();
}
};
export default { requireUsername, requirePassword, authenticate, authorizeGroupOwner, checkGroupPassword, userIsInGroup }
export default {
requireUsername,
requirePassword,
authenticate,
authorizeGroupOwner,
checkGroupPassword,
userIsInGroup
};

View File

@ -6,7 +6,7 @@ import CategoryService from '../services/category.js';
import log from '../utils/log.js';
import statuses from '../utils/status.js';
const TAG = "/middlewares/existance.js"
const TAG = "/middlewares/existance.js";
const usernameExists = async (req, res, next) => {
try {
@ -26,7 +26,7 @@ const usernameDoesntExist = async (req, res, next) => {
if (user != undefined && user != statuses.not_found) return res.status(400).send("Such username already taken");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/usernameDoesntExist: ${e}`)); }
}
};
const groupExists = async (req, res, next) => {
try {
@ -37,7 +37,7 @@ const groupExists = async (req, res, next) => {
if (!group || group == statuses.not_found) return res.status(404).send("Group not found");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupExists: ${e}`)) }
}
};
const groupDoesntExist = async (req, res, next) => {
try {
@ -48,7 +48,7 @@ const groupDoesntExist = async (req, res, next) => {
if (group || group != statuses.not_found) return res.status(400).send("Such group already exists");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupDoesntExist: ${e}`)) }
}
};
const groupNameDoesntExist = async (req, res, next) => {
try {
@ -57,8 +57,8 @@ const groupNameDoesntExist = async (req, res, next) => {
let group = await GroupService.getByName(groupName);
if (group) return res.status(400).send("Such group name already exists");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupNameDoesntExist: ${e}`)) }
}
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/groupNameDoesntExist: ${e}`)); }
};
const abstractProductExists = async (req, res, next) => {
try {
@ -67,8 +67,8 @@ const abstractProductExists = async (req, res, next) => {
let result = await AbstractProductService.exists(groupId, localId);
if (!result) return res.status(404).send("Abstract product not found");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/abstractProductExists: ${e}`)) }
}
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/abstractProductExists: ${e}`)); }
};
const productExists = async (req, res, next) => {
try {
@ -77,8 +77,8 @@ const productExists = async (req, res, next) => {
let result = await ProductService.exists(groupId, localId);
if (!result) return res.status(404).send("Product not found");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/productExists: ${e}`)) }
}
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/productExists: ${e}`)); }
};
const categoryNameDoesntExist = async (req, res, next) => {
try {
@ -87,8 +87,8 @@ const categoryNameDoesntExist = async (req, res, next) => {
let result = await CategoryService.getByName(groupId, localId, categoryName);
if (result != statuses.not_found) return res.status(400).send("Such category name exists");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryNameDoesntExist: ${e}`)) }
}
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryNameDoesntExist: ${e}`)); }
};
const categoryExists = async (req, res, next) => {
try {
@ -97,8 +97,8 @@ const categoryExists = async (req, res, next) => {
let result = await CategoryService.getById(groupId, localId);
if (!result || result == statuses.not_found) return res.status(404).send("No such category");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryExists: ${e}`)) }
}
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/categoryExists: ${e}`)); }
};
export default {
usernameExists,
@ -113,4 +113,4 @@ export default {
categoryNameDoesntExist,
categoryExists
}
};

View File

@ -1,11 +1,11 @@
import { Router } from 'express';
import auth from '../middlewares/auth.js';
import AbstractProductController from '../controllers/abstractproduct.js'
import AbstractProductController from '../controllers/abstractproduct.js';
import existance from '../middlewares/existance.js';
const AbstractProductRouter = new Router();
AbstractProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, AbstractProductController.create);
AbstractProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.abstractProductExists, AbstractProductController.update)
AbstractProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.abstractProductExists, AbstractProductController.update);
export default AbstractProductRouter;

View File

@ -6,6 +6,6 @@ import CategoryController from '../controllers/category.js';
const CategoryRouter = new Router();
CategoryRouter.post('/create', auth.authenticate, existance.groupExists, existance.categoryNameDoesntExist, CategoryController.create);
CategoryRouter.post('/update', auth.authenticate, existance.groupExists, existance.categoryExists, CategoryController.update)
CategoryRouter.post('/update', auth.authenticate, existance.groupExists, existance.categoryExists, CategoryController.update);
export default CategoryRouter;

View File

@ -1,12 +1,12 @@
import { Router } from 'express';
import auth from '../middlewares/auth.js';
import GroupController from '../controllers/group.js'
import GroupController from '../controllers/group.js';
import existance from '../middlewares/existance.js';
const GroupRouter = new Router();
GroupRouter.post('/create/:groupName', auth.authenticate, existance.groupNameDoesntExist, GroupController.create);
GroupRouter.post('/join/:groupId', auth.authenticate, existance.groupExists, auth.requirePassword, auth.checkGroupPassword, GroupController.join);
GroupRouter.post('/password/:groupId', auth.authenticate, existance.groupExists, auth.authorizeGroupOwner, auth.requirePassword, GroupController.updatePassword)
GroupRouter.post('/password/:groupId', auth.authenticate, existance.groupExists, auth.authorizeGroupOwner, auth.requirePassword, GroupController.updatePassword);
export default GroupRouter;

View File

@ -6,6 +6,6 @@ import existance from '../middlewares/existance.js';
const ProductRouter = new Router();
ProductRouter.post('/create', auth.authenticate, existance.groupExists, auth.userIsInGroup, ProductController.create);
ProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.productExists, ProductController.update)
ProductRouter.post('/update', auth.authenticate, existance.groupExists, auth.userIsInGroup, existance.productExists, ProductController.update);
export default ProductRouter;

View File

@ -1,7 +1,7 @@
import { Router } from 'express';
import auth from '../middlewares/auth.js';
import existance from '../middlewares/existance.js';
import UserController from '../controllers/user.js'
import UserController from '../controllers/user.js';
const UserRouter = new Router();

View File

@ -53,9 +53,9 @@ class AbstractProductService {
}
async getAll(groupId) {
let result = (await db.query("SELECT local_id, barcode, name, net_weight, image_filename, category, unit FROM abstract_products WHERE group_id = $1", [groupId])).rows
let result = (await db.query("SELECT local_id, barcode, name, net_weight, image_filename, category, unit FROM abstract_products WHERE group_id = $1", [groupId])).rows;
if (!result) return statuses.not_found;
return result
return result;
}
async exists(groupId, localId) {

View File

@ -3,7 +3,7 @@ import statuses from '../utils/status.js';
class CategoryService {
async create(groupId, categoryId, name) {
await db.query("INSERT INTO categories (group_id, local_id, name) VALUES ($1, $2, $3)", [groupId, categoryId, name])
await db.query("INSERT INTO categories (group_id, local_id, name) VALUES ($1, $2, $3)", [groupId, categoryId, name]);
}
async update(groupId, categoryId, name) {
@ -13,7 +13,7 @@ class CategoryService {
async getById(groupId, localId) {
let result = (await db.query("SELECT * FROM categories WHERE group_id = $1 AND local_id = $2", [groupId, localId]))
if (result.rowCount == 0) return statuses.not_found;
return result.rows[0]
return result.rows[0];
}
async getByName(groupId, localId, name) {

View File

@ -4,19 +4,19 @@ import status from '../utils/status.js';
class GroupService {
async create(name, creatorId) {
let res = await db.query("INSERT INTO groups (name, admin_id) VALUES ($1, $2) RETURNING ID", [name, creatorId]).catch(errorHandler)
let res = await db.query("INSERT INTO groups (name, admin_id) VALUES ($1, $2) RETURNING ID", [name, creatorId]).catch(errorHandler);
return res.rows[0];
}
async getById(id) {
let res = (await db.query("SELECT * FROM groups WHERE id = $1", [id]))
let res = (await db.query("SELECT * FROM groups WHERE id = $1", [id]));
if (res.rowCount == 0) return status.not_found;
return res.rows[0];
}
async getAdminId(id) {
return (await db.query("SELECT admin_id FROM groups WHERE ID = $1", [id])).rows[0].admin_id
return (await db.query("SELECT admin_id FROM groups WHERE ID = $1", [id])).rows[0].admin_id;
}
async updatePassword(id, password) {
@ -28,7 +28,7 @@ class GroupService {
}
async getByName(name) {
return (await db.query("SELECT * FROM groups WHERE name = $1", [name])).rows[0]
return (await db.query("SELECT * FROM groups WHERE name = $1", [name])).rows[0];
}
};

View File

@ -7,7 +7,7 @@ class ProductService {
await db.query("INSERT INTO products (group_id, local_id, abstract_product_id, amount, date_of_production, expiry_date) VALUES ($1, $2, $3, $4, $5, $6)", [groupid, localid, abstract_product_id, amount, date_of_production, expiry_date])
.catch((e) => {
errorHandler(e, "Abstract Product")
})
});
}
async updateAbstractProductId(groupId, localId, abstract_product_id) {
@ -29,20 +29,20 @@ class ProductService {
await db.query("UPDATE products SET date_of_production = $1 WHERE group_id = $2 AND local_id = $3", [date_of_production, groupId, localId])
.catch((e) => {
errorHandler(e, "date of production")
})
});
}
async updateExpiryDate(groupId, localId, expiry_date) {
await db.query("UPDATE products SET expiry_date = $1 WHERE group_id = $2 AND local_id = $3", [expiry_date, groupId, localId])
.catch((e) => {
errorHandler(e, "expiry date")
})
});
}
async getAll(groupId) {
let result = (await db.query("SELECT local_id, abstract_product_id, amount, date_of_production, expiry_date FROM products WHERE group_id = $1", [groupId])).rows
let result = (await db.query("SELECT local_id, abstract_product_id, amount, date_of_production, expiry_date FROM products WHERE group_id = $1", [groupId])).rows;
if (!result) return statuses.not_found;
return result
return result;
}
async exists(groupId, localId) {

View File

@ -5,14 +5,14 @@ import bcrypt from 'bcrypt';
class UserService {
async create(username, password) {
await db.query("INSERT INTO users (username, password) VALUES ($1, $2)", [username, bcrypt.hashSync(password, 12)]).catch((e) => {
errorHandler(e, "user")
errorHandler(e, "user");
})
return statuses.ok
return statuses.ok;
}
async getByUsername(username) {
let user = (await db.query("SELECT * FROM Users WHERE username = $1", [username])).rows
if (user == undefined) return statuses.not_found
let user = (await db.query("SELECT * FROM Users WHERE username = $1", [username])).rows;
if (user == undefined) return statuses.not_found;
return (user[0]);
}

View File

@ -1,24 +1,24 @@
import config from '../../config.json' with {type: "json"};
const debug = (text) => {
if (config.debug) console.debug(`[D] [${Date()}]: ${text}`)
if (config.debug) console.debug(`[D] [${Date()}]: ${text}`);
}
const info = (text) => {
console.log(`[I] [${Date()}]: ${text}`)
console.log(`[I] [${Date()}]: ${text}`);
}
const error = (text) => {
console.error(`[E] [${Date()}]: ${text}`)
console.error(`[E] [${Date()}]: ${text}`);
}
const warn = (text) => {
console.warn(`[W] [${Date()}]: ${text}`)
console.warn(`[W] [${Date()}]: ${text}`);
}
const unknownError = (text) => {
error(text);
return "Unknown server error. Please, report to the developer"
return "Unknown server error. Please, report to the developer";
}
export default { debug, info, error, warn, unknownError }
export default { debug, info, error, warn, unknownError };

View File

@ -1,4 +1,4 @@
import statuses from "./status.js"
import statuses from "./status.js";
const errorHandler = (e, obj) => {
switch (e.code) {
@ -6,24 +6,24 @@ const errorHandler = (e, obj) => {
throw {
status: statuses.duplicate,
message: `Such ${obj} already exists`
}
};
case '22007':
throw {
status: statuses.invalid_syntax,
message: `Invalid syntax in ${obj}`
}
};
case '22001':
throw {
status: statuses.invalid_syntax,
message: `Value too long (${obj})`
}
};
default:
throw {
status: statuses.unknown,
message: `Unknown error. Please, report to the developer`,
original: e
}
}
};
};
};
export default errorHandler;