API-17: Session Data Endpoint #7

Merged
Paddy merged 3 commits from API-17 into master 2021-08-21 10:58:16 +00:00
4 changed files with 129 additions and 12 deletions
Showing only changes of commit e6401ac28a - Show all commits

View File

@ -2,6 +2,8 @@
* Required External Modules and Interfaces * Required External Modules and Interfaces
*/ */
import express, {Request, Response} from 'express'; import express, {Request, Response} from 'express';
import * as DataService from './data.service';
import * as UserService from '../userService/user.service';
import logger from '../../../middleware/logger'; import logger from '../../../middleware/logger';
/** /**
@ -9,18 +11,32 @@ import logger from '../../../middleware/logger';
*/ */
export const dataRouter = express.Router(); export const dataRouter = express.Router();
dataRouter.get('/', async (req: Request, res: Response) => { dataRouter.get('/user/:isDevCall', async (req: Request, res: Response) => {
try { try {
res.status(200).send('GET data'); let userId = (req.query.userId ?? '').toString();
} catch (e) { let sessionId = (req.query.sessionId ?? '').toString();
logger.error('Error handling a request: ' + e.message); let sessionKey = (req.query.sessionKey ?? '').toString();
res.status(500).send({'message': 'Internal Server Error. Try again later.'}); let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
}
});
dataRouter.post('/', async (req: Request, res: Response) => { if (userId === '' || sessionId === '' || sessionKey === '') {
try { res.status(400).send({
res.status(200).send('POST data'); 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters'
});
return;
}
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({
'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid'
});
return;
}
let data = await DataService.getUserData(useDev, userId);
res.status(200).send(data);
} catch (e) { } catch (e) {
logger.error('Error handling a request: ' + e.message); logger.error('Error handling a request: ' + e.message);
res.status(500).send({'message': 'Internal Server Error. Try again later.'}); res.status(500).send({'message': 'Internal Server Error. Try again later.'});

View File

@ -0,0 +1,75 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Used in the getUserData method as return value
*/
export interface UserData {
username: string;
email: string;
firstName: string;
lastName: string;
lastLogin: string;
emailIsVerified: string;
isPremiumUser: string;
}
/**
* Returns all data about the given user
* @param useDev If the dev or prod database should be used
* @param userId The userId of the user to return the data for
* @return UserData An object containing the user data
*/
export const getUserData = async (useDev: boolean, userId: string): Promise<UserData> => {
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT username, email, first_name, last_Name, last_login, email_is_verified, is_premium_user FROM users WHERE user_id = ?', userId);
let user: UserData = {} as UserData;
for (let row in rows) {
if (row !== 'meta') {
user = {
username: rows[row].username,
email: rows[row].email,
firstName: rows[row].first_name,
lastName: rows[row].last_name,
lastLogin: rows[row].last_login,
emailIsVerified: rows[row].email_is_verified,
isPremiumUser: rows[row].is_premium_user
};
}
}
return user;
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
};

View File

@ -14,8 +14,6 @@ loginRouter.post('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let username: string = ''; let username: string = '';
let email: string = ''; let email: string = '';
let firstName: string = '';
let lastName: string = '';
let password: string = ''; let password: string = '';
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD

View File

@ -298,3 +298,31 @@ export const checkUsernameAndEmail = async (useDev: boolean, username: string, e
} }
} }
}; };
export const checkSession = async (useDev: boolean, userId: string, sessionId: string, sessionKey: string): Promise<boolean> => {
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]);
let savedHash = '';
for (let row in rows) {
if (row !== 'meta') {
savedHash = rows[row].session_key_hash;
}
}
return bcrypt.compareSync(sessionKey, savedHash);
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
};