Skip to content

Commit

Permalink
Merge pull request #39 from chrisbruford/chris
Browse files Browse the repository at this point in the history
Chris
  • Loading branch information
chrisbruford authored Dec 19, 2017
2 parents 035c24c + 4432e7f commit 6916550
Show file tree
Hide file tree
Showing 20 changed files with 282 additions and 37 deletions.
5 changes: 2 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ let uploads = require('./routes/uploads');
let wing = require('./routes/wing');
let discordAuth = require('./routes/discord-auth');
let interdicted = require('./routes/companion-app/interdicted');
let missions = require('./routes/companion-app/missions');

let app = express();

Expand Down Expand Up @@ -62,9 +63,6 @@ app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//mongo session store

let store = new MongoStore({ mongooseConnection: mongoose.connection });

app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret: process.env.cookieSecret || require('./secrets').cookieSecret
Expand Down Expand Up @@ -132,6 +130,7 @@ app.use('/api/wing', wing);
app.use('/discord', discordAuth);
//companion app routes
app.use('/api/interdicted', interdicted);
app.use('/api/missions', missions);

//checks auth level before sending these
app.use('/secure', secure);
Expand Down
2 changes: 1 addition & 1 deletion gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,5 @@ gulp.task('cache:clear', function (callback) {
});

gulp.task('default', function () {
runSequence(['sass', 'browserify'], 'browserSync', 'watch', 'test');
runSequence(['sass', 'browserify'], 'browserSync', 'watch');
});
3 changes: 1 addition & 2 deletions middleware/dbconnected.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ const db = require('../db.js');
let tracker = 0;

module.exports = (req,res,next) => {
if (db.mongoose.connection.status === 0) {
if (db.mongoose.connection.readyState === 1) {
next();
} else if (tracker < 5) {

tracker++;

setTimeout(()=>{
Expand Down
3 changes: 2 additions & 1 deletion models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ module.exports = new Promise((resolve, reject) => {
required: true
},
wings: [wing],
discordID: String
discordID: String,
broadcastGuilds: [String]
});

User.methods.setToken = function () {
Expand Down
17 changes: 17 additions & 0 deletions modules/kok-bot/modules/broadcasts/add.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const User = require('../../../../models/user');
const logger = require('../../../logger');

module.exports = (guildID, userID) => {
return new Promise((resolve, reject) => {
User.then(User=>User.findOneAndUpdate({ discordID: userID }, { $addToSet: { broadcastGuilds: guildID } }))
.then(user => {
if (!user) {
reject('No user found');
logger.log(new Error('No user found'));
} else {
resolve(true);
}
})
.catch(err=>logger.log(err));
})
}
3 changes: 3 additions & 0 deletions modules/kok-bot/modules/broadcasts/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports.add = require('./add');
module.exports.remove = require('./remove');
module.exports.list = require('./list');
33 changes: 33 additions & 0 deletions modules/kok-bot/modules/broadcasts/list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const User = require('../../../../models/user');
const client = require('../common/client');
const logger = require('../../../logger');

module.exports = userID => {
return new Promise((resolve, reject) => {
User.then(User=>User.findOne({ discordID: userID }))
.then(user => {
if (!user) {
reject('No user found');
logger.log(new Error('No user found'));
} else {
if (user.broadcastGuilds) {
if (user.broadcastGuilds.length > 0) {
let message = "```You are currently broadcasting to:\n";
user.broadcastGuilds.forEach(guildID => {
let guild = client.guilds.get(guildID);
let newLine = guild ? `${guild.name}\n`:`A guild I no longer exist in :(\n`;
message += newLine;
})
message += "```";
resolve(message);
} else {
resolve('You are not broadcasting to any guilds');
}
} else {
resolve('You are not broadcasting to any guilds');
}
}
})
.catch(err=>logger.log(err))
})
}
23 changes: 23 additions & 0 deletions modules/kok-bot/modules/broadcasts/remove.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const User = require('../../../../models/user');
const logger = require('../../../logger');

module.exports = (guildID, userID) => {
return new Promise((resolve, reject) => {

User.then(User=>User.findOneAndUpdate({discordID: userID}, { $pull: { broadcastGuilds: guildID } }))
.then(user => {
//see if guild was in original set anyway
let exists = user.broadcastGuilds.find(el => el === guildID)

if (exists) {
return resolve(true);
} else {
reject(false);
}
})
.catch(err => {
logger.log(err);
reject(err);
})
})
}
77 changes: 77 additions & 0 deletions modules/kok-bot/modules/common/commands/broadcasts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"use strict";
const logger = require('../../../../logger');
const reqAccess = require('../reqAccess');
const responseDict = require('../responseDict');
const help = require("./help");
let broadcast = require('../../broadcasts');

class Broadcasts {

exec(msg, commandArguments) {
let argsArray = [];
if (commandArguments.length !== 0) {
argsArray = commandArguments.split(" ");
}
if (argsArray.length > 0) {
let command = argsArray[0].toLowerCase();

if (this[command]) {
this[command](msg, argsArray)
} else {
msg.channel.sendMessage("Unknown command");
}
} else {
msg.channel.sendMessage(responseDict.noParams());
}
}

add(msg, argsArray) {
reqAccess(msg.guild, msg.member, 1)
.then(() => {
let thisGuild = msg.guild;
return broadcast.add(thisGuild.id, msg.member.id);
})
.then(wing => msg.channel.sendMessage(responseDict.success()))
.catch(err => {
logger.log(err);
msg.channel.sendMessage(responseDict.fail());
})
}

remove(msg, argsArray) {
reqAccess(msg.guild, msg.member, 1)
.then(() => {
return broadcast.remove(msg.guild.id, msg.member.id);
})
.then(wing => msg.channel.sendMessage(responseDict.success()))
.catch(err => {
logger.log(err);
msg.channel.sendMessage(responseDict.fail());
})
}

list(msg, argsArray) {
reqAccess(msg.guild, msg.member, 0)
.then(() => {
let thisGuild = msg.guild;
return broadcast.list(msg.member.id);
})
.then(res => msg.member.sendMessage(res))
.catch(err => {
logger.log(err);
msg.channel.sendMessage(responseDict.fail());
})
}
}

let helpMessage = "Adds,Removes the current guild to your list of broadcast targets or lists all your broadcast targets";
let template = "broadcast <add|remove|list>";
let example = [
"`-broadcasts add`",
"`-broadcasts remove`",
"`-broadcasts list`"
];

help.AddHelp("wings", helpMessage, template, example);

module.exports = new Broadcasts();
3 changes: 2 additions & 1 deletion modules/kok-bot/modules/common/commands/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ module.exports.initiateCommands = () => {
this.commandsMap.set("karma", require("./karma"));
this.commandsMap.set("errorlogs", require("./error-logs"));
this.commandsMap.set("version", require("./version"));
this.commandsMap.set("events", require("./events.js"));
this.commandsMap.set("events", require("./events"));
this.commandsMap.set("broadcasts", require("./broadcasts"));
}

client.on("message", msg => {
Expand Down
4 changes: 3 additions & 1 deletion modules/kok-bot/modules/companion/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
let interdicted = require('./interdicted');
let missionCompleted = require('./mission-completed');

module.exports = {
interdicted
interdicted,
missionCompleted
}
33 changes: 33 additions & 0 deletions modules/kok-bot/modules/companion/mission-completed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const discordGuildModel = require('../../../../models/discord-guild');
const client = require('../common/client');
const logger = require('../../../logger');

function alert(guildID, missionCompleted, cmdrName) {

let defaults = {
cmdrName: "Unknown CMDR",
Name: "Unknown Mission",
originator: "Unknown Faction"
}
missionCompleted = Object.assign(defaults, missionCompleted);

return discordGuildModel.findOne({guildID})
.then(guild=>{
if (guild) {
let targetChannelID = guild.logChannelID;
let targetChannel = client.channels.get(targetChannelID);
console.log(`mission completed to ${targetChannelID} ${targetChannel}`);
targetChannel.sendMessage(`MISSION COMPLETED: ${cmdrName.toUpperCase()} completed ${missionCompleted.Name.toUpperCase()} for ${missionCompleted.originator.toUpperCase()}`);
} else {
logger.log(`No such guild found`);
throw new Error('no such guild');
}
})
.catch(err=>{
logger.log(err);
})
}

module.exports = {
alert
}
2 changes: 1 addition & 1 deletion public/css/app.css

Large diffs are not rendered by default.

32 changes: 16 additions & 16 deletions public/js/app.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion public/js/app.min.js.map

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion public/modules/login/login-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module.exports = function (UserService, AuthService, $scope) {

vm.passwordRecovery = false;
vm.recoverySubmitted = false;
vm.remember = false;

vm.authentication = {
success: false,
Expand All @@ -30,7 +31,8 @@ module.exports = function (UserService, AuthService, $scope) {
vm.loginState = "loading"
return AuthService.authenticate({
username: vm.cmdrName,
password: vm.password
password: vm.password,
remember: vm.remember
})
.then(data => {
vm.loginState = "success"
Expand Down
6 changes: 6 additions & 0 deletions public/modules/login/login-template.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ <h1>And you are?</h1>
</div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="checkbox" name="remember" id="remember" ng-model="LoginCtrl.remember">
<label for="remember">Remember me</label>
</div>
</div>
<div class="row align-middle">
<div class="shrink columns">
<button type="submit" class="button" ng-disabled="loginForm.$invalid">Submit</button>
Expand Down
1 change: 1 addition & 0 deletions routes/companion-app/interdicted.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ router.post('/:cmdr',(req,res)=>{
if (user.username !== cmdrName) { throw new Error("commander name mismatch"); }
let interdictedEvent = req.body.interdicted;
let system = req.body.system;
//TODO: Refactor so that guildID is pulled from the logged in user and sent to THEIR guild(s)
let response = interdicted.alert("141575893691793408",interdictedEvent,cmdrName, system);
res.sendStatus(200);
})
Expand Down
41 changes: 41 additions & 0 deletions routes/companion-app/missions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
let router = require('express').Router();
let {missionCompleted} = require('../../modules/kok-bot/modules/companion');
let logger = require('../../modules/logger');

router.post('/completed/:cmdr',(req,res)=>{
let cmdrName = decodeURIComponent(req.params.cmdr);

if (!cmdrName) {
res.sendStatus(400) ;
logger.log(new Error("No cmdrName provided to route"));
return
}

if (!req.user) {
res.sendStatus(403)
logger.log(new Error("non-logged in user attempted to do a mission completed alert"));
return
}

require('../../models/user')
.then(User=>{
if (!User) { throw new Error("Fatal model error: no user model found"); }
return User.findOne(req.user)
})
.then(user=>{
if (!user) { throw new Error(`No such user found: ${req.user.username}`) }
if (user.username !== cmdrName) { throw new Error("commander name mismatch"); }
let missionCompletedEvent = req.body.missionCompleted;
//TODO: Refactor so that guildID is pulled from the logged in user and sent to THEIR guild(s)
return missionCompleted.alert("141575893691793408",missionCompletedEvent,cmdrName)
.then(response=>{
res.sendStatus(200).json(response);
})
})
.catch(err=>{
logger.log(err);
res.sendStatus(500);
})
})

module.exports = router;
25 changes: 16 additions & 9 deletions routes/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@ let passport = require('passport');

let dbConnected = require('../middleware/dbconnected');

router.post('/', dbConnected, passport.authenticate('local'),
function(req, res) {
router.post('/', dbConnected, passport.authenticate('local'),
function (req, res) {
require('../models/user')
.then(userModel=>{
return userModel.findOne({username: req.user.username});
})
.then(user=>res.json(user))
.catch(err=>{
.then(userModel => {
return userModel.findOne({ username: req.user.username });
})
.then(user => {
if (req.body.remember) {
let cookieMaxAge = 1000 * 60 * 60 * 24 * 14 //14 days
req.session.cookie.expires = new Date(Date.now() + cookieMaxAge);
req.session.cookie.maxAge = cookieMaxAge;
}
res.json(user);
})
.catch(err => {
console.log(err);
res.json(null);
})
});
})
});


module.exports = router;

0 comments on commit 6916550

Please sign in to comment.