This commit is contained in:
parent
eeace68b7b
commit
fc65474930
71
app.ts
71
app.ts
|
@ -18,8 +18,8 @@ let cors = require('cors');
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
if (!process.env.PORT) {
|
if (!process.env.PORT) {
|
||||||
logger.error('No port');
|
logger.error('No port');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const port: number = parseInt(process.env.PORT, 10);
|
const port: number = parseInt(process.env.PORT, 10);
|
||||||
|
@ -30,40 +30,57 @@ const server: http.Server = http.createServer(app);
|
||||||
// here we are adding middleware to parse all incoming requests as JSON
|
// here we are adding middleware to parse all incoming requests as JSON
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
// Use CORS
|
// Configure CORS
|
||||||
app.use(cors());
|
let allowedHosts = [
|
||||||
|
'https://rapla.p4ddy.com',
|
||||||
|
'https://betterzon.p4ddy.com'
|
||||||
|
];
|
||||||
|
app.use(cors({
|
||||||
|
origin: function (origin: any, callback: any) {
|
||||||
|
// Allow requests with no origin
|
||||||
|
if (!origin) return callback(null, true);
|
||||||
|
|
||||||
|
// Block requests with wrong origin
|
||||||
|
if (allowedHosts.indexOf(origin) === -1) {
|
||||||
|
return callback(new Error('The CORS policy doesn\'t allow access for your origin.'), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow all other requests
|
||||||
|
return callback(null, true);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
// Swagger documentation
|
// Swagger documentation
|
||||||
const swaggerDefinition = {
|
const swaggerDefinition = {
|
||||||
openapi: '3.0.0',
|
openapi: '3.0.0',
|
||||||
info: {
|
info: {
|
||||||
title: 'Pluto Development REST API',
|
title: 'Pluto Development REST API',
|
||||||
version: '2.0.0',
|
version: '2.0.0',
|
||||||
license: {
|
license: {
|
||||||
name: 'Licensed Under MIT',
|
name: 'Licensed Under MIT',
|
||||||
url: 'https://spdx.org/licenses/MIT.html'
|
url: 'https://spdx.org/licenses/MIT.html'
|
||||||
},
|
},
|
||||||
contact: {
|
contact: {
|
||||||
name: 'Pluto Development',
|
name: 'Pluto Development',
|
||||||
url: 'https://www.pluto-development.de'
|
url: 'https://www.pluto-development.de'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const options = {
|
const options = {
|
||||||
swaggerDefinition,
|
swaggerDefinition,
|
||||||
// Paths to files containing OpenAPI definitions
|
// Paths to files containing OpenAPI definitions
|
||||||
apis: [
|
apis: [
|
||||||
'./src/models/**/*.router.ts'
|
'./src/models/**/*.router.ts'
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const swaggerSpec = swaggerJSDoc(options);
|
const swaggerSpec = swaggerJSDoc(options);
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
'/docs',
|
'/docs',
|
||||||
swaggerUi.serve,
|
swaggerUi.serve,
|
||||||
swaggerUi.setup(swaggerSpec)
|
swaggerUi.setup(swaggerSpec)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Add routers
|
// Add routers
|
||||||
|
@ -77,9 +94,9 @@ app.use('/crr', crrRouter);
|
||||||
|
|
||||||
// this is a simple route to make sure everything is working properly
|
// this is a simple route to make sure everything is working properly
|
||||||
app.get('/', (req: express.Request, res: express.Response) => {
|
app.get('/', (req: express.Request, res: express.Response) => {
|
||||||
res.status(200).send('Welcome to the Pluto Development REST API V2!');
|
res.status(200).send('Welcome to the Pluto Development REST API V2!');
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(port, () => {
|
server.listen(port, () => {
|
||||||
logger.info('Server listening on Port ' + port);
|
logger.info('Server listening on Port ' + port);
|
||||||
});
|
});
|
||||||
|
|
|
@ -21,51 +21,49 @@ dotenv.config();
|
||||||
* Creates a user record in the database, also creates a session. Returns the session if successful.
|
* Creates a user record in the database, also creates a session. Returns the session if successful.
|
||||||
*/
|
*/
|
||||||
export const createUser = async (username: string, password: string, email: string, ip: string): Promise<Session> => {
|
export const createUser = async (username: string, password: string, email: string, ip: string): Promise<Session> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
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(password, 10);
|
||||||
const sessionKey = Guid.create().toString();
|
const sessionKey = Guid.create().toString();
|
||||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
||||||
|
|
||||||
// Create user entry in SQL
|
// Create user entry in SQL
|
||||||
const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id';
|
const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id';
|
||||||
const userIdRes = await conn.query(userQuery, [username, email, pwHash]);
|
const userIdRes = await conn.query(userQuery, [username, email, pwHash]);
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
// Get user id of the created user
|
// Get user id of the created user
|
||||||
let userId: number = -1;
|
let userId: number = -1;
|
||||||
for (const row in userIdRes) {
|
for (const row in userIdRes) {
|
||||||
if (row !== 'meta' && userIdRes[row].user_id != null) {
|
if (row !== 'meta' && userIdRes[row].user_id != null) {
|
||||||
userId = userIdRes[row].user_id;
|
userId = userIdRes[row].user_id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create session
|
// 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 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]);
|
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 session
|
||||||
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) {
|
||||||
sessionId = sessionIdRes[row].session_id;
|
sessionId = sessionIdRes[row].session_id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
session_id: sessionId,
|
session_id: sessionId,
|
||||||
session_key: sessionKey,
|
session_key: sessionKey,
|
||||||
session_key_hash: 'HIDDEN',
|
session_key_hash: 'HIDDEN',
|
||||||
last_IP: ip
|
last_IP: ip
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {} as Session;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -73,136 +71,134 @@ export const createUser = async (username: string, password: string, email: stri
|
||||||
* Returns the session information in case of a successful login
|
* Returns the session information in case of a successful login
|
||||||
*/
|
*/
|
||||||
export const login = async (username: string, password: string, ip: string): Promise<Session> => {
|
export const login = async (username: string, password: string, ip: string): Promise<Session> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
try {
|
try {
|
||||||
// Get saved password hash
|
// Get saved password hash
|
||||||
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
|
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
|
||||||
const userRows = await conn.query(query, username);
|
const userRows = await conn.query(query, username);
|
||||||
let savedHash = '';
|
let savedHash = '';
|
||||||
let userId = -1;
|
let userId = -1;
|
||||||
for (const row in userRows) {
|
for (const row in userRows) {
|
||||||
if (row !== 'meta' && userRows[row].user_id != null) {
|
if (row !== 'meta' && userRows[row].user_id != null) {
|
||||||
savedHash = userRows[row].bcrypt_password_hash;
|
savedHash = userRows[row].bcrypt_password_hash;
|
||||||
userId = userRows[row].user_id;
|
userId = userRows[row].user_id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for correct password
|
// Check for correct password
|
||||||
if (!bcrypt.compareSync(password, savedHash)) {
|
if (!bcrypt.compareSync(password, savedHash)) {
|
||||||
// Wrong password, return invalid
|
// Wrong password, return invalid
|
||||||
return {} as Session;
|
return {} as Session;
|
||||||
}
|
}
|
||||||
// Password is valid, continue
|
// Password is valid, continue
|
||||||
|
|
||||||
// Generate + hash session key
|
// Generate + hash session key
|
||||||
const sessionKey = Guid.create().toString();
|
const sessionKey = Guid.create().toString();
|
||||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
||||||
|
|
||||||
// Update user entry in SQL
|
// Update user entry in SQL
|
||||||
const userQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
|
const userQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
|
||||||
const userIdRes = await conn.query(userQuery, userId);
|
const userIdRes = await conn.query(userQuery, userId);
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
// Create session
|
// 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 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]);
|
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 session
|
||||||
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) {
|
||||||
sessionId = sessionIdRes[row].session_id;
|
sessionId = sessionIdRes[row].session_id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
session_id: sessionId,
|
session_id: sessionId,
|
||||||
session_key: sessionKey,
|
session_key: sessionKey,
|
||||||
session_key_hash: 'HIDDEN',
|
session_key_hash: 'HIDDEN',
|
||||||
last_IP: ip
|
last_IP: ip
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {} as Session;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the given session information are valid and returns the user information if they are
|
* 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> => {
|
export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
try {
|
try {
|
||||||
// Get saved session key hash
|
// Get saved session key hash
|
||||||
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
|
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
|
||||||
const sessionRows = await conn.query(query, sessionId);
|
const sessionRows = await conn.query(query, sessionId);
|
||||||
let savedHash = '';
|
let savedHash = '';
|
||||||
let userId = -1;
|
let userId = -1;
|
||||||
let validUntil = new Date();
|
let validUntil = new Date();
|
||||||
for (const row in sessionRows) {
|
for (const row in sessionRows) {
|
||||||
if (row !== 'meta' && sessionRows[row].user_id != null) {
|
if (row !== 'meta' && sessionRows[row].user_id != null) {
|
||||||
savedHash = sessionRows[row].session_key_hash;
|
savedHash = sessionRows[row].session_key_hash;
|
||||||
userId = sessionRows[row].user_id;
|
userId = sessionRows[row].user_id;
|
||||||
validUntil = sessionRows[row].validUntil;
|
validUntil = sessionRows[row].validUntil;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for correct key
|
// Check for correct key
|
||||||
if (!bcrypt.compareSync(sessionKey, savedHash)) {
|
if (!bcrypt.compareSync(sessionKey, savedHash)) {
|
||||||
// Wrong key, return invalid
|
// Wrong key, return invalid
|
||||||
return {} as User;
|
return {} as User;
|
||||||
}
|
}
|
||||||
// Key is valid, continue
|
// Key is valid, continue
|
||||||
|
|
||||||
// Check if the session is still valid
|
// Check if the session is still valid
|
||||||
if (validUntil <= new Date()) {
|
if (validUntil <= new Date()) {
|
||||||
// Session expired, return invalid
|
// Session expired, return invalid
|
||||||
return {} as User;
|
return {} as User;
|
||||||
}
|
}
|
||||||
// Session still valid, continue
|
// Session still valid, continue
|
||||||
|
|
||||||
// Update session entry in SQL
|
// Update session entry in SQL
|
||||||
const updateSessionsQuery = 'UPDATE sessions SET lastLogin = NOW(), last_IP = ? WHERE session_id = ?';
|
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 updateUsersQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
|
||||||
const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]);
|
const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]);
|
||||||
await conn.query(updateUsersQuery, userId);
|
await conn.query(updateUsersQuery, userId);
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
// Get the other required user information and update the user
|
// Get the other required user information and update the user
|
||||||
const userQuery = 'SELECT user_id, username, email, registration_date, last_login_date, is_admin FROM users WHERE user_id = ?';
|
const userQuery = 'SELECT user_id, username, email, registration_date, last_login_date, is_admin FROM users WHERE user_id = ?';
|
||||||
const userRows = await conn.query(userQuery, userId);
|
const userRows = await conn.query(userQuery, userId);
|
||||||
let username = '';
|
let username = '';
|
||||||
let email = '';
|
let email = '';
|
||||||
let registrationDate = new Date();
|
let registrationDate = new Date();
|
||||||
let lastLoginDate = new Date();
|
let lastLoginDate = new Date();
|
||||||
let is_admin = false;
|
let is_admin = false;
|
||||||
for (const row in userRows) {
|
for (const row in userRows) {
|
||||||
if (row !== 'meta' && userRows[row].user_id != null) {
|
if (row !== 'meta' && userRows[row].user_id != null) {
|
||||||
username = userRows[row].username;
|
username = userRows[row].username;
|
||||||
email = userRows[row].email;
|
email = userRows[row].email;
|
||||||
registrationDate = userRows[row].registration_date;
|
registrationDate = userRows[row].registration_date;
|
||||||
lastLoginDate = userRows[row].last_login_date;
|
lastLoginDate = userRows[row].last_login_date;
|
||||||
is_admin = userRows[row].is_admin;
|
is_admin = userRows[row].is_admin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Everything is fine, return user information
|
// Everything is fine, return user information
|
||||||
return {
|
return {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
username: username,
|
username: username,
|
||||||
email: email,
|
email: email,
|
||||||
password_hash: 'HIDDEN',
|
password_hash: 'HIDDEN',
|
||||||
registration_date: registrationDate,
|
registration_date: registrationDate,
|
||||||
last_login_date: lastLoginDate,
|
last_login_date: lastLoginDate,
|
||||||
is_admin: is_admin
|
is_admin: is_admin
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -211,21 +207,21 @@ export const checkSession = async (sessionId: string, sessionKey: string, ip: st
|
||||||
* @param ip The users IP address
|
* @param ip The users IP address
|
||||||
*/
|
*/
|
||||||
export const checkSessionWithCookie = async (cookie: any, ip: string): Promise<User> => {
|
export const checkSessionWithCookie = async (cookie: any, ip: string): Promise<User> => {
|
||||||
const parsedCookie = JSON.parse(cookie);
|
const parsedCookie = JSON.parse(cookie);
|
||||||
const session_id = parsedCookie.id;
|
const session_id = parsedCookie.id;
|
||||||
const session_key = parsedCookie.key;
|
const session_key = parsedCookie.key;
|
||||||
|
|
||||||
|
|
||||||
return checkSession(session_id, session_key, '');
|
return checkSession(session_id, session_key, '');
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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, 4 = wrong password, 5 = wrong session
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -234,53 +230,53 @@ export interface Status {
|
||||||
* @param email The email to check
|
* @param email The email to check
|
||||||
*/
|
*/
|
||||||
export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => {
|
export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
try {
|
try {
|
||||||
// Create user entry in SQL
|
// Create user entry in SQL
|
||||||
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
|
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
|
||||||
const emailQuery = 'SELECT email FROM users WHERE email = ?';
|
const emailQuery = 'SELECT email FROM users WHERE email = ?';
|
||||||
const usernameRes = await conn.query(usernameQuery, username);
|
const usernameRes = await conn.query(usernameQuery, username);
|
||||||
const emailRes = await conn.query(emailQuery, email);
|
const emailRes = await conn.query(emailQuery, email);
|
||||||
|
|
||||||
let res: Status = {
|
let res: Status = {
|
||||||
hasProblems: false,
|
hasProblems: false,
|
||||||
messages: [],
|
messages: [],
|
||||||
codes: []
|
codes: []
|
||||||
};
|
};
|
||||||
|
|
||||||
const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long
|
const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long
|
||||||
if (!usernameRegex.test(username)) {
|
if (!usernameRegex.test(username)) {
|
||||||
// Username doesn't match requirements
|
// Username doesn't match requirements
|
||||||
res.hasProblems = true;
|
res.hasProblems = true;
|
||||||
res.messages.push('Invalid username');
|
res.messages.push('Invalid username');
|
||||||
res.codes.push(1);
|
res.codes.push(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@betterzon.xyz
|
const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@betterzon.xyz
|
||||||
if (!emailRegex.test(email)) {
|
if (!emailRegex.test(email)) {
|
||||||
// Username doesn't match requirements
|
// Username doesn't match requirements
|
||||||
res.hasProblems = true;
|
res.hasProblems = true;
|
||||||
res.messages.push('Invalid email');
|
res.messages.push('Invalid email');
|
||||||
res.codes.push(2);
|
res.codes.push(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (usernameRes.length > 0) {
|
if (usernameRes.length > 0) {
|
||||||
// Username is a duplicate
|
// Username is a duplicate
|
||||||
res.hasProblems = true;
|
res.hasProblems = true;
|
||||||
res.messages.push('Duplicate username');
|
res.messages.push('Duplicate username');
|
||||||
res.codes.push(1);
|
res.codes.push(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (emailRes.length > 0) {
|
if (emailRes.length > 0) {
|
||||||
// Email is a duplicate
|
// Email is a duplicate
|
||||||
res.hasProblems = true;
|
res.hasProblems = true;
|
||||||
res.messages.push('Duplicate email');
|
res.messages.push('Duplicate email');
|
||||||
res.codes.push(2);
|
res.codes.push(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
198
src/models/betterzon/vendors/vendors.service.ts
vendored
198
src/models/betterzon/vendors/vendors.service.ts
vendored
|
@ -18,41 +18,41 @@ dotenv.config();
|
||||||
* Fetches and returns all known vendors
|
* Fetches and returns all known vendors
|
||||||
*/
|
*/
|
||||||
export const findAll = async (): Promise<Vendors> => {
|
export const findAll = async (): Promise<Vendors> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
let vendorRows = [];
|
let vendorRows = [];
|
||||||
try {
|
try {
|
||||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE isActive = true');
|
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE isActive = true');
|
||||||
for (let row in rows) {
|
for (let row in rows) {
|
||||||
if (row !== 'meta') {
|
if (row !== 'meta') {
|
||||||
let vendor: Vendor = {
|
let vendor: Vendor = {
|
||||||
city: '',
|
city: '',
|
||||||
country_code: '',
|
country_code: '',
|
||||||
name: '',
|
name: '',
|
||||||
phone: '',
|
phone: '',
|
||||||
streetname: '',
|
streetname: '',
|
||||||
vendor_id: 0,
|
vendor_id: 0,
|
||||||
website: '',
|
website: '',
|
||||||
zip_code: ''
|
zip_code: ''
|
||||||
};
|
};
|
||||||
const sqlVendor = rows[row];
|
const sqlVendor = rows[row];
|
||||||
|
|
||||||
vendor.vendor_id = sqlVendor.vendor_id;
|
vendor.vendor_id = sqlVendor.vendor_id;
|
||||||
vendor.name = sqlVendor.name;
|
vendor.name = sqlVendor.name;
|
||||||
vendor.streetname = sqlVendor.streetname;
|
vendor.streetname = sqlVendor.streetname;
|
||||||
vendor.zip_code = sqlVendor.zip_code;
|
vendor.zip_code = sqlVendor.zip_code;
|
||||||
vendor.city = sqlVendor.city;
|
vendor.city = sqlVendor.city;
|
||||||
vendor.country_code = sqlVendor.country_code;
|
vendor.country_code = sqlVendor.country_code;
|
||||||
vendor.phone = sqlVendor.phone;
|
vendor.phone = sqlVendor.phone;
|
||||||
vendor.website = sqlVendor.website;
|
vendor.website = sqlVendor.website;
|
||||||
vendorRows.push(vendor);
|
vendorRows.push(vendor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return vendorRows;
|
return vendorRows;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -60,21 +60,21 @@ export const findAll = async (): Promise<Vendors> => {
|
||||||
* @param id The id of the vendor to fetch
|
* @param id The id of the vendor to fetch
|
||||||
*/
|
*/
|
||||||
export const find = async (id: number): Promise<Vendor> => {
|
export const find = async (id: number): Promise<Vendor> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
let vendor: any;
|
let vendor: any;
|
||||||
try {
|
try {
|
||||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE vendor_id = ? AND isActive = true', id);
|
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE vendor_id = ? AND isActive = true', id);
|
||||||
for (let row in rows) {
|
for (let row in rows) {
|
||||||
if (row !== 'meta') {
|
if (row !== 'meta') {
|
||||||
vendor = rows[row];
|
vendor = rows[row];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return vendor;
|
return vendor;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -82,22 +82,22 @@ export const find = async (id: number): Promise<Vendor> => {
|
||||||
* @param term the term to match
|
* @param term the term to match
|
||||||
*/
|
*/
|
||||||
export const findBySearchTerm = async (term: string): Promise<Vendors> => {
|
export const findBySearchTerm = async (term: string): Promise<Vendors> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
let vendorRows = [];
|
let vendorRows = [];
|
||||||
try {
|
try {
|
||||||
term = '%' + term + '%';
|
term = '%' + term + '%';
|
||||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE name LIKE ? AND isActive = true', term);
|
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE name LIKE ? AND isActive = true', term);
|
||||||
for (let row in rows) {
|
for (let row in rows) {
|
||||||
if (row !== 'meta') {
|
if (row !== 'meta') {
|
||||||
vendorRows.push(rows[row]);
|
vendorRows.push(rows[row]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return vendorRows;
|
return vendorRows;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -105,21 +105,21 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
|
||||||
* @param user The user to return the managed shops for
|
* @param user The user to return the managed shops for
|
||||||
*/
|
*/
|
||||||
export const getManagedShops = async (user_id: number): Promise<Vendors> => {
|
export const getManagedShops = async (user_id: number): Promise<Vendors> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
let vendorRows = [];
|
let vendorRows = [];
|
||||||
try {
|
try {
|
||||||
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE admin_id LIKE ?', user_id);
|
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE admin_id LIKE ?', user_id);
|
||||||
for (let row in rows) {
|
for (let row in rows) {
|
||||||
if (row !== 'meta') {
|
if (row !== 'meta') {
|
||||||
vendorRows.push(rows[row]);
|
vendorRows.push(rows[row]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return vendorRows;
|
return vendorRows;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -129,22 +129,20 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
|
||||||
* @param product_id The product id of the product to deactivate the listing for
|
* @param product_id The product id of the product to deactivate the listing for
|
||||||
*/
|
*/
|
||||||
export const deactivateListing = async (user_id: number, vendor_id: number, product_id: number): Promise<Boolean> => {
|
export const deactivateListing = async (user_id: number, vendor_id: number, product_id: number): Promise<Boolean> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
try {
|
try {
|
||||||
// Check if the user is authorized to manage the requested vendor
|
// Check if the user is authorized to manage the requested vendor
|
||||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||||
if (user_vendor_rows.length !== 1) {
|
if (user_vendor_rows.length !== 1) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const status = await conn.query('UPDATE prices SET active_listing = false WHERE vendor_id = ? and product_id = ?', [vendor_id, product_id]);
|
const status = await conn.query('UPDATE prices SET active_listing = false WHERE vendor_id = ? and product_id = ?', [vendor_id, product_id]);
|
||||||
|
|
||||||
return status.affectedRows > 0;
|
return status.affectedRows > 0;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -154,21 +152,19 @@ export const deactivateListing = async (user_id: number, vendor_id: number, prod
|
||||||
* @param isActive The new active state
|
* @param isActive The new active state
|
||||||
*/
|
*/
|
||||||
export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => {
|
export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => {
|
||||||
let conn = BetterzonDB.getConnection();
|
let conn = BetterzonDB.getConnection();
|
||||||
try {
|
try {
|
||||||
// Check if the user is authorized to manage the requested vendor
|
// Check if the user is authorized to manage the requested vendor
|
||||||
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
|
||||||
if (user_vendor_rows.length !== 1) {
|
if (user_vendor_rows.length !== 1) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the vendor state
|
// Update the vendor state
|
||||||
const status = await conn.query('UPDATE vendors SET isActive = ? WHERE vendor_id = ?', [isActive, vendor_id]);
|
const status = await conn.query('UPDATE vendors SET isActive = ? WHERE vendor_id = ?', [isActive, vendor_id]);
|
||||||
|
|
||||||
return status.affectedRows > 0;
|
return status.affectedRows > 0;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
|
||||||
};
|
};
|
||||||
|
|
|
@ -14,7 +14,6 @@ export const eventRouter = express.Router();
|
||||||
|
|
||||||
eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
|
eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
throw new Error('Test');
|
|
||||||
let userId = (req.query.userId ?? '').toString();
|
let userId = (req.query.userId ?? '').toString();
|
||||||
let sessionId = (req.query.sessionId ?? '').toString();
|
let sessionId = (req.query.sessionId ?? '').toString();
|
||||||
let sessionKey = (req.query.sessionKey ?? '').toString();
|
let sessionKey = (req.query.sessionKey ?? '').toString();
|
||||||
|
|
Loading…
Reference in New Issue
Block a user