diff --git a/args/schema.sql b/args/schema.sql index 78610df..ed8d0d5 100644 --- a/args/schema.sql +++ b/args/schema.sql @@ -8,10 +8,11 @@ PRIMARY KEY(floID) ); CREATE TABLE Sessions ( +id INT NOT NULL AUTO_INCREMENT, floID CHAR(34) NOT NULL, proxyKey CHAR(66) NOT NULL, -session_id VARCHAR(100) UNIQUE, session_time DATETIME DEFAULT CURRENT_TIMESTAMP, +KEY (id), PRIMARY KEY(floID), FOREIGN KEY (floID) REFERENCES Users(floID) ); @@ -129,8 +130,7 @@ tag VARCHAR(50) NOT NULL, sellPriority INT, buyPriority INT, api TINYTEXT, -PRIMARY KEY(tag), -KEY (id) +PRIMARY KEY(tag) ); CREATE TABLE Tags ( @@ -184,6 +184,13 @@ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(t_name, id) ); +CREATE TRIGGER Sessions_I AFTER INSERT ON Sessions +FOR EACH ROW INSERT INTO _backup (t_name, id) VALUES ('Sessions', NEW.id) ON DUPLICATE KEY UPDATE mode=TRUE, timestamp=DEFAULT; +CREATE TRIGGER Sessions_U AFTER UPDATE ON Sessions +FOR EACH ROW INSERT INTO _backup (t_name, id) VALUES ('Sessions', NEW.id) ON DUPLICATE KEY UPDATE mode=TRUE, timestamp=DEFAULT; +CREATE TRIGGER Sessions_D AFTER DELETE ON Sessions +FOR EACH ROW INSERT INTO _backup (t_name, id) VALUES ('Sessions', OLD.id) ON DUPLICATE KEY UPDATE mode=NULL, timestamp=DEFAULT; + CREATE TRIGGER Cash_I AFTER INSERT ON Cash FOR EACH ROW INSERT INTO _backup (t_name, id) VALUES ('Cash', NEW.id) ON DUPLICATE KEY UPDATE mode=TRUE, timestamp=DEFAULT; CREATE TRIGGER Cash_U AFTER UPDATE ON Cash diff --git a/public/fn.js b/public/fn.js index f288367..85b8678 100644 --- a/public/fn.js +++ b/public/fn.js @@ -1,4 +1,24 @@ //console.log(document.cookie.toString()); +var nodeList, nodeURL, nodeKBucket; //Container for (backup) node list + +function exchangeAPI(api, options) { + return new Promise((resolve, reject) => { + let curPos = exchangeAPI.curPos || 0; + if (curPos >= nodeList.length) + return resolve('No Nodes online'); + let url = nodeURL[nodeList[curPos]]; + (options ? fetch(url + api, options) : fetch(url + api)) + .then(result => resolve(result)).catch(error => { + console.debug(error); + console.warn(nodeList[curPos], 'is offline'); + //try next node + exchangeAPI.curPos = curPos + 1; + exchangeAPI(api, options) + .then(result => resolve(result)) + .catch(error => reject(error)) + }); + }) +} const tokenAPI = { fetch_api: function(apicall) { @@ -74,10 +94,25 @@ function responseParse(response, json_ = true) { }); } -function getAccount() { +function getAccount(floID, proxySecret) { return new Promise((resolve, reject) => { - fetch('/account') - .then(result => responseParse(result) + let request = { + floID: floID, + timestamp: Date.now() + }; + request.sign = signRequest({ + type: "get_account", + timestamp: data.timestamp + }, proxySecret); + console.debug(request); + + exchangeAPI('/account', { + method: "POST", + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(request) + }).then(result => responseParse(result) .then(result => resolve(result)) .catch(error => reject(error))) .catch(error => reject(error)); @@ -86,7 +121,7 @@ function getAccount() { function getBuyList() { return new Promise((resolve, reject) => { - fetch('/list-buyorders') + exchangeAPI('/list-buyorders') .then(result => responseParse(result) .then(result => resolve(result)) .catch(error => reject(error))) @@ -96,7 +131,7 @@ function getBuyList() { function getSellList() { return new Promise((resolve, reject) => { - fetch('/list-sellorders') + exchangeAPI('/list-sellorders') .then(result => responseParse(result) .then(result => resolve(result)) .catch(error => reject(error))) @@ -106,7 +141,7 @@ function getSellList() { function getTransactionList() { return new Promise((resolve, reject) => { - fetch('/list-transactions') + exchangeAPI('/list-transactions') .then(result => responseParse(result) .then(result => resolve(result)) .catch(error => reject(error))) @@ -116,7 +151,7 @@ function getTransactionList() { function getRate() { return new Promise((resolve, reject) => { - fetch('/get-rate') + exchangeAPI('/get-rate') .then(result => responseParse(result, false) .then(result => resolve(result)) .catch(error => reject(error))) @@ -131,21 +166,35 @@ function signRequest(request, privKey) { return floCrypto.signData(req_str, privKey); } -function signUp(privKey, sid) { +function getLoginCode() { return new Promise((resolve, reject) => { + exchangeAPI('/list-buyorders') + .then(result => responseParse(result) + .then(result => resolve(result)) + .catch(error => reject(error))) + .catch(error => reject(error)); + }) +} + +function signUp(privKey, code, hash) { + return new Promise((resolve, reject) => { + if (!code || !hash) + return reject("Login Code missing") let request = { pubKey: floCrypto.getPubKeyHex(privKey), floID: floCrypto.getFloID(privKey), + code: code, + hash: hash, timestamp: Date.now() }; request.sign = signRequest({ type: "create_account", - random: sid, + random: code, timestamp: request.timestamp }, privKey); console.debug(request); - fetch("/signup", { + exchangeAPI("/signup", { method: "POST", headers: { 'Content-Type': 'application/json' @@ -158,25 +207,28 @@ function signUp(privKey, sid) { }); } -function login(privKey, proxyKey, sid, rememberMe = false) { +function login(privKey, proxyKey, code, hash) { return new Promise((resolve, reject) => { + if (!code || !hash) + return reject("Login Code missing") let request = { proxyKey: proxyKey, floID: floCrypto.getFloID(privKey), timestamp: Date.now(), - saveSession: rememberMe + code: code, + hash: hash }; if (!privKey || !request.floID) return reject("Invalid Private key"); request.sign = signRequest({ type: "login", - random: sid, - proxyKey: request.proxyKey, + random: code, + proxyKey: proxyKey, timestamp: request.timestamp }, privKey); console.debug(request); - fetch("/login", { + exchangeAPI("/login", { method: "POST", headers: { 'Content-Type': 'application/json' @@ -189,23 +241,39 @@ function login(privKey, proxyKey, sid, rememberMe = false) { }) } -function logout() { +function logout(floID, proxySecret) { return new Promise((resolve, reject) => { - fetch("/logout") - .then(result => responseParse(result, false) + let request = { + floID: floID, + timestamp: Date.now() + }; + request.sign = signRequest({ + type: "logout", + timestamp: data.timestamp + }, proxySecret); + console.debug(request); + + exchangeAPI("/logout", { + method: "POST", + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(request) + }).then(result => responseParse(result, false) .then(result => resolve(result)) .catch(error => reject(error))) .catch(error => reject(error)) }) } -function buy(quantity, max_price, proxySecret) { +function buy(quantity, max_price, floID, proxySecret) { return new Promise((resolve, reject) => { if (typeof quantity !== "number" || quantity <= 0) return reject(`Invalid quantity (${quantity})`); else if (typeof max_price !== "number" || max_price <= 0) return reject(`Invalid max_price (${max_price})`); let request = { + floID: floID, quantity: quantity, max_price: max_price, timestamp: Date.now() @@ -218,7 +286,7 @@ function buy(quantity, max_price, proxySecret) { }, proxySecret); console.debug(request); - fetch('/buy', { + exchangeAPI('/buy', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -232,13 +300,14 @@ function buy(quantity, max_price, proxySecret) { } -function sell(quantity, min_price, proxySecret) { +function sell(quantity, min_price, floID, proxySecret) { return new Promise((resolve, reject) => { if (typeof quantity !== "number" || quantity <= 0) return reject(`Invalid quantity (${quantity})`); else if (typeof min_price !== "number" || min_price <= 0) return reject(`Invalid min_price (${min_price})`); let request = { + floID: floID, quantity: quantity, min_price: min_price, timestamp: Date.now() @@ -251,7 +320,7 @@ function sell(quantity, min_price, proxySecret) { }, proxySecret); console.debug(request); - fetch('/sell', { + exchangeAPI('/sell', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -265,11 +334,12 @@ function sell(quantity, min_price, proxySecret) { } -function cancelOrder(type, id, proxySecret) { +function cancelOrder(type, id, floID, proxySecret) { return new Promise((resolve, reject) => { if (type !== "buy" && type !== "sell") return reject(`Invalid type (${type}): type should be sell (or) buy`); let request = { + floID: floID, orderType: type, orderID: id, timestamp: Date.now() @@ -282,7 +352,7 @@ function cancelOrder(type, id, proxySecret) { }, proxySecret); console.debug(request); - fetch('/cancel', { + exchangeAPI('/cancel', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -295,12 +365,13 @@ function cancelOrder(type, id, proxySecret) { }) } -function depositFLO(quantity, userID, privKey, proxySecret) { +function depositFLO(quantity, floID, privKey, proxySecret) { return new Promise((resolve, reject) => { if (typeof quantity !== "number" || quantity <= floGlobals.fee) return reject(`Invalid quantity (${quantity})`); - floBlockchainAPI.sendTx(userID, floGlobals.adminID, quantity, privKey, 'Deposit FLO in market').then(txid => { + floBlockchainAPI.sendTx(floID, floGlobals.adminID, quantity, privKey, 'Deposit FLO in market').then(txid => { let request = { + floID: floID, txid: txid, timestamp: Date.now() }; @@ -311,7 +382,7 @@ function depositFLO(quantity, userID, privKey, proxySecret) { }, proxySecret); console.debug(request); - fetch('/deposit-flo', { + exchangeAPI('/deposit-flo', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -325,9 +396,10 @@ function depositFLO(quantity, userID, privKey, proxySecret) { }) } -function withdrawFLO(quantity, proxySecret) { +function withdrawFLO(quantity, floID, proxySecret) { return new Promise((resolve, reject) => { let request = { + floID: floID, amount: quantity, timestamp: Date.now() }; @@ -338,7 +410,7 @@ function withdrawFLO(quantity, proxySecret) { }, proxySecret); console.debug(request); - fetch('/withdraw-flo', { + exchangeAPI('/withdraw-flo', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -351,12 +423,13 @@ function withdrawFLO(quantity, proxySecret) { }) } -function depositRupee(quantity, userID, privKey, proxySecret) { +function depositRupee(quantity, floID, privKey, proxySecret) { return new Promise((resolve, reject) => { - if (!floCrypto.verifyPrivKey(privKey, userID)) + if (!floCrypto.verifyPrivKey(privKey, floID)) return reject("Invalid Private Key"); tokenAPI.sendToken(privKey, quantity, 'Deposit Rupee in market').then(txid => { let request = { + floID: floID, txid: txid, timestamp: Date.now() }; @@ -367,7 +440,7 @@ function depositRupee(quantity, userID, privKey, proxySecret) { }, proxySecret); console.debug(request); - fetch('/deposit-rupee', { + exchangeAPI('/deposit-rupee', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -381,9 +454,10 @@ function depositRupee(quantity, userID, privKey, proxySecret) { }) } -function withdrawRupee(quantity, proxySecret) { +function withdrawRupee(quantity, floID, proxySecret) { return new Promise((resolve, reject) => { let request = { + floID: floID, amount: quantity, timestamp: Date.now() }; @@ -394,7 +468,7 @@ function withdrawRupee(quantity, proxySecret) { }, proxySecret); console.debug(request); - fetch('/withdraw-rupee', { + exchangeAPI('/withdraw-rupee', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -407,10 +481,11 @@ function withdrawRupee(quantity, proxySecret) { }) } -function addUserTag(floID, tag, proxySecret) { +function addUserTag(tag_user, tag, floID, proxySecret) { return new Promise((resolve, reject) => { let request = { - user: floID, + floID: floID, + user: tag_user, tag: tag, timestamp: Date.now() }; @@ -422,7 +497,7 @@ function addUserTag(floID, tag, proxySecret) { }, proxySecret); console.debug(request); - fetch('/add-tag', { + exchangeAPI('/add-tag', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -435,10 +510,11 @@ function addUserTag(floID, tag, proxySecret) { }) } -function removeUserTag(floID, tag, proxySecret) { +function removeUserTag(tag_user, tag, floID, proxySecret) { return new Promise((resolve, reject) => { let request = { - user: floID, + floID: floID, + user: tag_user, tag: tag, timestamp: Date.now() }; @@ -450,7 +526,7 @@ function removeUserTag(floID, tag, proxySecret) { }, proxySecret); console.debug(request); - fetch('/remove-tag', { + exchangeAPI('/remove-tag', { method: "POST", headers: { 'Content-Type': 'application/json' @@ -461,4 +537,44 @@ function removeUserTag(floID, tag, proxySecret) { .catch(error => reject(error))) .catch(error => reject(error)) }) +} + +function refreshDataFromBlockchain() { + return new Promise((resolve, reject) => { + let nodes, lastTx; + try { + nodes = JSON.parse(localStorage.getItems('exhange-nodes')); + if (typeof nodes !== 'object') + throw Error('nodes must be an object') + else + lastTx = parseInt(localStorage.getItem('exchange-lastTx')) || 0; + } catch (error) { + nodes = {}; + lastTx = 0; + } + floBlockchainAPI.readData(floGlobals.adminID, { + ignoreOld: lastTx, + sentOnly: true, + pattern: floGlobals.application + }).then(result => { + result.data.reverse().forEach(data => { + var content = JSON.parse(data)[floGlobals.application]; + //Node List + if (content.Nodes) { + if (content.Nodes.remove) + for (let n of content.Nodes.remove) + delete nodes[n]; + if (content.Nodes.add) + for (let n in content.Nodes.add) + nodes[n] = content.Nodes.add[n]; + } + }); + localStorage.setItem('exhange-lastTx', result.totalTxs); + localStorage.setItem('exhange-nodes', JSON.stringify(nodes)); + nodeURL = nodes; + nodeKBucket = new K_Bucket(floGlobals.adminID, Object.keys(nodeURL)); + nodeList = nodeKBucket.order; + resolve(nodes); + }).catch(error => reject(error)); + }) } \ No newline at end of file diff --git a/public/home.html b/public/home.html index d13cbb2..fbec54b 100644 --- a/public/home.html +++ b/public/home.html @@ -96,7 +96,8 @@ Remember me - + +
Log in
@@ -854,7 +855,7 @@ let pageId let params if (targetPage === '') { - if (typeof myFloID === "undefined") { + if (typeof proxy.userID === "undefined") { pageId = 'landing' } else { pageId = 'home' @@ -1206,13 +1207,13 @@ const quantity = parseFloat(getRef('get_user_amount').value) try { showProcess('wallet_popup__cta_wrapper') - const proxySecret = await proxy.secret + const proxySecret = await proxy.secret; if (type === 'deposit') { const privKey = getRef('get_private_key').value; if (asset === 'FLO') { - await depositFLO(quantity, userID, privKey, proxySecret) + await depositFLO(quantity, proxy.userID, privKey, proxySecret) } else { - await depositRupee(quantity, userID, privKey, proxySecret) + await depositRupee(quantity, proxy.userID, privKey, proxySecret) } showWalletResult('success', `Sent ${asset} deposit request`, 'This may take upto 30 mins to reflect in your wallet.') } else { @@ -1451,10 +1452,10 @@ transactions.forEach(transaction => { const { quantity, unitValue, tx_time, buyer, seller } = transaction let type, other; - if (seller === userID) { + if (seller === proxy.userID) { type = 'Sold'; - other = buyer === userID ? 'MySelf' : buyer; - } else if (buyer === userID) { + other = buyer === proxy.userID ? 'MySelf' : buyer; + } else if (buyer === proxy.userID) { type = 'Bought'; other = seller; } else @@ -1551,9 +1552,9 @@ diff --git a/src/app.js b/src/app.js index 9e216b4..582a0f9 100644 --- a/src/app.js +++ b/src/app.js @@ -1,9 +1,8 @@ 'use strict'; const express = require('express'); -const cookieParser = require("cookie-parser"); -const sessions = require('express-session'); +//const cookieParser = require("cookie-parser"); +//const sessions = require('express-session'); const Request = require('./request'); -const WebSocket = require('ws'); const REFRESH_INTERVAL = 5 * 1000; //10 * 60 * 1000; @@ -12,16 +11,15 @@ module.exports = function App(secret, DB) { if (!(this instanceof App)) return new App(secret, DB); - var server = null, - wss = null; + var server = null; const app = express(); //session middleware - app.use(sessions({ + /*app.use(sessions({ secret: secret, saveUninitialized: true, resave: false, name: "session" - })); + }));*/ // parsing the incoming data app.use(express.json()); app.use(express.urlencoded({ @@ -30,12 +28,17 @@ module.exports = function App(secret, DB) { //serving public file app.use(express.static(PUBLIC_DIR)); // cookie parser middleware - app.use(cookieParser()); + //app.use(cookieParser()); + /* Decentralising - Users will load from user-end files and request via APIs only //Initital page loading app.get('/', (req, res) => res.sendFile('home.html', { root: PUBLIC_DIR })); + */ + + //get code for login or signup + app.get('/get-login-code', Request.getLoginCode); //signup request app.post('/signup', Request.SignUp); @@ -76,6 +79,7 @@ module.exports = function App(secret, DB) { app.post('/remove-tag', Request.removeUserTag); Request.DB = DB; + Request.secret = secret; //Properties var periodInstance = null; diff --git a/src/request.js b/src/request.js index 86f3336..8d51727 100644 --- a/src/request.js +++ b/src/request.js @@ -1,7 +1,7 @@ 'use strict'; const market = require("./market"); -var DB, trustedIDs; //container for database +var DB, trustedIDs, secret; //container for database global.INVALID = function(message) { if (!(this instanceof INVALID)) @@ -28,9 +28,13 @@ function validateRequestFromFloID(request, sign, floID, proxy = true) { return new Promise((resolve, reject) => { if (!serving) return reject(INVALID(INVALID_SERVER_MSG)); - DB.query("SELECT " + (proxy ? "proxyKey AS pubKey FROM Sessions" : "pubKey FROM Users") + " WHERE floID=?", [floID]).then(result => { + else if (!floCrypto.validateAddr(floID)) + return res.status(INVALID.e_code).send("Invalid floID"); + DB.query("SELECT " + (proxy ? "session_time, proxyKey AS pubKey FROM Sessions" : "pubKey FROM Users") + " WHERE floID=?", [floID]).then(result => { if (result.length < 1) return reject(INVALID(proxy ? "Session not active" : "User not registered")); + if (proxy && result[0].session_time + maxSessionTimeout < Date.now()) + return res.status(INVALID.e_code).send("Session Expired! Re-login required"); let req_str = validateRequest(request, sign, result[0].pubKey); req_str instanceof INVALID ? reject(req_str) : resolve(req_str); }).catch(error => reject(error)); @@ -57,18 +61,26 @@ function storeRequest(floID, req_str, sign) { .then(_ => null).catch(error => console.error(error)); } +function getLoginCode(req, res) { + let randID = floCrypto.randString(8, true) + Math.round(Date.now() / 1000); + let hash = Crypto.SHA1(randID + secret); + res.status(INVALID.e_code).send({ + code: randID, + hash: hash + }); +} + function SignUp(req, res) { if (!serving) return res.status(INVALID.e_code).send(INVALID_SERVER_MSG); - let data = req.body, - session = req.session; + let data = req.body; if (floCrypto.getFloID(data.pubKey) !== data.floID) return res.status(INVALID.e_code).send("Invalid Public Key"); - if (!session.random) - return res.status(INVALID.e_code).send("Invalid Session"); + if (!data.code || data.hash != Crypto.SHA1(data.code + secret)) + return res.status(INVALID.e_code).send("Invalid Code"); let req_str = validateRequest({ type: "create_account", - random: session.random, + random: data.code, timestamp: data.timestamp }, data.sign, data.pubKey); if (req_str instanceof INVALID) @@ -90,22 +102,18 @@ function SignUp(req, res) { } function Login(req, res) { - let data = req.body, - session = req.session; - if (!session.random) - return res.status(INVALID.e_code).send("Invalid Session"); + let data = req.body; + if (!data.code || data.hash != Crypto.SHA1(data.code + secret)) + return res.status(INVALID.e_code).send("Invalid Code"); validateRequestFromFloID({ type: "login", - random: session.random, + random: data.code, proxyKey: data.proxyKey, timestamp: data.timestamp }, data.sign, data.floID, false).then(req_str => { - DB.query("INSERT INTO Sessions (floID, session_id, proxyKey) VALUES (?, ?, ?) " + - "ON DUPLICATE KEY UPDATE session_id=?, session_time=DEFAULT, proxyKey=?", - [data.floID, req.sessionID, data.proxyKey, req.sessionID, data.proxyKey]).then(_ => { - if (data.saveSession) - session.cookie.maxAge = maxSessionTimeout; - session.user_id = data.floID; + DB.query("INSERT INTO Sessions (floID, proxyKey) VALUES (?, ?, ?) " + + "ON DUPLICATE KEY UPDATE session_time=DEFAULT, proxyKey=?", + [data.floID, data.code, data.proxyKey, data.code, data.proxyKey]).then(_ => { storeRequest(data.floID, req_str, data.sign); res.send("Login Successful"); }).catch(error => { @@ -123,32 +131,38 @@ function Login(req, res) { } function Logout(req, res) { - let session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("No logged in user found in this session"); - DB.query("DELETE FROM Sessions WHERE floID=?", [session.user_id]).then(_ => { - session.destroy(); - res.send('Logout successful'); + validateRequestFromFloID({ + type: "logout", + timestamp: data.timestamp + }, data.sign, data.floID).then(req_str => { + DB.query("DELETE FROM Sessions WHERE floID=?", [data.floID]).then(_ => { + storeRequest(data.floID, req_str, data.sign); + res.send('Logout successful'); + }).catch(error => { + console.error(error); + res.status(INTERNAL.e_code).send("Logout failed! Try again later! Contact support if this error occurs frequently"); + }); }).catch(error => { - console.error(error); - res.status(INTERNAL.e_code).send("Logout failed! Try again later! Contact support if this error occurs frequently"); + if (error instanceof INVALID) + res.status(INVALID.e_code).send(error.message); + else { + console.error(error); + res.status(INTERNAL.e_code).send("Request processing failed! Try again later!"); + } }); } function PlaceSellOrder(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "sell_order", quantity: data.quantity, min_price: data.min_price, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.addSellOrder(session.user_id, data.quantity, data.min_price) + }, data.sign, data.floID).then(req_str => { + market.addSellOrder(data.floID, data.quantity, data.min_price) .then(result => { - storeRequest(session.user_id, req_str, data.sign); + storeRequest(data.floID, req_str, data.sign); res.send('Sell Order placed successfully'); }).catch(error => { if (error instanceof INVALID) @@ -169,19 +183,16 @@ function PlaceSellOrder(req, res) { } function PlaceBuyOrder(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "buy_order", quantity: data.quantity, max_price: data.max_price, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.addBuyOrder(session.user_id, data.quantity, data.max_price) + }, data.sign, data.floID).then(req_str => { + market.addBuyOrder(data.floID, data.quantity, data.max_price) .then(result => { - storeRequest(session.user_id, req_str, data.sign); + storeRequest(data.floID, req_str, data.sign); res.send('Buy Order placed successfully'); }).catch(error => { if (error instanceof INVALID) @@ -202,19 +213,16 @@ function PlaceBuyOrder(req, res) { } function CancelOrder(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "cancel_order", order: data.orderType, id: data.orderID, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.cancelOrder(data.orderType, data.orderID, session.user_id) + }, data.sign, data.floID).then(req_str => { + market.cancelOrder(data.orderType, data.orderID, data.floID) .then(result => { - storeRequest(session.user_id, req_str, data.sign); + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -263,54 +271,35 @@ function getRate(req, res) { } function Account(req, res) { - if (!serving) - return res.status(INVALID.e_code).send(INVALID_SERVER_MSG); - const setLogin = function(message) { - let randID = floCrypto.randString(16, true); - req.session.random = randID; - res.status(INVALID.e_code).send({ - message, - sid: randID + let data = req.body; + validateRequestFromFloID({ + type: "get_account", + timestamp: data.timestamp + }, data.sign, data.floID).then(req_str => { + market.getAccountDetails(data.floID).then(result => { + if (trustedIDs.includes(data.floID)) + result.subAdmin = true; + res.send(result); }); - } - if (!req.session.user_id) - setLogin("Login required"); - else { - DB.query("SELECT session_id, session_time FROM Sessions WHERE floID=?", [req.session.user_id]).then(result => { - if (result.length < 1) { - res.status(INVALID.e_code).send("floID not registered"); - return; - } - let { - session_id, - session_time - } = result.pop(); - if (!session_id || session_id != req.sessionID || session_time + maxSessionTimeout < Date.now()) - setLogin("Session Expired! Re-login required"); - else { - let floID = req.session.user_id; - market.getAccountDetails(floID).then(result => { - if (trustedIDs.includes(floID)) - result.subAdmin = true; - res.send(result) - }); - } - }).catch(_ => res.status(INTERNAL.e_code).send("Try again later!")); - } + }).catch(error => { + if (error instanceof INVALID) + res.status(INVALID.e_code).send(error.message); + else { + console.error(error); + res.status(INTERNAL.e_code).send("Request processing failed! Try again later!"); + } + }); } function DepositFLO(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "deposit_FLO", txid: data.txid, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.depositFLO(session.user_id, data.txid).then(result => { - storeRequest(session.user_id, req_str, data.sign); + }, data.sign, data.floID).then(req_str => { + market.depositFLO(data.floID, data.txid).then(result => { + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -331,17 +320,14 @@ function DepositFLO(req, res) { } function WithdrawFLO(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "withdraw_FLO", amount: data.amount, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.withdrawFLO(session.user_id, data.amount).then(result => { - storeRequest(session.user_id, req_str, data.sign); + }, data.sign, data.floID).then(req_str => { + market.withdrawFLO(data.floID, data.amount).then(result => { + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -362,17 +348,14 @@ function WithdrawFLO(req, res) { } function DepositRupee(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "deposit_Rupee", txid: data.txid, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.depositRupee(session.user_id, data.txid).then(result => { - storeRequest(session.user_id, req_str, data.sign); + }, data.sign, data.floID).then(req_str => { + market.depositRupee(data.floID, data.txid).then(result => { + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -393,17 +376,14 @@ function DepositRupee(req, res) { } function WithdrawRupee(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); + let data = req.body; validateRequestFromFloID({ type: "withdraw_Rupee", amount: data.amount, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { - market.withdrawRupee(session.user_id, data.amount).then(result => { - storeRequest(session.user_id, req_str, data.sign); + }, data.sign, data.floID).then(req_str => { + market.withdrawRupee(data.floID, data.amount).then(result => { + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -424,20 +404,17 @@ function WithdrawRupee(req, res) { } function addUserTag(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); - else if (!trustedIDs.includes(session.user_id)) + let data = req.body; + if (!trustedIDs.includes(data.floID)) return res.status(INVALID.e_code).send("Access Denied"); validateRequestFromFloID({ command: "add_Tag", user: data.user, tag: data.tag, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { + }, data.sign, data.floID).then(req_str => { market.group.addTag(data.user, data.tag).then(result => { - storeRequest(session.user_id, req_str, data.sign); + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -458,11 +435,8 @@ function addUserTag(req, res) { } function removeUserTag(req, res) { - let data = req.body, - session = req.session; - if (!session.user_id) - return res.status(INVALID.e_code).send("Login required"); - else if (!trustedIDs.includes(session.user_id)) + let data = req.body; + if (!trustedIDs.includes(data.floID)) return res.status(INVALID.e_code).send("Access Denied"); else validateRequestFromFloID({ @@ -470,9 +444,9 @@ function removeUserTag(req, res) { user: data.user, tag: data.tag, timestamp: data.timestamp - }, data.sign, session.user_id).then(req_str => { + }, data.sign, data.floID).then(req_str => { market.group.removeTag(data.user, data.tag).then(result => { - storeRequest(session.user_id, req_str, data.sign); + storeRequest(data.floID, req_str, data.sign); res.send(result); }).catch(error => { if (error instanceof INVALID) @@ -493,6 +467,7 @@ function removeUserTag(req, res) { } module.exports = { + getLoginCode, SignUp, Login, Logout, @@ -518,6 +493,9 @@ module.exports = { DB = db; market.DB = db; }, + set secret(s) { + secret = s; + }, pause() { serving = false; },