Commit 8ebe56c2 authored by Geovanny's avatar Geovanny

War participation api

parent c7632c96
...@@ -4,17 +4,16 @@ const MySQL = require('promise-mysql'); ...@@ -4,17 +4,16 @@ const MySQL = require('promise-mysql');
const ENV = require('../settings'); const ENV = require('../settings');
const db = {} const db = {}
let connection = MySQL.createConnection({ db.connectDB = async () =>{
host: ENV.DB_HOST, const connection = await MySQL.createConnection({
port: ENV.DB_PORT, host: ENV.DB_HOST,
user: ENV.DB_USER, port: ENV.DB_PORT,
password: ENV.DB_PASS, user: ENV.DB_USER,
database: ENV.DB_NAME password: ENV.DB_PASS,
}); database: ENV.DB_NAME
});
connection.then((con) =>{ console.log('Database connected');
console.log('Database Connected'); db.con = connection;
db.con = con; }
});
module.exports = db; module.exports = db;
\ No newline at end of file
...@@ -169,13 +169,45 @@ model.changeHouseLiege = async(liege_id, member_id) => { ...@@ -169,13 +169,45 @@ model.changeHouseLiege = async(liege_id, member_id) => {
} }
model.getMemberUnits = async(member_id) => { model.getMemberUnits = async(member_id) => {
const sql_txt = `SELECT u.*, uu.unit_level, uu.elite_flg const sql_text = `SELECT u.*, uu.unit_level, uu.elite_flg
FROM users as us FROM users as us
LEFT JOIN users_units as uu ON us.id = uu.user_id LEFT JOIN users_units as uu ON us.id = uu.user_id
LEFT JOIN units as u ON uu.unit_id = u.id LEFT JOIN units as u ON uu.unit_id = u.id
WHERE us.id = ? ORDER BY u.name ASC;` WHERE us.id = ? ORDER BY u.name ASC;`
const data = await db.con.query(sql_txt, [member_id]); const data = await db.con.query(sql_text, [member_id]);
return data; return data;
} }
model.getCurrentWar = async() => {
const sql_text = 'SELECT * FROM war_days WHERE completed = 0 LIMIT 1;'
const data = await db.con.query(sql_text);
return data[0];
}
model.insertNewWar = async() => {
const sql_text = 'UPDATE war_days SET completed = 1;';
const sql_text2 = 'INSERT INTO war_days (day) VALUES (CURDATE());'
await db.con.query('START TRANSACTION;');
await db.con.query(sql_text);
await db.con.query(sql_text2);
await db.con.query('COMMIT;');
}
model.warParticipation = async (user_id, house_id, decision) => {
const sql_text = 'SELECT @current_war_id:=id FROM war_days WHERE completed = 0 LIMIT 1;';
const sql_text2 = `INSERT INTO users_war (user_id, war_id, house_id, decision) VALUES (?, @current_war_id, ?, ?)
ON DUPLICATE KEY UPDATE decision = ?`;
await db.con.query('START TRANSACTION;');
await db.con.query(sql_text);
await db.con.query(sql_text2, [user_id, house_id, decision, decision]);
await db.con.query('COMMIT;');
}
module.exports = model; module.exports = model;
\ No newline at end of file
const Koa = require('koa'); const Koa = require('koa');
const Router = require('@koa/router'); const Router = require('@koa/router');
const CronJob = require('cron').CronJob;
const router = new Router(); const router = new Router();
const authRouter = new Router(); const authRouter = new Router();
const houseModel = require('./model'); const houseModel = require('./model');
const userModel = require('../user/model') const userModel = require('../user/model');
const HOUSE_ROLES = { const HOUSE_ROLES = {
lg: 0, lg: 0,
...@@ -314,5 +315,48 @@ authRouter.delete('/:house_id', async (context, next) => { ...@@ -314,5 +315,48 @@ authRouter.delete('/:house_id', async (context, next) => {
} }
}); });
authRouter.post('/participation', async (context, next) => {
hasHouse(context);
const body = context.request.body;
if(!body || !body.decision){
context.throw(400, 'No decision found');
}
try{
await houseModel.warParticipation(context.user.id, context.user.house_id, body.decision);
context.response.status = 204;
}catch(error){
console.log(error);
context.throw(400, 'Failed to Update Participation');
}
});
router.get('/current-war', async (context, next) => {
try{
const data = await houseModel.getCurrentWar();
if(!data){
throw Error('Failed to get Current War');
}
context.response.status = 200;
context.response.body = data;
}catch(error){
console.log(error);
context.throw(400, 'Failed to get Current War');
}
});
async function insertNewWar(){
try{
await houseModel.insertNewWar();
console.log('Inserted new War')
}catch(error){
console.log(error);
}
}
const war_job = new CronJob('30 22 * * Tue,Sat', ()=> {
insertNewWar();
});
war_job.start();
module.exports = [router, authRouter]; module.exports = [router, authRouter];
\ No newline at end of file
'use strict'; 'use strict';
const Koa = require('koa'); const Koa = require('koa');
const Router = require('@koa/router'); const Router = require('@koa/router');
const bodyParser = require('koa-body'); const bodyParser = require('koa-body');
const session = require('koa-session') const session = require('koa-session')
const serve = require('koa-static'); const serve = require('koa-static');
const logger = require('koa-logger') const logger = require('koa-logger')
const getUser = require('./user/model'); async function main(){
const [userRouter, userAuthRouter] = require('./user/route'); const db = require('./database/database.js');
const [houseRouter, houseAuthRouter] = require('./house/route'); await db.connectDB();
const unitRouter = require('./unit/route'); const getUser = require('./user/model');
const SESS_CONFIG = require('./session_config'); const [userRouter, userAuthRouter] = require('./user/route');
const ENV = require('./settings') const [houseRouter, houseAuthRouter] = require('./house/route');
const app = new Koa(); const unitRouter = require('./unit/route');
const router = new Router();
const authRouter = new Router(); const SESS_CONFIG = require('./session_config');
const ENV = require('./settings')
app.use(serve(`${__dirname}/../web`)) const app = new Koa();
app.use(logger()) const router = new Router();
const authRouter = new Router();
app.keys = [ENV.SESS_KEY]
app.use(bodyParser()); app.use(serve(`${__dirname}/../web`))
app.use(session(SESS_CONFIG, app)); app.use(logger())
router.use('/api/unit', unitRouter.routes(), unitRouter.allowedMethods()); app.keys = [ENV.SESS_KEY]
router.use('/api/user', userRouter.routes(), userRouter.allowedMethods()); app.use(bodyParser());
router.use('/api/house', houseRouter.routes(), houseRouter.allowedMethods()); app.use(session(SESS_CONFIG, app));
authRouter.use('/api/user', userAuthRouter.routes(), userAuthRouter.allowedMethods()); router.use('/api/unit', unitRouter.routes(), unitRouter.allowedMethods());
authRouter.use('/api/house', houseAuthRouter.routes(), houseAuthRouter.allowedMethods()); router.use('/api/user', userRouter.routes(), userRouter.allowedMethods());
router.use('/api/house', houseRouter.routes(), houseRouter.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
authRouter.use('/api/user', userAuthRouter.routes(), userAuthRouter.allowedMethods());
// Make sure user is authorized authRouter.use('/api/house', houseAuthRouter.routes(), houseAuthRouter.allowedMethods());
app.use(async (context, next) => {
if(context.session.user_id){ app.use(router.routes()).use(router.allowedMethods());
await next();
console.log(context.status) // Make sure user is authorized
} else { app.use(async (context, next) => {
context.response.status = 401; if(context.session.user_id){
} await next();
}); console.log(context.status)
// Add user to context } else {
app.use(async (context, next) => { context.response.status = 401;
const user = await getUser.getUserFullFromId(context.session.user_id); }
if(user){ });
context.user = user; // Add user to context
await next(); app.use(async (context, next) => {
} else { const user = await getUser.getUserFullFromId(context.session.user_id);
context.response.status = 403; if(user){
} context.user = user;
}); await next();
} else {
app.use(authRouter.routes()).use(authRouter.allowedMethods()); context.response.status = 403;
}
app.listen(3000, () => console.log('Server Started')); });
\ No newline at end of file
app.use(authRouter.routes()).use(authRouter.allowedMethods());
app.listen(3000, () => console.log('Server Started'));
}
main();
\ No newline at end of file
...@@ -256,6 +256,14 @@ ...@@ -256,6 +256,14 @@
"buffer": "^5.1.0" "buffer": "^5.1.0"
} }
}, },
"cron": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/cron/-/cron-1.8.2.tgz",
"integrity": "sha512-Gk2c4y6xKEO8FSAUTklqtfSr7oTq0CiPQeLBG5Fl0qoXpZyMcj1SG59YL+hqq04bu6/IuEA7lMkYDAplQNKkyg==",
"requires": {
"moment-timezone": "^0.5.x"
}
},
"debug": { "debug": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
...@@ -720,6 +728,19 @@ ...@@ -720,6 +728,19 @@
"minimist": "^1.2.5" "minimist": "^1.2.5"
} }
}, },
"moment": {
"version": "2.25.3",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.25.3.tgz",
"integrity": "sha512-PuYv0PHxZvzc15Sp8ybUCoQ+xpyPWvjOuK72a5ovzp2LI32rJXOiIfyoFoYvG3s6EwwrdkMyWuRiEHSZRLJNdg=="
},
"moment-timezone": {
"version": "0.5.29",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.29.tgz",
"integrity": "sha512-qWtUhRIk29zviEFAhttY0fDbM/zsu/OlCRoeQG8vxuH6XcTTuji9ILJkOdxjr+vzIv0J39RsO/SPTuMvzm90wA==",
"requires": {
"moment": ">= 2.9.0"
}
},
"ms": { "ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
"dependencies": { "dependencies": {
"@koa/router": "^8.0.8", "@koa/router": "^8.0.8",
"bcrypt": "^4.0.1", "bcrypt": "^4.0.1",
"cron": "^1.8.2",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"fs": "0.0.1-security", "fs": "0.0.1-security",
"koa": "^2.11.0", "koa": "^2.11.0",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment