Compare commits

..

No commits in common. "e1da64cac3f3e292558eb314eafee799814d3bdf" and "e9d03b9cbb9346a1b25a404bf5ea802347fc2aa1" have entirely different histories.

8 changed files with 251 additions and 246 deletions

View File

@ -20,18 +20,19 @@ export const categoriesRouter = express.Router();
*/ */
// GET categories/ // GET categories/
categoriesRouter.get('/', async (req: Request, res: Response) => { categoriesRouter.get('/', async (req: Request, res: Response) => {
try { try {
const categories: Categories = await CategoryService.findAll(); const categories: Categories = await CategoryService.findAll();
res.status(200).send(categories); res.status(200).send(categories);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET categories/:id // GET categories/:id
categoriesRouter.get('/:id', async (req: Request, res: Response) => { categoriesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
@ -45,12 +46,12 @@ categoriesRouter.get('/:id', async (req: Request, res: Response) => {
res.status(200).send(category); res.status(200).send(category);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET categories/search/:term // GET categories/search/:term
categoriesRouter.get('/search/:term', async (req: Request, res: Response) => { categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
@ -64,7 +65,48 @@ categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
res.status(200).send(categories); res.status(200).send(categories);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// POST items/
// categoriesRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// categoriesRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// categoriesRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -20,18 +20,19 @@ export const manufacturersRouter = express.Router();
*/ */
// GET items/ // GET items/
manufacturersRouter.get('/', async (req: Request, res: Response) => { manufacturersRouter.get('/', async (req: Request, res: Response) => {
try { try {
const manufacturers: Manufacturers = await ManufacturerService.findAll(); const manufacturers: Manufacturers = await ManufacturerService.findAll();
res.status(200).send(manufacturers); res.status(200).send(manufacturers);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET items/:id // GET items/:id
manufacturersRouter.get('/:id', async (req: Request, res: Response) => { manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
@ -45,12 +46,12 @@ manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
res.status(200).send(manufacturer); res.status(200).send(manufacturer);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET items/:name // GET items/:name
manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => { manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
@ -64,7 +65,48 @@ manufacturersRouter.get('/search/:term', async (req: Request, res: Response) =>
res.status(200).send(manufacturer); res.status(200).send(manufacturer);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// POST items/
// manufacturersRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// manufacturersRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// manufacturersRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -20,6 +20,7 @@ export const pricesRouter = express.Router();
*/ */
// GET prices/ // GET prices/
pricesRouter.get('/', async (req: Request, res: Response) => { pricesRouter.get('/', async (req: Request, res: Response) => {
try { try {
let prices: Prices = []; let prices: Prices = [];
@ -39,12 +40,12 @@ pricesRouter.get('/', async (req: Request, res: Response) => {
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET prices/:id // GET prices/:id
pricesRouter.get('/:id', async (req: Request, res: Response) => { pricesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
@ -58,12 +59,12 @@ pricesRouter.get('/:id', async (req: Request, res: Response) => {
res.status(200).send(price); res.status(200).send(price);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET prices/bestDeals // GET prices/bestDeals
pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => { pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
const amount: number = parseInt(req.params.amount, 10); const amount: number = parseInt(req.params.amount, 10);
@ -77,12 +78,12 @@ pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET prices/byProduct/list/[] // GET prices/byProduct/list/[]
pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) => { pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) => {
const productIds: [number] = JSON.parse(req.params.ids); const productIds: [number] = JSON.parse(req.params.ids);
@ -96,7 +97,47 @@ pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) =>
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// POST items/
// pricesRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// pricesRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// pricesRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -20,18 +20,19 @@ export const productsRouter = express.Router();
*/ */
// GET products/ // GET products/
productsRouter.get('/', async (req: Request, res: Response) => { productsRouter.get('/', async (req: Request, res: Response) => {
try { try {
const products: Products = await ProductService.findAll(); const products: Products = await ProductService.findAll();
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET products/:id // GET products/:id
productsRouter.get('/:id', async (req: Request, res: Response) => { productsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
@ -45,12 +46,12 @@ productsRouter.get('/:id', async (req: Request, res: Response) => {
res.status(200).send(product); res.status(200).send(product);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET products/search/:term // GET products/search/:term
productsRouter.get('/search/:term', async (req: Request, res: Response) => { productsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
@ -64,12 +65,12 @@ productsRouter.get('/search/:term', async (req: Request, res: Response) => {
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET products/list/[1,2,3] // GET products/list/[1,2,3]
productsRouter.get('/list/:ids', async (req: Request, res: Response) => { productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
const ids: [number] = JSON.parse(req.params.ids); const ids: [number] = JSON.parse(req.params.ids);
@ -83,7 +84,50 @@ productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET products/bestDeals
// POST items/
// productsRouter.post('/', async (req: Request, res: Response) => {
// try {
// const product: Product = req.body.product;
//
// await ProductService.create(product);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// productsRouter.put('/', async (req: Request, res: Response) => {
// try {
// const product: Product = req.body.product;
//
// await ProductService.update(product);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// productsRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await ProductService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -3,6 +3,7 @@ export interface User {
username: string; username: string;
email: string; email: string;
password_hash: string; password_hash: string;
hashing_salt: string;
registration_date: Date; registration_date: Date;
last_login_date: Date; last_login_date: Date;
} }

View File

@ -49,67 +49,6 @@ usersRouter.post('/register', async (req: Request, res: Response) => {
// Send the session details back to the user // Send the session details back to the user
res.status(201).send(session); res.status(201).send(session);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
}
});
// POST users/login
usersRouter.post('/login', async (req: Request, res: Response) => {
try {
const username: string = req.body.username;
const password: string = req.body.password;
const ip: string = req.connection.remoteAddress ?? '';
if (!username || !password) {
// Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return;
}
// Update the user entry and create a session
const session: Session = await UserService.login(username, password, ip);
if(!session.session_id) {
// Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ["Wrong username and / or password"], codes: [1, 4]}));
return;
}
// Send the session details back to the user
res.status(201).send(session);
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
}
});
// POST users/checkSessionValid
usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
try {
const sessionId: string = req.body.sessionId;
const sessionKey: string = req.body.sessionKey;
const ip: string = req.connection.remoteAddress ?? '';
if (!sessionId || !sessionKey) {
// Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return;
}
// Update the user entry and create a session
const user: User = await UserService.checkSession(sessionId, sessionKey, ip);
if(!user.user_id) {
// Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ["Invalid session"], codes: [5]}));
return;
}
// Send the session details back to the user
res.status(201).send(user);
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });

View File

@ -34,7 +34,7 @@ export const createUser = async (username: string, password: string, email: stri
let conn; let conn;
try { try {
// Hash password and generate + hash session key // Hash password and generate + hash session key
const pwHash = bcrypt.hashSync(password, 10); const pwHash = bcrypt.hashSync('123', 10);
const sessionKey = Guid.create().toString(); const sessionKey = Guid.create().toString();
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10); const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
@ -57,7 +57,7 @@ export const createUser = async (username: string, password: string, email: stri
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]); const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
await conn.commit(); await conn.commit();
// Get session id of the created session // Get session id of the created user
let sessionId: number = -1; let sessionId: number = -1;
for (const row in sessionIdRes) { for (const row in sessionIdRes) {
if (row !== 'meta' && sessionIdRes[row].session_id != null) { if (row !== 'meta' && sessionIdRes[row].session_id != null) {
@ -83,159 +83,13 @@ export const createUser = async (username: string, password: string, email: stri
return {} as Session; return {} as Session;
}; };
/**
* Checks if the given credentials are valid and creates a new session if they are.
* Returns the session information in case of a successful login
*/
export const login = async (username: string, password: string, ip: string): Promise<Session> => {
let conn;
try {
// Get saved password hash
conn = await pool.getConnection();
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
const userRows = await conn.query(query, username);
let savedHash = '';
let userId = -1;
for (const row in userRows) {
if (row !== 'meta' && userRows[row].user_id != null) {
savedHash = userRows[row].bcrypt_password_hash;
userId = userRows[row].user_id;
}
}
// Check for correct password
if (!bcrypt.compareSync(password, savedHash)) {
// Wrong password, return invalid
return {} as Session;
}
// Password is valid, continue
// Generate + hash session key
const sessionKey = Guid.create().toString();
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
// Update user entry in SQL
const userQuery = 'UPDATE users SET last_login_date = NOW()';
const userIdRes = await conn.query(userQuery);
await conn.commit();
// Create session
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id';
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
await conn.commit();
// Get session id of the created session
let sessionId: number = -1;
for (const row in sessionIdRes) {
if (row !== 'meta' && sessionIdRes[row].session_id != null) {
sessionId = sessionIdRes[row].session_id;
}
}
return {
session_id: sessionId,
session_key: sessionKey,
session_key_hash: '',
last_IP: ip
};
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return {} as Session;
};
/**
* Checks if the given session information are valid and returns the user information if they are
*/
export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User> => {
let conn;
try {
// Get saved session key hash
conn = await pool.getConnection();
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
const sessionRows = await conn.query(query, sessionId);
let savedHash = '';
let userId = -1;
let validUntil = new Date();
for (const row in sessionRows) {
if (row !== 'meta' && sessionRows[row].user_id != null) {
savedHash = sessionRows[row].session_key_hash;
userId = sessionRows[row].user_id;
validUntil = sessionRows[row].validUntil;
}
}
// Check for correct key
if (!bcrypt.compareSync(sessionKey, savedHash)) {
// Wrong key, return invalid
return {} as User;
}
// Key is valid, continue
// Check if the session is still valid
if(validUntil <= new Date()) {
// Session expired, return invalid
return {} as User;
}
// Session still valid, continue
// Update session entry in SQL
const updateSessionsQuery = 'UPDATE sessions SET lastLogin = NOW(), last_IP = ? WHERE session_id = ?';
const updateUsersQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]);
await conn.query(updateUsersQuery, userId);
await conn.commit();
// Get the other required user information and update the user
const userQuery = "SELECT user_id, username, email, registration_date, last_login_date FROM users WHERE user_id = ?";
const userRows = await conn.query(userQuery, userId);
let username = '';
let email = '';
let registrationDate = new Date();
let lastLoginDate = new Date();
for (const row in userRows) {
if (row !== 'meta' && userRows[row].user_id != null) {
username = userRows[row].username;
email = userRows[row].email;
registrationDate = userRows[row].registration_date;
lastLoginDate = userRows[row].last_login_date;
}
}
// Everything is fine, return user information
return {
user_id: userId,
username: username,
email: email,
password_hash: '',
registration_date: registrationDate,
last_login_date: lastLoginDate
};
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return {} as User;
};
/** /**
* Used in the checkUsernameAndEmail method as return value * Used in the checkUsernameAndEmail method as return value
*/ */
export interface Status { export interface Status {
hasProblems: boolean; hasProblems: boolean;
messages: string[]; messages: string[];
codes: number[]; // 0 = all good, 1 = wrong username, 2 = wrong email, 3 = server error, 4 = wrong password, 5 = wrong session codes: number[]; // 0 = all good, 1 = wrong username, 2 = wrong email, 3 = server error
} }
/** /**

View File

@ -20,18 +20,19 @@ export const vendorsRouter = express.Router();
*/ */
// GET items/ // GET items/
vendorsRouter.get('/', async (req: Request, res: Response) => { vendorsRouter.get('/', async (req: Request, res: Response) => {
try { try {
const vendors: Vendors = await VendorService.findAll(); const vendors: Vendors = await VendorService.findAll();
res.status(200).send(vendors); res.status(200).send(vendors);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET items/:id // GET items/:id
vendorsRouter.get('/:id', async (req: Request, res: Response) => { vendorsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
@ -45,12 +46,12 @@ vendorsRouter.get('/:id', async (req: Request, res: Response) => {
res.status(200).send(vendor); res.status(200).send(vendor);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// GET items/:name // GET items/:name
vendorsRouter.get('/search/:term', async (req: Request, res: Response) => { vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
@ -64,7 +65,48 @@ vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
res.status(200).send(vendors); res.status(200).send(vendors);
} catch (e) { } catch (e) {
console.log('Error handling a request: ' + e.message); res.status(404).send(e.message);
res.status(500).send(JSON.stringify({"message": "Internal Server Error. Try again later."}));
} }
}); });
// POST items/
// vendorsRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// vendorsRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// vendorsRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });