Skip to content

Commit

Permalink
Merge pull request #36 from Remynijsten/dev
Browse files Browse the repository at this point in the history
Dev to main
  • Loading branch information
RickLugtigheid authored Jan 10, 2022
2 parents b01cad8 + 8458526 commit 73bc916
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 28 deletions.
13 changes: 13 additions & 0 deletions controllers/room_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

/**
* @param {Request} req
* @param {Response} res
*/
const create = (req, res) => {
console.log(req.body);
res.status(200).json();
}

module.exports = {
create
}
16 changes: 7 additions & 9 deletions controllers/user_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const bcrypt = require('bcrypt');
const harms = /[!#$%^&*()_+\-=\[\]{};':"\\|,<>\/?]+/;
const session = require('express-session')
const msal = require('@azure/msal-node');

const server = require('../server');
const { User, ACCOUNT_TYPE } = require('../models/user_schema')

const register = (req, res) => {
Expand Down Expand Up @@ -294,8 +294,9 @@ const loginMicrosoft = (req, res) => {
scopes: ["user.read"],
// TODO:
// Get server info (url/port)
redirectUri: "https://localhost:5555/api/user/auth/microsoft"
redirectUri: `${req.protocol}://${server.hostname}/api/user/auth/microsoft`
}
console.log("Redirect url: ", `${req.protocol}://${server.hostname}/api/user/auth/microsoft`)
cca.getAuthCodeUrl(authUrlParams)
.then(response => {
res.status(200).json(
Expand All @@ -317,14 +318,11 @@ const authMicrosoft = (req, res) => {
res.sendStatus(500);
return;
}

const HOST = req.hostname;
const USE_PORT = HOST == 'localhost';

console.log("Redirect url: ", `${req.protocol}://${server.hostname}/api/user/auth/microsoft`)
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: `https://${HOST}${ USE_PORT ? ':5555' : '' }/api/user/auth/microsoft`
redirectUri: `${req.protocol}://${server.hostname}/api/user/auth/microsoft`
};

cca.acquireTokenByCode(tokenRequest)
Expand All @@ -346,7 +344,7 @@ const authMicrosoft = (req, res) => {
req.session.token = generateToken([acc]);
req.session.name = response.account.name || response.account.username;
req.session.email = response.account.username;
res.redirect(`https://${HOST.includes('-server') ? HOST.replace('-server', '-client') : HOST}${ USE_PORT ? ':8080' : '' }/login?token=${req.session.token}`);
res.redirect(`${req.protocol}://${server.clienthost}/login?token=${req.session.token}`);
}).catch(err => res.status(500).json({ when: 'creating user', error: err.message }));
}
else
Expand All @@ -363,7 +361,7 @@ const authMicrosoft = (req, res) => {
req.session.token = generateToken(found);
req.session.name = response.account.name;
req.session.email = response.account.username;
res.redirect('https://localhost:8080/login?token=' + req.session.token);
res.redirect(`${req.protocol}://${server.clienthost}/login?token=${req.session.token}`);
}
}
});
Expand Down
8 changes: 4 additions & 4 deletions helpers/classes/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ class Session
if(votes !== undefined) // Waiting state has no features yet
{
votes.forEach(vote => vote.value == -1 ? coffeeVotes++ : '');
let half = Math.floor(votes.length / 2) !== 0 ? Math.floor(votes.length / 2) : 1
return coffeeVotes >= half;
return coffeeVotes >= (votes.length / 2);
}
return false;
}
Expand All @@ -124,22 +123,23 @@ class Session
featureData()
{
let feature = this.backlog.cards[this.featurePointer];

let users = []
this.clients.forEach(client => {
users.push({
name : client.name,
status : client.status
})
})

return {
// Name of the feature
name : feature.name,

// Description of the feature
desc : feature.desc,

// Attachments
attachments : feature.attachments,

// Checklists of the feature
checklists : feature.checklists,

Expand Down
8 changes: 4 additions & 4 deletions helpers/classes/stateMachine.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,11 @@ class StateMachine {
this.coffeeUsed = false;

this.session.createFeatureObject();
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData() });
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData(), template : this.session.template });
break;

case STATE.END:
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData() });
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData(), template : this.session.template });
break;
}
this.prevState = this.state;
Expand All @@ -109,7 +109,7 @@ class StateMachine {

this.state = STATE.ROUND_1;
!this.coffeeUsed ? this.session.createFeatureObject() : ''; // Was coffee used in the previous round? Don't make another DB object key for this feature
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData() });
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData(), template : this.session.template });
}

loadRound2() {
Expand All @@ -123,7 +123,7 @@ class StateMachine {
.then(response => {
this.session.dbData = response[0]

this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData(), chats: this.session.dbData.features[this.session.featurePointer] });
this.session.broadcast('load', { toLoad: this.state, data: this.session.featureData(), template : this.session.template, chats: this.session.dbData.features[this.session.featurePointer] });
});
}

Expand Down
61 changes: 54 additions & 7 deletions helpers/socketServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,20 @@ module.exports = function(io)

// Set settings for number assign method
session.settings = args.settings

session.template = args.cardtemplate

// Push to active sessions
this.activeSessions.push(session);

trello.getListByName(board.id, "backlog")
trello.getListByName(board.id, args.settings.board)
.then(backlog => {
session.backlog = backlog;

trello.getCardsFromList(session.backlog.id)
trello.getCardsFromList(session.backlog.id, true)
.then(cards => {
session.backlog.cards = cards;

// Return the session key to front end
client.emit('createRoom', {key: key});
})
Expand Down Expand Up @@ -114,7 +116,7 @@ module.exports = function(io)

User.find({ email: args.email }).then(data => {
client.uid = Types.ObjectId(data[0]._id)._id;

// Add player to players array in session database if not done yet
SessionObject
.find({'_id' : Types.ObjectId(currentSession.dbData._id), 'players.email' : args.email})
Expand Down Expand Up @@ -154,15 +156,15 @@ module.exports = function(io)
switch(currentSession.stateMachine.state)
{
case STATE.WAITING:
client.emit('load', { toLoad: 0, data: currentSession.featureData() });
client.emit('load', { toLoad: 0, data: currentSession.featureData(), template : currentSession.template });
break;

case STATE.ROUND_1:
client.emit('load', { toLoad: 1, data: currentSession.featureData() });
client.emit('load', { toLoad: 1, data: currentSession.featureData(), template : currentSession.template });
break;

case STATE.ROUND_2:
client.emit('load', { toLoad: 2, data: currentSession.featureData(), chats: currentSession.dbData.features[currentSession.featurePointer] });
client.emit('load', { toLoad: 2, data: currentSession.featureData(), template : currentSession.template, chats: currentSession.dbData.features[currentSession.featurePointer] });
break;

case STATE.ADMIN_CHOICE:
Expand All @@ -177,6 +179,19 @@ module.exports = function(io)
} else client.emit('undefinedSession');
break;

case 'checkURL':
let trellodata = [...args.url.matchAll(/https:\/\/trello\.com\/b\/(.*)\/(.*)/g)][0]
let trello = new TrelloApi('c6f2658e8bbe5ac486d18c13e49f1abb', args.token);

if(trellodata !== undefined) {
trello.getLists(trellodata[1]).then(r => {
client.emit('checkURL', r.map(list => {
return {content : list.name, value : list.name}
}));
})
} else client.emit('urlError', {error: "Invalid Trello board"});
break;

case 'start':
this.activeSessions.find(session => session.key == args.key)?.start();
break;
Expand Down Expand Up @@ -402,5 +417,37 @@ module.exports = function(io)
break;
}
});

client.on('templates', args => {
switch (args.event)
{
case 'load':
User.find({email : args.email})
.then(data => {
client.emit('templates:load', data[0]['templates'])
})
break;

case 'save':
User.updateOne({"email" : args.email}, {
"$push":
{
"templates":
{
"title" : args.template.name,
"cards" : args.template.cards
}
}
})
.then(data => {
console.log(data)
})
.catch(e => {
console.log(e)
})

break;
}
})
});
}
26 changes: 24 additions & 2 deletions helpers/trelloApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class TrelloApi
}).catch(err => reject(err));
});
}

/**
*
* @param {string} boardID
Expand Down Expand Up @@ -103,7 +104,7 @@ class TrelloApi
* @param {string} listID
* @returns {Promise<Array<Card>>}
*/
getCardsFromList(listID)
getCardsFromList(listID, loadAttachments)
{
let url = `${this.baseUrl}/lists/${listID}/cards?key=${this.key}&token=${this.token}&checklists=all`;
return new Promise((resolve, reject) => {
Expand All @@ -113,13 +114,33 @@ class TrelloApi
}).then(res => {
let cards = [];
res.data.forEach(card => {
cards.push(new Card(card));
let result = new Card(card);
// Check if we should load attachments for this card
if (loadAttachments)
this.getAttachmentsFormCard(result.id).then(attachments => {
result.attachments = attachments;
}).catch(err => console.timeStamp(err));
cards.push(result);
});
resolve(cards);
}).catch(err => reject(err));
});
}


getAttachmentsFormCard(cardID)
{
let url = `${this.baseUrl}/cards/${cardID}/attachments?key=${this.key}&token=${this.token}`;
return new Promise((resolve, reject) => {
axios({
method: 'GET',
url
}).then(res => {
resolve(res.data);
}).catch(err => reject(err));
});
}

/**
* Update the name/title of the card in Trello
* @param {Card} card
Expand Down Expand Up @@ -225,6 +246,7 @@ class Card
this.labels = data.labels;
this.isSubscribed = data.subscribed;
this.url = data.url;
this.attachments = null;
}
}

Expand Down
9 changes: 9 additions & 0 deletions models/user_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ const ACCOUNT_TYPE = {
DEFAULT : 0,
MICROSOFT : 1
}

const template = new Schema(
{
cards : Array,
title : String
}
)

const userSchema = new Schema(
{
name : {
Expand All @@ -29,6 +37,7 @@ const userSchema = new Schema(
type : String,
required : false,
},
templates : [template]
},
{timestamps : true},
);
Expand Down
12 changes: 12 additions & 0 deletions routes/api/room.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const express = require('express');

const {
create
} = require('../../controllers/room_controller');

const router = express.Router();

router
.post('/', create);

module.exports = router;
14 changes: 12 additions & 2 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,23 @@ app.use((req,res, next) => {
app.use('/api', require('./routes/api'));

if(process.env.PRODUCTION_CONFIG)
{
{
// Set host config
module.exports.hostname = "scrumbers-server.herokuapp.com";
module.exports.clienthost = "scrumbers-client.herokuapp.com";

// Create server
const server = app.listen(port)
const io = require('socket.io')(server, {cors: {origin: "*", methods: ["GET", "POST"], allowedHeaders: ["Content-Type", "Authorization"], credentials: true}})
require('./helpers/socketServer')(io);
}
else
{
// Set default host config
module.exports.hostname = 'localhost:' + port;
module.exports.clienthost = 'localhost:8080';

// Create server
const https = require('https');
const server = https.createServer({key: fs.readFileSync('./localhost-key.pem'), cert: fs.readFileSync('./localhost.pem'),}, app);
const io = require('socket.io')(server, {cors: {origin: "*", methods: ["GET", "POST"], allowedHeaders: ["Content-Type", "Authorization"], credentials: true}})
Expand All @@ -72,4 +82,4 @@ else
}

console.log(`Listening On https://localhost:${port}/api`);
module.exports = app;
module.exports.app = app;

0 comments on commit 73bc916

Please sign in to comment.