From cb6adfbb7f0e0ac5f2fd33826d879e1355615450 Mon Sep 17 00:00:00 2001 From: Jon McCarthy Date: Tue, 13 Nov 2018 10:03:37 -0700 Subject: [PATCH] syntax clean up --- config/hasher.js | 41 +- config/routes.js | 61 ++- config/sessions.js | 25 +- controllers/favorites_controller.js | 46 +-- controllers/modes_controller.js | 302 +++++++------- controllers/users_controller.js | 383 +++++++++-------- controllers/votes_controller.js | 73 ++-- db/knex.js | 6 +- db/migrations/20181005135753_users.js | 13 +- db/migrations/20181005135801_modes.js | 17 +- db/migrations/20181005135824_favorites.js | 23 +- db/migrations/20181005135829_votes.js | 23 +- db/migrations/20181015220345_analytics.js | 6 +- db/seeds/01_users.js | 51 +-- db/seeds/02_modes.js | 208 +++++++++- db/seeds/03_favorites.js | 10 +- db/seeds/04_votes.js | 9 +- db/seeds/production/01_modes.js | 210 ++++++++-- knexfile.js | 52 +-- resources/js/export.js | 77 ++-- resources/js/header.js | 35 +- resources/js/login.js | 26 +- resources/js/modes.js | 85 ++-- resources/js/passwordChange.js | 32 +- resources/js/popover.js | 12 +- resources/js/setup.js | 477 +++++++++++----------- server.js | 16 +- views/account.ejs | 296 ++++++++++---- views/draft.ejs | 214 +++++----- views/export.ejs | 232 +++++++---- views/index.ejs | 109 +++-- views/partials/header.ejs | 93 +++-- 32 files changed, 1972 insertions(+), 1291 deletions(-) diff --git a/config/hasher.js b/config/hasher.js index 44e630e..c333c2f 100644 --- a/config/hasher.js +++ b/config/hasher.js @@ -1,35 +1,34 @@ -let bcrypt = require('bcrypt-nodejs'); +let bcrypt = require("bcrypt-nodejs"); let SALT_WORK_FACTOR = 10; module.exports = { - - hash: function(user){ - return new Promise((resolve, reject)=>{ + hash: function(user) { + return new Promise((resolve, reject) => { bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { - if (err) reject(err); + if (err) reject(err); - // hash the password using our new salt - bcrypt.hash(user.password, salt, null, function(err, hash) { //null? - if (err) reject(err); + // hash the password using our new salt + bcrypt.hash(user.password, salt, null, function(err, hash) { + //null? + if (err) reject(err); - // override the cleartext password with the hashed one - user.password = hash; - resolve(user); - }); + // override the cleartext password with the hashed one + user.password = hash; + resolve(user); + }); }); }); - }, - check: function(encryptedUser, user){ - return new Promise((resolve, reject)=>{ - bcrypt.compare(user.password, encryptedUser.password, function(err, isMatch) { - if (err) reject(err); - resolve(isMatch); + check: function(encryptedUser, user) { + return new Promise((resolve, reject) => { + bcrypt.compare(user.password, encryptedUser.password, function( + err, + isMatch + ) { + if (err) reject(err); + resolve(isMatch); }); }); - } - - }; diff --git a/config/routes.js b/config/routes.js index cdaf045..faa6659 100644 --- a/config/routes.js +++ b/config/routes.js @@ -1,61 +1,60 @@ -const users = require("../controllers/users_controller.js"); -const modes = require("../controllers/modes_controller.js"); -const votes = require("../controllers/votes_controller.js"); -const favorites = require("../controllers/favorites_controller.js"); +const users = require("../controllers/users_controller.js"); +const modes = require("../controllers/modes_controller.js"); +const votes = require("../controllers/votes_controller.js"); +const favorites = require("../controllers/favorites_controller.js"); -module.exports = function(app){ +module.exports = function(app) { app.use(createMessageArr); //ANALYTICS ROUTES - app.post('/draftcount', users.draftcount); + app.post("/draftcount", users.draftcount); //USER ROUTES - app.get('/', users.index); - app.post('/register', users.register); - app.post('/login', users.login); - app.get('/logout', users.logout); - app.get('/forgotpassword', users.forgotpassword); - app.post('/sendemail', users.sendemail); + app.get("/", users.index); + app.post("/register", users.register); + app.post("/login", users.login); + app.get("/logout", users.logout); + app.get("/forgotpassword", users.forgotpassword); + app.post("/sendemail", users.sendemail); - app.get('/setup/relative', users.setupRelative); - app.get('/setup/absolute', users.setupAbsolute); - app.get('/draft', users.draft); - app.get('/export', users.export); - app.post('/export', users.encode); + app.get("/setup/relative", users.setupRelative); + app.get("/setup/absolute", users.setupAbsolute); + app.get("/draft", users.draft); + app.get("/export", users.export); + app.post("/export", users.encode); //MODES ROUTES - app.get('/modes/:tab/:subtab', modes.browse); + app.get("/modes/:tab/:subtab", modes.browse); app.use(authenticateUser); - app.get('/user', users.account); - app.post('/user/delete', users.delete); - app.post('/user/resetpassword', users.password); - app.post('/modes', modes.create); - app.post('/modes/publish/:id', modes.publish); - app.post('/modes/publish_existing/:id', modes.publishExisting); - app.post('/modes/delete/:id', modes.delete); + app.get("/user", users.account); + app.post("/user/delete", users.delete); + app.post("/user/resetpassword", users.password); + app.post("/modes", modes.create); + app.post("/modes/publish/:id", modes.publish); + app.post("/modes/publish_existing/:id", modes.publishExisting); + app.post("/modes/delete/:id", modes.delete); //VOTES ROUTES - app.post('/modes/vote/:id/:tab/:subtab', votes.modeVote); //COMPLETE + app.post("/modes/vote/:id/:tab/:subtab", votes.modeVote); //COMPLETE //FAVORITES ROUTES - app.post('/modes/favorite/:id/:tab/:subtab', favorites.modeFavorite); //COMPLETE - + app.post("/modes/favorite/:id/:tab/:subtab", favorites.modeFavorite); //COMPLETE }; function authenticateUser(req, res, next) { if (!req.session.user_id) { - res.redirect('/'); + res.redirect("/"); } else { next(); } } -function createMessageArr(req, res, next){ - if(!req.session.messages){ +function createMessageArr(req, res, next) { + if (!req.session.messages) { req.session.messages = { loginErrors: [], registerErrors: [], diff --git a/config/sessions.js b/config/sessions.js index 54700f0..394a181 100644 --- a/config/sessions.js +++ b/config/sessions.js @@ -1,21 +1,22 @@ -const session = require('express-session'); -const KnexSessionStore = require('connect-session-knex')(session); -var knex = require('../db/knex.js'); +const session = require("express-session"); +const KnexSessionStore = require("connect-session-knex")(session); +var knex = require("../db/knex.js"); -module.exports = function(app){ +module.exports = function(app) { const store = new KnexSessionStore({ - knex: knex, - tablename: 'sessions' // optional. Defaults to 'sessions' + knex: knex, + tablename: "sessions" // optional. Defaults to 'sessions' }); - - app.use(session({ - secret: 'keyboard cat', + app.use( + session({ + secret: "keyboard cat", cookie: { - maxAge: 259200000000// 30 days + maxAge: 259200000000 // 30 days }, resave: false, saveUninitialized: false, store: store - })); -} + }) + ); +}; diff --git a/controllers/favorites_controller.js b/controllers/favorites_controller.js index 5c3a885..6739d21 100644 --- a/controllers/favorites_controller.js +++ b/controllers/favorites_controller.js @@ -1,29 +1,29 @@ const knex = require("../db/knex.js"); module.exports = { - modeFavorite: (req,res) => { + modeFavorite: (req, res) => { //Delete if favorited - knex('favorites') - .where({user_id: req.session.user_id, mode_id: req.params.id}) - .then((results) => { - if (results.length) { - knex('favorites') - .delete() - .where({user_id: req.session.user_id, mode_id: req.params.id}) - .then(() => { - res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); - }); - } else { - //Update if not favorited - knex('favorites') - .insert({ - user_id: req.session.user_id, - mode_id: req.params.id - }) - .then(() => { - res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); - }); - } - }); + knex("favorites") + .where({ user_id: req.session.user_id, mode_id: req.params.id }) + .then(results => { + if (results.length) { + knex("favorites") + .delete() + .where({ user_id: req.session.user_id, mode_id: req.params.id }) + .then(() => { + res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); + }); + } else { + //Update if not favorited + knex("favorites") + .insert({ + user_id: req.session.user_id, + mode_id: req.params.id + }) + .then(() => { + res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); + }); + } + }); } }; diff --git a/controllers/modes_controller.js b/controllers/modes_controller.js index 2550f3e..bb51d1b 100644 --- a/controllers/modes_controller.js +++ b/controllers/modes_controller.js @@ -9,173 +9,201 @@ module.exports = { const subtab = req.params.subtab; let isSingle = false; - - - - knex.select('modes.*', 'votes.user_id as hasVoted', 'favorites.user_id as hasFavorited') - .from('modes') + knex + .select( + "modes.*", + "votes.user_id as hasVoted", + "favorites.user_id as hasFavorited" + ) + .from("modes") .leftJoin( - knex('votes') - .where('votes.user_id', user_id) - .as('votes'), - 'modes.id','votes.mode_id') + knex("votes") + .where("votes.user_id", user_id) + .as("votes"), + "modes.id", + "votes.mode_id" + ) .leftJoin( - knex('favorites') - .where('favorites.user_id', user_id) - .as('favorites'), - 'modes.id','favorites.mode_id') - .orderBy('created_at', 'desc') - .then(modes => { - if (tab === "single") { - isSingle = true; - modes = modes.filter(mode => mode.id === + req.params.subtab) - } else if (tab === "basic") { - modes = modes.filter(mode => mode.type === "basic"); - } else if (tab === "community") { - modes = modes.filter(mode => mode.type === "community"); - if (subtab !== "newest") { - modes.sort((modeA, modeB) => modeB.votes - modeA.votes); - } - if (subtab === "trending") { - modes = modes.filter(mode => moment(mode.created_at).isAfter(moment().subtract(trendingDaysRange, 'd'))); + knex("favorites") + .where("favorites.user_id", user_id) + .as("favorites"), + "modes.id", + "favorites.mode_id" + ) + .orderBy("created_at", "desc") + .then(modes => { + if (tab === "single") { + isSingle = true; + modes = modes.filter(mode => mode.id === +req.params.subtab); + } else if (tab === "basic") { + modes = modes.filter(mode => mode.type === "basic"); + } else if (tab === "community") { + modes = modes.filter(mode => mode.type === "community"); + if (subtab !== "newest") { + modes.sort((modeA, modeB) => modeB.votes - modeA.votes); + } + if (subtab === "trending") { + modes = modes.filter(mode => + moment(mode.created_at).isAfter( + moment().subtract(trendingDaysRange, "d") + ) + ); + } + } else if (subtab === "created") { + modes = modes.filter( + mode => mode.creator_id === user_id && mode.type === "user" + ); + } else { + modes = modes.filter(mode => mode.hasFavorited); } - } else if (subtab === "created") { - modes = modes.filter(mode => mode.creator_id === user_id && mode.type === "user"); - } else { - modes = modes.filter(mode => mode.hasFavorited); - } - let heroList = ''; - for (const mode of modes) { - for (const hero of mode.settings.heroArray) { - heroList += `\n${hero}`; + let heroList = ""; + for (const mode of modes) { + for (const hero of mode.settings.heroArray) { + heroList += `\n${hero}`; + } + mode.heroList = + mode.settings.heroArray.length === 0 ? "All" : heroList; } - mode.heroList = mode.settings.heroArray.length === 0 ? "All" : heroList; - } - res.render('modes', { modes: modes, tab: tab, subtab: subtab, messages: req.session.messages, username: req.session.user_name, isSingle: isSingle }); - req.session.messages = { - loginErrors: [], - registerErrors: [], - resetError: [], - resetSuccess: [] - }; - req.session.save(); - }); + res.render("modes", { + modes: modes, + tab: tab, + subtab: subtab, + messages: req.session.messages, + username: req.session.user_name, + isSingle: isSingle + }); + req.session.messages = { + loginErrors: [], + registerErrors: [], + resetError: [], + resetSuccess: [] + }; + req.session.save(); + }); }, create: (req, res) => { let dupe = false; - knex('modes') - .then((modes) => { + knex("modes").then(modes => { for (const mode of modes) { - if (mode.type !== "user" && JSON.stringify(mode.settings) == JSON.stringify(req.body.settings)) { - res.json({dupe: true, id: mode.id}) + if ( + mode.type !== "user" && + JSON.stringify(mode.settings) == JSON.stringify(req.body.settings) + ) { + res.json({ dupe: true, id: mode.id }); dupe = true; return; } } if (!dupe) { - knex('modes') - .returning('modes.id') - .insert({ - mode_name: req.body.mode_name, - type: "user", - creator_id: req.session.user_id, - settings: req.body.settings - }) - .then((results) => { - res.json(results[0]) - }); + knex("modes") + .returning("modes.id") + .insert({ + mode_name: req.body.mode_name, + type: "user", + creator_id: req.session.user_id, + settings: req.body.settings + }) + .then(results => { + res.json(results[0]); + }); } }); }, publish: (req, res) => { - knex('modes') - .where('id', req.params.id) - .returning('*') + knex("modes") + .where("id", req.params.id) + .returning("*") .update({ - 'published': 'true' + published: "true" }) - .then(results => { - let dupe = false; - knex('modes') - .then((modes) => { - for (const mode of modes) { - if (mode.type === "community" && JSON.stringify(mode.settings) == JSON.stringify(results[0].settings)) { - res.json({dupe: true, id: mode.id}) - dupe = true; - return Promise.reject(); - } - } + .then(results => { + let dupe = false; + knex("modes") + .then(modes => { + for (const mode of modes) { + if ( + mode.type === "community" && + JSON.stringify(mode.settings) == + JSON.stringify(results[0].settings) + ) { + res.json({ dupe: true, id: mode.id }); + dupe = true; + return Promise.reject(); + } + } - if (!dupe) { - const mode = results[0]; - if (mode.creator_id === req.session.user_id) { - return knex('modes') - .insert({ - mode_name: mode.mode_name, - type: 'community', - creator_id: mode.creator_id, - settings: mode.settings - }); - } - } - }) - .then(() => res.redirect('/modes/user/created')) - }) + if (!dupe) { + const mode = results[0]; + if (mode.creator_id === req.session.user_id) { + return knex("modes").insert({ + mode_name: mode.mode_name, + type: "community", + creator_id: mode.creator_id, + settings: mode.settings + }); + } + } + }) + .then(() => res.redirect("/modes/user/created")); + }); }, publishExisting: (req, res) => { - knex('modes') - .where('id', req.params.id) - .returning('*') - .update({ - 'published': 'true' - }) - .then(results => { - let dupe = false; - knex('modes') - .then((modes) => { - for (const mode of modes) { - if (mode.type === "community" && JSON.stringify(mode.settings) == JSON.stringify(results[0].settings)) { - res.redirect(`/modes/single/${mode.id}`) - dupe = true; - return Promise.reject(); - } - } + knex("modes") + .where("id", req.params.id) + .returning("*") + .update({ + published: "true" + }) + .then(results => { + let dupe = false; + knex("modes") + .then(modes => { + for (const mode of modes) { + if ( + mode.type === "community" && + JSON.stringify(mode.settings) == + JSON.stringify(results[0].settings) + ) { + res.redirect(`/modes/single/${mode.id}`); + dupe = true; + return Promise.reject(); + } + } - if (!dupe) { - const mode = results[0]; - if (mode.creator_id === req.session.user_id) { - return knex('modes') - .insert({ - mode_name: mode.mode_name, - type: 'community', - creator_id: mode.creator_id, - settings: mode.settings - }); - } - } - }) - .then(() => res.redirect('/modes/user/created')) - }) + if (!dupe) { + const mode = results[0]; + if (mode.creator_id === req.session.user_id) { + return knex("modes").insert({ + mode_name: mode.mode_name, + type: "community", + creator_id: mode.creator_id, + settings: mode.settings + }); + } + } + }) + .then(() => res.redirect("/modes/user/created")); + }); }, delete: (req, res) => { - knex('modes') - .where('id', req.params.id) - .then(results => { - if (results[0].creator_id === req.session.user_id) { - knex('modes') - .where('id', req.params.id) - .del() - .then(() => { - res.redirect('/modes/user/created'); - }); - } - }); - }, + knex("modes") + .where("id", req.params.id) + .then(results => { + if (results[0].creator_id === req.session.user_id) { + knex("modes") + .where("id", req.params.id) + .del() + .then(() => { + res.redirect("/modes/user/created"); + }); + } + }); + } // browsemore: (req, res) => { // knex.select('modes.*', 'votes.user_id as hasVoted').from('modes').leftJoin('votes', 'modes.id', 'votes.mode_id').where('votes.user_id', req.session.user_id).orWhere('votes.user_id', null).then(votes => { diff --git a/controllers/users_controller.js b/controllers/users_controller.js index 4d67450..07a0207 100644 --- a/controllers/users_controller.js +++ b/controllers/users_controller.js @@ -1,12 +1,15 @@ const knex = require("../db/knex.js"); const hasher = require("../config/hasher.js"); const deckstrings = require("deckstrings"); -const nodemailer = require('nodemailer'); -const xoauth2 = require('xoauth2'); +const nodemailer = require("nodemailer"); +const xoauth2 = require("xoauth2"); module.exports = { index: (req, res) => { - res.render('index', {messages: req.session.messages, username: req.session.user_name}); + res.render("index", { + messages: req.session.messages, + username: req.session.user_name + }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -17,7 +20,10 @@ module.exports = { }, setupRelative: (req, res) => { - res.render('setup-relative', {messages: req.session.messages, username: req.session.user_name}); + res.render("setup-relative", { + messages: req.session.messages, + username: req.session.user_name + }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -28,7 +34,10 @@ module.exports = { }, setupAbsolute: (req, res) => { - res.render('setup-absolute', {messages: req.session.messages, username: req.session.user_name}); + res.render("setup-absolute", { + messages: req.session.messages, + username: req.session.user_name + }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -36,11 +45,13 @@ module.exports = { resetSuccess: [] }; req.session.save(); - }, draft: (req, res) => { - res.render('draft', {messages: req.session.messages, username: req.session.user_name}); + res.render("draft", { + messages: req.session.messages, + username: req.session.user_name + }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -51,7 +62,10 @@ module.exports = { }, export: (req, res) => { - res.render('export', {messages: req.session.messages, username: req.session.user_name}); + res.render("export", { + messages: req.session.messages, + username: req.session.user_name + }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -62,66 +76,70 @@ module.exports = { }, register: (req, res) => { - hasher.hash(req.body).then((user)=>{ - knex('users') - .insert({ - user_name: user.username, - email: user.email, - password: user.password, - }) - .then(() => res.redirect('/')) - .catch(err => { - console.log(err); - if (err.code == 23505) { - req.session.messages.registerErrors.push("User with that email already exists."); - } - req.session.save(() => { - res.redirect('/'); - }); + hasher.hash(req.body).then(user => { + knex("users") + .insert({ + user_name: user.username, + email: user.email, + password: user.password + }) + .then(() => res.redirect("/")) + .catch(err => { + console.log(err); + if (err.code == 23505) { + req.session.messages.registerErrors.push( + "User with that email already exists." + ); + } + req.session.save(() => { + res.redirect("/"); + }); + }); }); - }); }, login: (req, res) => { - knex('users') - .where('email', req.body.email) - .then(results => { - const user = results[0]; - if (!user) { - req.session.messages.loginErrors.push("Email or password incorrect."); - req.session.save(() => { - res.redirect('/'); - return; - }); - } - if(user){ - hasher.check(user, req.body).then((isMatch)=>{ - if(isMatch){ - req.session.user_id = user.id; - req.session.user_name = user.user_name; - req.session.save(() => { - res.redirect('/'); - }); - } else { - req.session.messages.loginErrors.push("Email or password incorrect."); - req.session.save(() => { - res.redirect('/'); - return; - }); - } - }); - } - }); + knex("users") + .where("email", req.body.email) + .then(results => { + const user = results[0]; + if (!user) { + req.session.messages.loginErrors.push("Email or password incorrect."); + req.session.save(() => { + res.redirect("/"); + return; + }); + } + if (user) { + hasher.check(user, req.body).then(isMatch => { + if (isMatch) { + req.session.user_id = user.id; + req.session.user_name = user.user_name; + req.session.save(() => { + res.redirect("/"); + }); + } else { + req.session.messages.loginErrors.push( + "Email or password incorrect." + ); + req.session.save(() => { + res.redirect("/"); + return; + }); + } + }); + } + }); }, logout: (req, res) => { req.session.destroy(() => { - res.redirect('/'); + res.redirect("/"); }); }, forgotpassword: (req, res) => { - res.render('password', {messages: req.session.messages}); + res.render("password", { messages: req.session.messages }); req.session.messages = { loginErrors: [], registerErrors: [], @@ -132,7 +150,7 @@ module.exports = { }, sendemail: (req, res) => { - let temporary = Math.floor(Math.random() * (999999 - 100000 + 1) ) + 100000 + let temporary = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000; let output = `

Instructions

@@ -140,139 +158,146 @@ module.exports = {

***IMPORTANT*** Make sure you go in right away and change this to your new password. You can do this by loggin in and clicking your account icon in the upper right corner and then resetting your password.


Temporary Password:${temporary} - ` + `; // create reusable transporter object using the default SMTP transport - let transporter = nodemailer.createTransport({ + let transporter = nodemailer.createTransport({ + // service: 'gmail', + // auth: { + // xoauth2: xoauth2.createXOAuth2Generator({ + // user: 'draftstonebeta@gmail.com', + // clientId: '', + // clientSecret: '', + // refreshToken: '', + // }) + // } - // service: 'gmail', - // auth: { - // xoauth2: xoauth2.createXOAuth2Generator({ - // user: 'draftstonebeta@gmail.com', - // clientId: '', - // clientSecret: '', - // refreshToken: '', - // }) - // } - - host: 'smtp.gmail.com', - port: 465, - secure: true, // true for 465, false for other ports - auth: { - user: 'draftstonebeta@gmail.com', // generated ethereal user - pass: 'g100rocks!' // generated ethereal password - }, - tls:{ - rejectUnauthorized: false - } - }); + host: "smtp.gmail.com", + port: 465, + secure: true, // true for 465, false for other ports + auth: { + user: "draftstonebeta@gmail.com", // generated ethereal user + pass: "g100rocks!" // generated ethereal password + }, + tls: { + rejectUnauthorized: false + } + }); - // setup email data with unicode symbols - let mailOptions = { - from: '"Draftstone Team" ', // sender address - to: 'seanjtayler@gmail.com', // list of receivers `${req.body.email}` - subject: 'Temporary Password', // Subject line - text: '', // plain text body - html: output // html body - }; + // setup email data with unicode symbols + let mailOptions = { + from: '"Draftstone Team" ', // sender address + to: "seanjtayler@gmail.com", // list of receivers `${req.body.email}` + subject: "Temporary Password", // Subject line + text: "", // plain text body + html: output // html body + }; - // send mail with defined transport object - transporter.sendMail(mailOptions, (error, info) => { - if (error) { - return console.log(error); - } - console.log('Message sent: %s', info.messageId); - console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); - }); + // send mail with defined transport object + transporter.sendMail(mailOptions, (error, info) => { + if (error) { + return console.log(error); + } + console.log("Message sent: %s", info.messageId); + console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); + }); - const unhashedUser = { - password: `${temporary}` - }; - hasher.hash(unhashedUser) - .then((updatedUser) => { - knex('users') - .where('email', req.body.email) - .update({ - password: updatedUser.password - }) - .then(() => { - req.session.messages.resetSuccess.push("Email Sent!"); - req.session.save(() => { - res.redirect('/forgotpassword'); - return; - }) - }); - }) + const unhashedUser = { + password: `${temporary}` + }; + hasher.hash(unhashedUser).then(updatedUser => { + knex("users") + .where("email", req.body.email) + .update({ + password: updatedUser.password + }) + .then(() => { + req.session.messages.resetSuccess.push("Email Sent!"); + req.session.save(() => { + res.redirect("/forgotpassword"); + return; + }); + }); + }); }, draftcount: (req, res) => { - knex('analytics').where('id', 1).increment('drafts', 1) - .then((drafts)=>{ - res.sendStatus(201); - }); + knex("analytics") + .where("id", 1) + .increment("drafts", 1) + .then(drafts => { + res.sendStatus(201); + }); }, account: (req, res) => { - knex('users').where('id', req.session.user_id).then((users)=>{ - res.render('account', {users: users, messages: req.session.messages, username: req.session.user_name}); - req.session.messages = { - loginErrors: [], - registerErrors: [], - resetError: [], - resetSuccess: [] - }; - req.session.save(); - }); + knex("users") + .where("id", req.session.user_id) + .then(users => { + res.render("account", { + users: users, + messages: req.session.messages, + username: req.session.user_name + }); + req.session.messages = { + loginErrors: [], + registerErrors: [], + resetError: [], + resetSuccess: [] + }; + req.session.save(); + }); }, delete: (req, res) => { - knex('modes') - .where({"type": "user", "creator_id": req.session.user_id}) + knex("modes") + .where({ type: "user", creator_id: req.session.user_id }) .del() - .then(() => { - knex('users').del().where('id', req.session.user_id).then(()=>{ - req.session.destroy(() => { - res.redirect('/'); - }); + .then(() => { + knex("users") + .del() + .where("id", req.session.user_id) + .then(() => { + req.session.destroy(() => { + res.redirect("/"); + }); + }); }); - }); }, password: (req, res) => { - knex('users') - .where('id', req.session.user_id) - .then((results)=>{ - let user = results[0]; - hasher.check(user, req.body) - .then((isMatch) => { - if(isMatch){ - unhashedUser = { - password: req.body.newpassword - }; - hasher.hash(unhashedUser) - .then((updatedUser) => { - knex('users') - .where('id', req.session.user_id) - .update({ - password: updatedUser.password - }) - .then(() => { - req.session.messages.resetSuccess.push("Password updated!"); - req.session.save(() => { - res.redirect('/user'); - return; - }); + knex("users") + .where("id", req.session.user_id) + .then(results => { + let user = results[0]; + hasher.check(user, req.body).then(isMatch => { + if (isMatch) { + unhashedUser = { + password: req.body.newpassword + }; + hasher.hash(unhashedUser).then(updatedUser => { + knex("users") + .where("id", req.session.user_id) + .update({ + password: updatedUser.password + }) + .then(() => { + req.session.messages.resetSuccess.push("Password updated!"); + req.session.save(() => { + res.redirect("/user"); + return; + }); + }); }); - }); - } else { - req.session.messages.resetError.push("Password incorrect."); - req.session.save(() => { - res.redirect('/user'); - return; - }); - } + } else { + req.session.messages.resetError.push("Password incorrect."); + req.session.save(() => { + res.redirect("/user"); + return; + }); + } + }); }); - }); }, encode: (req, res) => { @@ -280,24 +305,20 @@ module.exports = { const heroCard = req.body.heroCard; const cards = []; for (let i = 0; i < 30; i++) { - if (i < 29 && deck[i].dbfId === deck[i + 1].dbfId) { - cards.push([+ deck[i].dbfId, 2]); - i++; - } - else { - cards.push([+ deck[i].dbfId, 1]); - } + if (i < 29 && deck[i].dbfId === deck[i + 1].dbfId) { + cards.push([+deck[i].dbfId, 2]); + i++; + } else { + cards.push([+deck[i].dbfId, 1]); + } } const encodableDeck = { - 'cards': cards, - heroes: [+ heroCard.dbfId], - format: 1 + cards: cards, + heroes: [+heroCard.dbfId], + format: 1 }; - const deckstring = deckstrings.encode(encodableDeck); res.json(deckstring); - } - }; diff --git a/controllers/votes_controller.js b/controllers/votes_controller.js index d856209..1f236a2 100644 --- a/controllers/votes_controller.js +++ b/controllers/votes_controller.js @@ -1,44 +1,43 @@ const knex = require("../db/knex.js"); module.exports = { - modeVote: (req,res) => { + modeVote: (req, res) => { //Delete and Decrement if voted - knex('votes') - .where({user_id: req.session.user_id, mode_id: req.params.id}) - .then((results) => { - if (results.length) { - knex('votes') - .delete() - .where({user_id: req.session.user_id, mode_id: req.params.id}) - .then(() => { - return knex('modes') - .where('id', req.params.id) - .decrement('votes', 1); - }) - .then(() => { - res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); - }); - } - //Insert and Increment if not voted - else { - knex('votes') - .insert({ - user_id: req.session.user_id, - mode_id: req.params.id - }) - .then(() => { - return knex('modes') - .where('id', req.params.id) - .increment('votes', 1); - }) - .then(() => { - res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); - }); - } - knex('modes') - .where('id', req.params.id) - .then(mode => { + knex("votes") + .where({ user_id: req.session.user_id, mode_id: req.params.id }) + .then(results => { + if (results.length) { + knex("votes") + .delete() + .where({ user_id: req.session.user_id, mode_id: req.params.id }) + .then(() => { + return knex("modes") + .where("id", req.params.id) + .decrement("votes", 1); + }) + .then(() => { + res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); + }); + } + //Insert and Increment if not voted + else { + knex("votes") + .insert({ + user_id: req.session.user_id, + mode_id: req.params.id + }) + .then(() => { + return knex("modes") + .where("id", req.params.id) + .increment("votes", 1); + }) + .then(() => { + res.redirect(`/modes/${req.params.tab}/${req.params.subtab}`); + }); + } + knex("modes") + .where("id", req.params.id) + .then(mode => {}); }); - }); } }; diff --git a/db/knex.js b/db/knex.js index 58cd1b8..01b512d 100644 --- a/db/knex.js +++ b/db/knex.js @@ -1,4 +1,4 @@ -var environment = process.env.NODE_ENV || 'development'; -var config = require('../knexfile.js')[environment]; +var environment = process.env.NODE_ENV || "development"; +var config = require("../knexfile.js")[environment]; console.log(config); -module.exports = require('knex')(config); +module.exports = require("knex")(config); diff --git a/db/migrations/20181005135753_users.js b/db/migrations/20181005135753_users.js index 6d4030e..7cb64e7 100644 --- a/db/migrations/20181005135753_users.js +++ b/db/migrations/20181005135753_users.js @@ -1,15 +1,14 @@ - exports.up = function(knex, Promise) { - return knex.schema.createTable('users', table => { + return knex.schema.createTable("users", table => { table.increments(); - table.string('user_name'); - table.string('password'); - table.string('email').unique(); - table.json('collection'); + table.string("user_name"); + table.string("password"); + table.string("email").unique(); + table.json("collection"); table.timestamps(true, true); }); }; exports.down = function(knex, Promise) { - return knex.schema.dropTable('users'); + return knex.schema.dropTable("users"); }; diff --git a/db/migrations/20181005135801_modes.js b/db/migrations/20181005135801_modes.js index eb8ccaf..418e949 100644 --- a/db/migrations/20181005135801_modes.js +++ b/db/migrations/20181005135801_modes.js @@ -1,17 +1,16 @@ - exports.up = function(knex, Promise) { - return knex.schema.createTable('modes', table => { + return knex.schema.createTable("modes", table => { table.increments(); - table.string('mode_name'); - table.string('type'); - table.integer('votes').defaultTo(0); - table.integer('creator_id'); - table.json('settings'); - table.boolean('published').defaultTo('false'); + table.string("mode_name"); + table.string("type"); + table.integer("votes").defaultTo(0); + table.integer("creator_id"); + table.json("settings"); + table.boolean("published").defaultTo("false"); table.timestamps(true, true); }); }; exports.down = function(knex, Promise) { - return knex.schema.dropTable('modes'); + return knex.schema.dropTable("modes"); }; diff --git a/db/migrations/20181005135824_favorites.js b/db/migrations/20181005135824_favorites.js index 35a84ea..5df2ae8 100644 --- a/db/migrations/20181005135824_favorites.js +++ b/db/migrations/20181005135824_favorites.js @@ -1,23 +1,24 @@ - exports.up = function(knex, Promise) { - return knex.schema.createTable('favorites', table => { + return knex.schema.createTable("favorites", table => { table.increments(); - table.integer('user_id') + table + .integer("user_id") .notNullable() - .references('id') - .inTable('users') - .onDelete('CASCADE') + .references("id") + .inTable("users") + .onDelete("CASCADE") .index(); - table.integer('mode_id') + table + .integer("mode_id") .notNullable() - .references('id') - .inTable('modes') - .onDelete('CASCADE') + .references("id") + .inTable("modes") + .onDelete("CASCADE") .index(); table.timestamps(true, true); }); }; exports.down = function(knex, Promise) { - return knex.schema.dropTable('favorites'); + return knex.schema.dropTable("favorites"); }; diff --git a/db/migrations/20181005135829_votes.js b/db/migrations/20181005135829_votes.js index 534a5b3..b180749 100644 --- a/db/migrations/20181005135829_votes.js +++ b/db/migrations/20181005135829_votes.js @@ -1,23 +1,24 @@ - exports.up = function(knex, Promise) { - return knex.schema.createTable('votes', table => { + return knex.schema.createTable("votes", table => { table.increments(); - table.integer('user_id') + table + .integer("user_id") .notNullable() - .references('id') - .inTable('users') - .onDelete('CASCADE') + .references("id") + .inTable("users") + .onDelete("CASCADE") .index(); - table.integer('mode_id') + table + .integer("mode_id") .notNullable() - .references('id') - .inTable('modes') - .onDelete('CASCADE') + .references("id") + .inTable("modes") + .onDelete("CASCADE") .index(); table.timestamps(true, true); }); }; exports.down = function(knex, Promise) { - return knex.schema.dropTable('votes'); + return knex.schema.dropTable("votes"); }; diff --git a/db/migrations/20181015220345_analytics.js b/db/migrations/20181015220345_analytics.js index f538b48..31a9ecb 100644 --- a/db/migrations/20181015220345_analytics.js +++ b/db/migrations/20181015220345_analytics.js @@ -1,11 +1,11 @@ exports.up = function(knex, Promise) { - return knex.schema.createTable('analytics', table => { + return knex.schema.createTable("analytics", table => { table.increments(); - table.integer('drafts'); + table.integer("drafts"); table.timestamps(true, true); }); }; exports.down = function(knex, Promise) { - return knex.schema.dropTable('analytics'); + return knex.schema.dropTable("analytics"); }; diff --git a/db/seeds/01_users.js b/db/seeds/01_users.js index c843b6f..c914c4d 100644 --- a/db/seeds/01_users.js +++ b/db/seeds/01_users.js @@ -2,39 +2,42 @@ const hasher = require("../../config/hasher.js"); exports.seed = function(knex, Promise) { // Deletes ALL existing entries - return knex('users').del() - .then(function () { + return knex("users") + .del() + .then(function() { // Inserts seed entries const leandro = { - user_name: 'lschuab', - password: 'as', - email: 'lschuab@gmail.com', + user_name: "lschuab", + password: "as", + email: "lschuab@gmail.com" }; const sean = { - user_name: 'sean', - password: 'yes', - email: 'sean@gmail.com', + user_name: "sean", + password: "yes", + email: "sean@gmail.com" }; const promiseArr = []; - promiseArr.push(hasher.hash(leandro).then(leandro => { - return knex('users').insert({ - user_name: leandro.user_name, - password: leandro.password, - email: leandro.email - }); - })); - promiseArr.push(hasher.hash(sean).then(sean => { - return knex('users').insert({ - user_name: sean.user_name, - password: sean.password, - email: sean.email - }); - })); + promiseArr.push( + hasher.hash(leandro).then(leandro => { + return knex("users").insert({ + user_name: leandro.user_name, + password: leandro.password, + email: leandro.email + }); + }) + ); + promiseArr.push( + hasher.hash(sean).then(sean => { + return knex("users").insert({ + user_name: sean.user_name, + password: sean.password, + email: sean.email + }); + }) + ); return Promise.all(promiseArr); - - }); }; diff --git a/db/seeds/02_modes.js b/db/seeds/02_modes.js index 01fc074..ad45f0e 100644 --- a/db/seeds/02_modes.js +++ b/db/seeds/02_modes.js @@ -1,64 +1,228 @@ - exports.seed = function(knex, Promise) { // Deletes ALL existing entries - return knex('modes').del() - .then(function () { + return knex("modes") + .del() + .then(function() { // Inserts seed entries - return knex('modes').insert([ + return knex("modes").insert([ { - mode_name: 'Wildest Dreams', + mode_name: "Wildest Dreams", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame","Naxxramas","Goblins vs Gnomes","Blackrock Mountain","The Grand Tournament","The League of Explorers","Whispers of the Old Gods","One Night in Karazhan","Mean Streets of Gadgetzan"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Basic", + "Classic", + "Hall of Fame", + "Naxxramas", + "Goblins vs Gnomes", + "Blackrock Mountain", + "The Grand Tournament", + "The League of Explorers", + "Whispers of the Old Gods", + "One Night in Karazhan", + "Mean Streets of Gadgetzan" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Standard Procedures', + mode_name: "Standard Procedures", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame","Journey to Un'Goro","Knights of the Frozen Throne","Kobolds & Catacombs","The Witchwood","The Boomsday Project"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Basic", + "Classic", + "Hall of Fame", + "Journey to Un'Goro", + "Knights of the Frozen Throne", + "Kobolds & Catacombs", + "The Witchwood", + "The Boomsday Project" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null } }, { - mode_name: 'Classically Trained', + mode_name: "Classically Trained", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: ["Basic", "Classic", "Hall of Fame"], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Feeling Adventurous', + mode_name: "Feeling Adventurous", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Naxxramas","Blackrock Mountain","The League of Explorers","One Night in Karazhan"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Naxxramas", + "Blackrock Mountain", + "The League of Explorers", + "One Night in Karazhan" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'New Cards on the Block', + mode_name: "New Cards on the Block", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Kobolds & Catacombs","The Witchwood","The Boomsday Project"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Kobolds & Catacombs", + "The Witchwood", + "The Boomsday Project" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Living Legends', + mode_name: "Living Legends", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"custom","legendaryCount":"30","epicCount":"0","rareCount":"0","typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "custom", + legendaryCount: "30", + epicCount: "0", + rareCount: "0", + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Spellbound', + mode_name: "Spellbound", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"all","costArray":[],"classSetting":"custom","classCount":"30","raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"custom","spellCount":"30"} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "all", + costArray: [], + classSetting: "custom", + classCount: "30", + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "custom", + spellCount: "30" + } }, { - mode_name: 'Wisp me Away', + mode_name: "Wisp me Away", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"custom","costArray":["0","1","2","3"],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "custom", + costArray: ["0", "1", "2", "3"], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Aggro-a-phobic', + mode_name: "Aggro-a-phobic", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"custom","costArray":["7","8","9","10+"],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "custom", + costArray: ["7", "8", "9", "10+"], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } } ]); }); diff --git a/db/seeds/03_favorites.js b/db/seeds/03_favorites.js index b6ce323..02b8194 100644 --- a/db/seeds/03_favorites.js +++ b/db/seeds/03_favorites.js @@ -1,11 +1,9 @@ - exports.seed = function(knex, Promise) { // Deletes ALL existing entries - return knex('favorites').del() - .then(function () { + return knex("favorites") + .del() + .then(function() { // Inserts seed entries - return knex('favorites').insert([ - - ]); + return knex("favorites").insert([]); }); }; diff --git a/db/seeds/04_votes.js b/db/seeds/04_votes.js index 9ca3ea1..b71ba2a 100644 --- a/db/seeds/04_votes.js +++ b/db/seeds/04_votes.js @@ -1,10 +1,9 @@ - exports.seed = function(knex, Promise) { // Deletes ALL existing entries - return knex('votes').del() - .then(function () { + return knex("votes") + .del() + .then(function() { // Inserts seed entries - return knex('votes').insert([ - ]); + return knex("votes").insert([]); }); }; diff --git a/db/seeds/production/01_modes.js b/db/seeds/production/01_modes.js index d83e2a1..ad45f0e 100644 --- a/db/seeds/production/01_modes.js +++ b/db/seeds/production/01_modes.js @@ -1,65 +1,229 @@ - exports.seed = function(knex, Promise) { // Deletes ALL existing entries - return knex('modes').del() - .then(function () { + return knex("modes") + .del() + .then(function() { // Inserts seed entries - return knex('modes').insert([ + return knex("modes").insert([ { - mode_name: 'Wildest Dreams', + mode_name: "Wildest Dreams", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame","Naxxramas","Goblins vs Gnomes","Blackrock Mountain","The Grand Tournament","The League of Explorers","Whispers of the Old Gods","One Night in Karazhan","Mean Streets of Gadgetzan"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Basic", + "Classic", + "Hall of Fame", + "Naxxramas", + "Goblins vs Gnomes", + "Blackrock Mountain", + "The Grand Tournament", + "The League of Explorers", + "Whispers of the Old Gods", + "One Night in Karazhan", + "Mean Streets of Gadgetzan" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Standard Procedures', + mode_name: "Standard Procedures", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame","Journey to Un'Goro","Knights of the Frozen Throne","Kobolds & Catacombs","The Witchwood","The Boomsday Project"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Basic", + "Classic", + "Hall of Fame", + "Journey to Un'Goro", + "Knights of the Frozen Throne", + "Kobolds & Catacombs", + "The Witchwood", + "The Boomsday Project" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null } }, { - mode_name: 'Classically Trained', + mode_name: "Classically Trained", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Basic","Classic","Hall of Fame"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: ["Basic", "Classic", "Hall of Fame"], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Feeling Adventurous', + mode_name: "Feeling Adventurous", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Naxxramas","Blackrock Mountain","The League of Explorers","One Night in Karazhan"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Naxxramas", + "Blackrock Mountain", + "The League of Explorers", + "One Night in Karazhan" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'New Cards on the Block', + mode_name: "New Cards on the Block", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"custom","setArray":["Kobolds & Catacombs","The Witchwood","The Boomsday Project"],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "custom", + setArray: [ + "Kobolds & Catacombs", + "The Witchwood", + "The Boomsday Project" + ], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Living Legends', + mode_name: "Living Legends", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"all","costArray":[],"classSetting":"chaos","classCount":null,"raritySetting":"custom","legendaryCount":"30","epicCount":"0","rareCount":"0","typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "all", + costArray: [], + classSetting: "chaos", + classCount: null, + raritySetting: "custom", + legendaryCount: "30", + epicCount: "0", + rareCount: "0", + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Spellbound', + mode_name: "Spellbound", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"all","costArray":[],"classSetting":"custom","classCount":"30","raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"custom","spellCount":"30"} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "all", + costArray: [], + classSetting: "custom", + classCount: "30", + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "custom", + spellCount: "30" + } }, { - mode_name: 'Wisp me Away', + mode_name: "Wisp me Away", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"custom","costArray":["0","1","2","3"],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "custom", + costArray: ["0", "1", "2", "3"], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } }, { - mode_name: 'Aggro-a-phobic', + mode_name: "Aggro-a-phobic", type: "basic", creator_id: 2, - settings: {"heroFilterSetting":"all","heroArray":[],"setFilterSetting":"all","setArray":[],"costFilterSetting":"custom","costArray":["7","8","9","10+"],"classSetting":"chaos","classCount":null,"raritySetting":"chaos","legendaryCount":null,"epicCount":null,"rareCount":null,"typeSetting":"chaos","spellCount":null} - }, + settings: { + heroFilterSetting: "all", + heroArray: [], + setFilterSetting: "all", + setArray: [], + costFilterSetting: "custom", + costArray: ["7", "8", "9", "10+"], + classSetting: "chaos", + classCount: null, + raritySetting: "chaos", + legendaryCount: null, + epicCount: null, + rareCount: null, + typeSetting: "chaos", + spellCount: null + } + } ]); }); }; diff --git a/knexfile.js b/knexfile.js index 7fe22f9..cace18e 100644 --- a/knexfile.js +++ b/knexfile.js @@ -1,32 +1,32 @@ -console.log(process.env) +console.log(process.env); module.exports = { development: { - client: 'pg', - connection: { - database: "draftstone", - host: "localhost" - }, - migrations: { - directory: __dirname + '/db/migrations', - }, - seeds: { - directory: __dirname + '/db/seeds', - }, + client: "pg", + connection: { + database: "draftstone", + host: "localhost" }, + migrations: { + directory: __dirname + "/db/migrations" + }, + seeds: { + directory: __dirname + "/db/seeds" + } + }, production: { - client: 'pg', - connection: { - host: process.env.RDS_HOSTNAME, - user: process.env.RDS_USERNAME, - database: 'ebdb', - password: process.env.RDS_PASSWORD, - port: 5432 - }, - migrations: { - directory: __dirname + '/db/migrations', - }, - seeds: { - directory: __dirname + '/db/seeds/production', - }, + client: "pg", + connection: { + host: process.env.RDS_HOSTNAME, + user: process.env.RDS_USERNAME, + database: "ebdb", + password: process.env.RDS_PASSWORD, + port: 5432 + }, + migrations: { + directory: __dirname + "/db/migrations" }, + seeds: { + directory: __dirname + "/db/seeds/production" + } + } }; diff --git a/resources/js/export.js b/resources/js/export.js index 0d10e38..c2bb505 100644 --- a/resources/js/export.js +++ b/resources/js/export.js @@ -1,25 +1,23 @@ -const deck = JSON.parse(localStorage.getItem('deck')); -const heroCard = JSON.parse(localStorage.getItem('heroCard')); +const deck = JSON.parse(localStorage.getItem("deck")); +const heroCard = JSON.parse(localStorage.getItem("heroCard")); const data = { - "deck": deck, - "heroCard": heroCard + deck: deck, + heroCard: heroCard }; -const exportDeck = document.getElementById('export-deck'); -const deckstringInput = document.getElementById('deckstring-input'); -const clipboard = document.getElementById('clipboard'); +const exportDeck = document.getElementById("export-deck"); +const deckstringInput = document.getElementById("deckstring-input"); +const clipboard = document.getElementById("clipboard"); - -axios.post('/export', data) -.then(deckstring => { - exportDeck.addEventListener('click', () => { - deckstringInput.innerHTML = JSON.stringify(deckstring.data).slice(1,-1); +axios.post("/export", data).then(deckstring => { + exportDeck.addEventListener("click", () => { + deckstringInput.innerHTML = JSON.stringify(deckstring.data).slice(1, -1); }); }); //copy to clipboard -function copyToClipboard(id){ +function copyToClipboard(id) { // Create an auxiliary hidden input var aux = document.createElement("input"); // Get the text from the element passed into the input @@ -34,46 +32,45 @@ function copyToClipboard(id){ document.body.removeChild(aux); } - - const customRules = JSON.parse(localStorage.getItem("customRules")); -const modeName = document.getElementById('mode-name-input'); -const saveModeBtn = document.getElementById('save-mode-btn'); -const savePublishBtn = document.getElementById('save-publish-btn'); +const modeName = document.getElementById("mode-name-input"); +const saveModeBtn = document.getElementById("save-mode-btn"); +const savePublishBtn = document.getElementById("save-publish-btn"); - -saveModeBtn.addEventListener('click', e => { +saveModeBtn.addEventListener("click", e => { const modeNameValue = modeName.value; if (!modeNameValue) { - const requireText = document.getElementById('require-text'); + const requireText = document.getElementById("require-text"); requireText.innerText = "Please enter a creative game mode name"; } else { - axios.post('/modes', { - mode_name: modeNameValue, - settings: customRules - }).then(() => { - window.location.href = "/modes/user"; - }); + axios + .post("/modes", { + mode_name: modeNameValue, + settings: customRules + }) + .then(() => { + window.location.href = "/modes/user"; + }); } }); -savePublishBtn.addEventListener('click', e => { +savePublishBtn.addEventListener("click", e => { const modeNameValue = modeName.value; if (!modeNameValue) { - const requireText = document.getElementById('require-text'); + const requireText = document.getElementById("require-text"); requireText.innerText = "Please enter a creative game mode name"; } else { - axios.post('/modes', { - mode_name: modeNameValue, - settings: customRules - }) - .then(results => { - const mode_id = results.data; - axios.post(`/modes/publish/${mode_id}`) - .then(() => { - window.location.href = "/modes/user/created"; - }) ; - }); + axios + .post("/modes", { + mode_name: modeNameValue, + settings: customRules + }) + .then(results => { + const mode_id = results.data; + axios.post(`/modes/publish/${mode_id}`).then(() => { + window.location.href = "/modes/user/created"; + }); + }); } }); diff --git a/resources/js/header.js b/resources/js/header.js index ec6cc14..a0d0b72 100644 --- a/resources/js/header.js +++ b/resources/js/header.js @@ -5,23 +5,22 @@ window.onscroll = function() { const username = document.getElementById("username"); const accounticon = document.getElementById("account-icon"); - // Add the sticky class to the navbar on scroll. Remove "sticky" when you leave the scroll position - if (window.pageYOffset > 50) { - navbar.classList.add("sticky"); - draftstone.classList.remove("draftstone-text"); - draftstone.classList.add("draftstone-text-sticky"); - username.classList.remove("darker"); - username.classList.add("light"); - accounticon.classList.remove("dark"); - accounticon.classList.add("brown"); - } else { - navbar.classList.remove("sticky"); - draftstone.classList.remove("draftstone-text-sticky"); - draftstone.classList.add("draftstone-text"); - username.classList.remove("light"); - username.classList.add("darker"); - accounticon.classList.remove("brown"); - accounticon.classList.add("dark"); - } + if (window.pageYOffset > 50) { + navbar.classList.add("sticky"); + draftstone.classList.remove("draftstone-text"); + draftstone.classList.add("draftstone-text-sticky"); + username.classList.remove("darker"); + username.classList.add("light"); + accounticon.classList.remove("dark"); + accounticon.classList.add("brown"); + } else { + navbar.classList.remove("sticky"); + draftstone.classList.remove("draftstone-text-sticky"); + draftstone.classList.add("draftstone-text"); + username.classList.remove("light"); + username.classList.add("darker"); + accounticon.classList.remove("brown"); + accounticon.classList.add("dark"); + } }; diff --git a/resources/js/login.js b/resources/js/login.js index f091e4f..42f1109 100644 --- a/resources/js/login.js +++ b/resources/js/login.js @@ -1,25 +1,23 @@ - -const registerForm = document.getElementById('register'); -const password = document.getElementById('register-password'); -const confirm = document.getElementById('register-confirm'); +const registerForm = document.getElementById("register"); +const password = document.getElementById("register-password"); +const confirm = document.getElementById("register-confirm"); const mismatch = document.getElementById("mismatch"); - -registerForm.addEventListener('submit', (e) => { +registerForm.addEventListener("submit", e => { if (password.value !== confirm.value) { e.preventDefault(); - password.value = ''; - confirm.value = ''; - if(mismatch.classList.contains('hidden')) { - mismatch.classList.remove('hidden'); + password.value = ""; + confirm.value = ""; + if (mismatch.classList.contains("hidden")) { + mismatch.classList.remove("hidden"); } - mismatch.classList.remove('hidden'); + mismatch.classList.remove("hidden"); return false; } else { - if(!mismatch.classList.contains('hidden')) { - mismatch.classList.add('hidden'); + if (!mismatch.classList.contains("hidden")) { + mismatch.classList.add("hidden"); } return true; } -}); \ No newline at end of file +}); diff --git a/resources/js/modes.js b/resources/js/modes.js index 938c51f..710b5e0 100644 --- a/resources/js/modes.js +++ b/resources/js/modes.js @@ -2,48 +2,53 @@ localStorage.clear(); const masterPool = []; // All collectible cards const heroes = []; // The nine original heroes to represent classes -document.addEventListener('DOMContentLoaded', () => { - axios.get('https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1', { - headers: { - 'X-Mashape-Key': 'gAeuReVzM3mshLLX97GlEfieDYDep1H5yDOjsn5z5VlqqZie5Q' - } - }).then(response => { - - // First nine cards of data are the heroes. Add them to heroes array - for (let i = 0; i < 9; i++) { - heroes.push(response.data.Basic[i]); - } - - // Iterate through all cards in data and push non-Hero cards to the master pool - for (const set in response.data) { - for (const card of response.data[set]) { - if (card.type !== "Hero") { - masterPool.push(card); - } - } - } - - // Save both arrays to local storage in order to be accessed by draft page - // eventually this will be placed in the server and the API call won't be necessary at all - localStorage.setItem("masterPool", JSON.stringify(masterPool)); - localStorage.setItem("heroes", JSON.stringify(heroes)); - - +document.addEventListener("DOMContentLoaded", () => { + axios + .get("https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1", { + headers: { + "X-Mashape-Key": "gAeuReVzM3mshLLX97GlEfieDYDep1H5yDOjsn5z5VlqqZie5Q" + } + }) + .then(response => { + // First nine cards of data are the heroes. Add them to heroes array + for (let i = 0; i < 9; i++) { + heroes.push(response.data.Basic[i]); + } + // Iterate through all cards in data and push non-Hero cards to the master pool + for (const set in response.data) { + for (const card of response.data[set]) { + if (card.type !== "Hero") { + masterPool.push(card); + } + } + } - const modeList = document.getElementById('mode-list'); - modeList.addEventListener('click', e => { - if (e.target.id.substring(0,4) === "mode" || e.target.parentNode.id.substring(0,4) === "mode") { - const modeSettings = JSON.parse(document.getElementById(`${e.target.id || e.target.parentNode.id}-input`).value); - localStorage.setItem('customRules', JSON.stringify(modeSettings)); - window.open("/draft", "_self"); + // Save both arrays to local storage in order to be accessed by draft page + // eventually this will be placed in the server and the API call won't be necessary at all + localStorage.setItem("masterPool", JSON.stringify(masterPool)); + localStorage.setItem("heroes", JSON.stringify(heroes)); + + const modeList = document.getElementById("mode-list"); + modeList.addEventListener("click", e => { + if ( + e.target.id.substring(0, 4) === "mode" || + e.target.parentNode.id.substring(0, 4) === "mode" + ) { + const modeSettings = JSON.parse( + document.getElementById( + `${e.target.id || e.target.parentNode.id}-input` + ).value + ); + localStorage.setItem("customRules", JSON.stringify(modeSettings)); + window.open("/draft", "_self"); + } + }); + + const startBtns = document.querySelectorAll(".start-btn"); + for (const btn of startBtns) { + btn.disabled = false; + btn.classList.remove("inactive"); } }); - - const startBtns = document.querySelectorAll('.start-btn'); - for (const btn of startBtns) { - btn.disabled = false; - btn.classList.remove('inactive'); - } - }); }); diff --git a/resources/js/passwordChange.js b/resources/js/passwordChange.js index 8c25117..fb6f72f 100644 --- a/resources/js/passwordChange.js +++ b/resources/js/passwordChange.js @@ -1,32 +1,30 @@ +const passwordForm = document.getElementById("password-change"); +const newPassword = document.getElementById("newpassword"); +const newConfirm = document.getElementById("confirmpassword"); -const passwordForm = document.getElementById('password-change'); -const newPassword = document.getElementById('newpassword'); -const newConfirm = document.getElementById('confirmpassword'); +const error = document.getElementById("error"); +const success = document.getElementById("success"); -const error = document.getElementById('error'); -const success = document.getElementById('success'); - - -passwordForm.addEventListener('submit', (e) => { +passwordForm.addEventListener("submit", e => { if (error) { - error.classList.add('hidden'); + error.classList.add("hidden"); } if (success) { - success.classList.add('hidden'); + success.classList.add("hidden"); } if (newPassword.value !== newConfirm.value) { e.preventDefault(); - newPassword.value = ''; - newConfirm.value = ''; - if(mismatch.classList.contains('hidden')) { - mismatch.classList.remove('hidden'); + newPassword.value = ""; + newConfirm.value = ""; + if (mismatch.classList.contains("hidden")) { + mismatch.classList.remove("hidden"); } - mismatch.classList.remove('hidden'); + mismatch.classList.remove("hidden"); return false; } else { - if(!mismatch.classList.contains('hidden')) { - mismatch.classList.add('hidden'); + if (!mismatch.classList.contains("hidden")) { + mismatch.classList.add("hidden"); } return true; } diff --git a/resources/js/popover.js b/resources/js/popover.js index e93d201..8236417 100644 --- a/resources/js/popover.js +++ b/resources/js/popover.js @@ -1,7 +1,7 @@ -$(function () { - $('[data-toggle="popover"]').popover() -}) +$(function() { + $('[data-toggle="popover"]').popover(); +}); -$(function () { - $('[data-toggle="tooltip"]').tooltip() -}) +$(function() { + $('[data-toggle="tooltip"]').tooltip(); +}); diff --git a/resources/js/setup.js b/resources/js/setup.js index c6f1f91..dc4a092 100644 --- a/resources/js/setup.js +++ b/resources/js/setup.js @@ -3,118 +3,119 @@ const masterPool = []; // All collectible cards const heroes = []; // The nine original heroes to represent classes let customRules = {}; -console.log('setup.js') -document.addEventListener('DOMContentLoaded', () => { - console.log('DCL') - axios.get('https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1', { - headers: { - 'X-Mashape-Key': 'gAeuReVzM3mshLLX97GlEfieDYDep1H5yDOjsn5z5VlqqZie5Q' - } - }).then(response => { - - // First nine cards of data are the heroes. Add them to heroes array - for (let i = 0; i < 9; i++) { - heroes.push(response.data.Basic[i]); - } - - // Iterate through all cards in data and push non-Hero cards to the master pool - for (const set in response.data) { - for (const card of response.data[set]) { - if (card.type === "Hero" && card.cardSet !== "Basic" && card.cardSet !== "Hero Skins") { - card.type = "Spell" - } - if (card.type !== "Hero") { - masterPool.push(card); - } - } - } - - // Save both arrays to local storage in order to be accessed by draft page - // eventually this will be placed in the server and the API call won't be necessary at all - localStorage.setItem("masterPool", JSON.stringify(masterPool)); - localStorage.setItem("heroes", JSON.stringify(heroes)); - - // The "Start Draft" button is faded (low opacity) at first, but becomes fully "active" once the data from the API is processed - // this too will probably become unnecessary once we have our own server - const draftBtn = document.getElementById('draft-btn'); - draftBtn.classList.remove("inactive"); - const saveBtn = document.getElementById('save-btn'); - saveBtn.classList.remove("inactive"); - saveBtn.disabled = false; - - // Once the user is ready to draft (either they have chosen settings or foregone doing so), they will click this button - // The button triggers storing of all their settings to localStorage in order to be retrieved during the draft - draftBtn.addEventListener('click', e => { - buildSettings(); - window.location.href = "/draft"; - }); - - saveBtn.addEventListener('click', e => { - buildSettings(); - }); - - - - }); -}); +console.log("setup.js"); +document.addEventListener("DOMContentLoaded", () => { + console.log("DCL"); + axios + .get("https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1", { + headers: { + "X-Mashape-Key": "gAeuReVzM3mshLLX97GlEfieDYDep1H5yDOjsn5z5VlqqZie5Q" + } + }) + .then(response => { + // First nine cards of data are the heroes. Add them to heroes array + for (let i = 0; i < 9; i++) { + heroes.push(response.data.Basic[i]); + } + + // Iterate through all cards in data and push non-Hero cards to the master pool + for (const set in response.data) { + for (const card of response.data[set]) { + if ( + card.type === "Hero" && + card.cardSet !== "Basic" && + card.cardSet !== "Hero Skins" + ) { + card.type = "Spell"; + } + if (card.type !== "Hero") { + masterPool.push(card); + } + } + } -const modeName = document.getElementById('mode-name-input'); -const saveModeBtn = document.getElementById('save-mode-btn'); -const savePublishBtn = document.getElementById('save-publish-btn'); + // Save both arrays to local storage in order to be accessed by draft page + // eventually this will be placed in the server and the API call won't be necessary at all + localStorage.setItem("masterPool", JSON.stringify(masterPool)); + localStorage.setItem("heroes", JSON.stringify(heroes)); + + // The "Start Draft" button is faded (low opacity) at first, but becomes fully "active" once the data from the API is processed + // this too will probably become unnecessary once we have our own server + const draftBtn = document.getElementById("draft-btn"); + draftBtn.classList.remove("inactive"); + const saveBtn = document.getElementById("save-btn"); + saveBtn.classList.remove("inactive"); + saveBtn.disabled = false; + + // Once the user is ready to draft (either they have chosen settings or foregone doing so), they will click this button + // The button triggers storing of all their settings to localStorage in order to be retrieved during the draft + draftBtn.addEventListener("click", e => { + buildSettings(); + window.location.href = "/draft"; + }); + + saveBtn.addEventListener("click", e => { + buildSettings(); + }); + }); +}); +const modeName = document.getElementById("mode-name-input"); +const saveModeBtn = document.getElementById("save-mode-btn"); +const savePublishBtn = document.getElementById("save-publish-btn"); -saveModeBtn.addEventListener('click', e => { +saveModeBtn.addEventListener("click", e => { const modeNameValue = modeName.value; if (!modeNameValue) { - const requireText = document.getElementById('require-text'); + const requireText = document.getElementById("require-text"); requireText.innerText = "Please enter a creative game mode name"; } else { - axios.post('/modes', { - mode_name: modeNameValue, - settings: customRules - }).then(({data}) => { - if (data.dupe) { - window.location.href = `/modes/single/${data.id}`; - } else { - window.location.href = "/modes/user/created"; - } - }); + axios + .post("/modes", { + mode_name: modeNameValue, + settings: customRules + }) + .then(({ data }) => { + if (data.dupe) { + window.location.href = `/modes/single/${data.id}`; + } else { + window.location.href = "/modes/user/created"; + } + }); } }); -savePublishBtn.addEventListener('click', e => { +savePublishBtn.addEventListener("click", e => { const modeNameValue = modeName.value; if (!modeNameValue) { - const requireText = document.getElementById('require-text'); + const requireText = document.getElementById("require-text"); requireText.innerText = "Please enter a creative game mode name"; } else { - axios.post('/modes', { - mode_name: modeNameValue, - settings: customRules - }) - .then(results => { - if (results.data.dupe) { - window.location.href = `/modes/single/${results.data.id}`; - } else { - const mode_id = results.data; - axios.post(`/modes/publish/${mode_id}`) - .then(() => { - window.location.href = "/modes/user/created"; - }) ; - } - }); + axios + .post("/modes", { + mode_name: modeNameValue, + settings: customRules + }) + .then(results => { + if (results.data.dupe) { + window.location.href = `/modes/single/${results.data.id}`; + } else { + const mode_id = results.data; + axios.post(`/modes/publish/${mode_id}`).then(() => { + window.location.href = "/modes/user/created"; + }); + } + }); } }); - - function buildSettings() { - // Retrieve and store heroes chosen by user - const heroFilterSetting = document.querySelector('input[name="hero"]:checked').value; + const heroFilterSetting = document.querySelector('input[name="hero"]:checked') + .value; const heroArray = []; if (heroFilterSetting === "custom") { - let heroOptions = document.getElementById('select-hero').options; + let heroOptions = document.getElementById("select-hero").options; for (const hero of heroOptions) { if (hero.selected) { heroArray.push(hero.value); @@ -123,22 +124,24 @@ function buildSettings() { } // Retrieve and store sets chosen by user - const setFilterSetting = document.querySelector('input[name="set"]:checked').value; + const setFilterSetting = document.querySelector('input[name="set"]:checked') + .value; const setArray = []; if (setFilterSetting === "custom") { - let setOptions = document.getElementById('select-set').options; + let setOptions = document.getElementById("select-set").options; for (const set of setOptions) { - if(set.selected) { + if (set.selected) { setArray.push(set.value); } } } // Retrieve and store sets chosen by user - const costFilterSetting = document.querySelector('input[name="cost"]:checked').value; + const costFilterSetting = document.querySelector('input[name="cost"]:checked') + .value; const costArray = []; if (costFilterSetting === "custom") { - let costOptions = document.getElementById('select-cost').options; + let costOptions = document.getElementById("select-cost").options; for (const cost of costOptions) { if (cost.selected) { costArray.push(cost.value); @@ -146,62 +149,75 @@ function buildSettings() { } } - - const classSetting = document.querySelector('input[name="class"]:checked').value; - const raritySetting = document.querySelector('input[name="rarity"]:checked').value; - const typeSetting = document.querySelector('input[name="type"]:checked').value; - - let classCount = classSetting !== "custom" ? NaN : document.getElementById('classInput').value; - - let legendaryCount = raritySetting !== "custom" ? NaN : document.getElementById('legendInput').value; - let epicCount = raritySetting !== "custom" ? NaN : document.getElementById('epicInput').value; - let rareCount = raritySetting !== "custom" ? NaN : document.getElementById('rareInput').value; - - let spellCount = typeSetting !== "custom" ? NaN : document.getElementById('spellInput').value; - - let specifiedClasses = document.getElementById('select-hero').value; - - + const classSetting = document.querySelector('input[name="class"]:checked') + .value; + const raritySetting = document.querySelector('input[name="rarity"]:checked') + .value; + const typeSetting = document.querySelector('input[name="type"]:checked') + .value; + + let classCount = + classSetting !== "custom" + ? NaN + : document.getElementById("classInput").value; + + let legendaryCount = + raritySetting !== "custom" + ? NaN + : document.getElementById("legendInput").value; + let epicCount = + raritySetting !== "custom" + ? NaN + : document.getElementById("epicInput").value; + let rareCount = + raritySetting !== "custom" + ? NaN + : document.getElementById("rareInput").value; + + let spellCount = + typeSetting !== "custom" + ? NaN + : document.getElementById("spellInput").value; + + let specifiedClasses = document.getElementById("select-hero").value; customRules = { - 'heroFilterSetting': heroFilterSetting, - 'heroArray': heroArray, - 'setFilterSetting': setFilterSetting, - 'setArray': setArray, - 'costFilterSetting': costFilterSetting, - 'costArray': costArray, - 'classSetting': classSetting, - 'classCount': classCount, - 'raritySetting': raritySetting, - 'legendaryCount': legendaryCount, - 'epicCount': epicCount, - 'rareCount': rareCount, - 'typeSetting': typeSetting, - 'spellCount': spellCount + heroFilterSetting: heroFilterSetting, + heroArray: heroArray, + setFilterSetting: setFilterSetting, + setArray: setArray, + costFilterSetting: costFilterSetting, + costArray: costArray, + classSetting: classSetting, + classCount: classCount, + raritySetting: raritySetting, + legendaryCount: legendaryCount, + epicCount: epicCount, + rareCount: rareCount, + typeSetting: typeSetting, + spellCount: spellCount }; - localStorage.setItem("customRules", JSON.stringify(customRules)); - - - - } //Multi-Select Click Function -window.onmousedown = function (e) { - var el = e.target; - if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) { - e.preventDefault(); - - // toggle selection - if (el.hasAttribute('selected')) el.removeAttribute('selected'); - else el.setAttribute('selected', ''); - - // hack to correct buggy behavior - var select = el.parentNode.cloneNode(true); - el.parentNode.parentNode.replaceChild(select, el.parentNode); - } +window.onmousedown = function(e) { + var el = e.target; + if ( + el.tagName.toLowerCase() == "option" && + el.parentNode.hasAttribute("multiple") + ) { + e.preventDefault(); + + // toggle selection + if (el.hasAttribute("selected")) el.removeAttribute("selected"); + else el.setAttribute("selected", ""); + + // hack to correct buggy behavior + var select = el.parentNode.cloneNode(true); + el.parentNode.parentNode.replaceChild(select, el.parentNode); + } }; // Enable/Disable Hero Checkbox/Multiselect @@ -209,12 +225,11 @@ let selectHero = document.getElementById("select-hero"); const heroAllInput = document.getElementById("hero-all-input"); const heroCustomInput = document.getElementById("hero-custom-input"); - -heroCustomInput.addEventListener('change', () => { +heroCustomInput.addEventListener("change", () => { selectHero = document.getElementById("select-hero"); - if (heroCustomInput.checked === true){ - selectHero.classList.toggle('faded'); - selectHero.childNodes.forEach((node)=>{ + if (heroCustomInput.checked === true) { + selectHero.classList.toggle("faded"); + selectHero.childNodes.forEach(node => { node.disabled = false; }); } else { @@ -222,11 +237,11 @@ heroCustomInput.addEventListener('change', () => { } }); -heroAllInput.addEventListener('change', () => { +heroAllInput.addEventListener("change", () => { selectHero = document.getElementById("select-hero"); - if (heroAllInput.checked === true){ - selectHero.classList.toggle('faded'); - selectHero.childNodes.forEach((node)=>{ + if (heroAllInput.checked === true) { + selectHero.classList.toggle("faded"); + selectHero.childNodes.forEach(node => { node.disabled = true; node.selected = false; }); @@ -238,12 +253,11 @@ let selectSet = document.getElementById("select-set"); const setAllInput = document.getElementById("set-all-input"); const setCustomInput = document.getElementById("set-custom-input"); - -setCustomInput.addEventListener('change', () => { +setCustomInput.addEventListener("change", () => { selectSet = document.getElementById("select-set"); - if (setCustomInput.checked === true){ - selectSet.classList.toggle('faded'); - selectSet.childNodes.forEach((node)=>{ + if (setCustomInput.checked === true) { + selectSet.classList.toggle("faded"); + selectSet.childNodes.forEach(node => { node.disabled = false; }); } else { @@ -251,11 +265,11 @@ setCustomInput.addEventListener('change', () => { } }); -setAllInput.addEventListener('change', () => { +setAllInput.addEventListener("change", () => { selectSet = document.getElementById("select-set"); - if (setAllInput.checked === true){ - selectSet.classList.toggle('faded'); - selectSet.childNodes.forEach((node)=>{ + if (setAllInput.checked === true) { + selectSet.classList.toggle("faded"); + selectSet.childNodes.forEach(node => { node.disabled = true; node.selected = false; }); @@ -267,12 +281,11 @@ let selectCost = document.getElementById("select-cost"); const costAllInput = document.getElementById("cost-all-input"); const costCustomInput = document.getElementById("cost-custom-input"); - -costCustomInput.addEventListener('change', () => { +costCustomInput.addEventListener("change", () => { selectCost = document.getElementById("select-cost"); - if (costCustomInput.checked === true){ - selectCost.classList.toggle('faded'); - selectCost.childNodes.forEach((node)=>{ + if (costCustomInput.checked === true) { + selectCost.classList.toggle("faded"); + selectCost.childNodes.forEach(node => { node.disabled = false; }); } else { @@ -280,36 +293,33 @@ costCustomInput.addEventListener('change', () => { } }); -costAllInput.addEventListener('change', () => { +costAllInput.addEventListener("change", () => { selectCost = document.getElementById("select-cost"); - if (costAllInput.checked === true){ - selectCost.classList.toggle('faded'); - selectCost.childNodes.forEach((node)=>{ + if (costAllInput.checked === true) { + selectCost.classList.toggle("faded"); + selectCost.childNodes.forEach(node => { node.disabled = true; node.selected = false; }); } }); - - // Enable/Disable Class Checkbox/Slider const classFieldSet = document.getElementById("class-fieldset"); const classCustomInput = document.getElementById("class-custom-input"); const classChaosInput = document.getElementById("class-chaos-input"); const classConsistentInput = document.getElementById("class-consistent-input"); - -classCustomInput.addEventListener('change', () => { - if (classCustomInput.checked === true){ +classCustomInput.addEventListener("change", () => { + if (classCustomInput.checked === true) { classFieldSet.disabled = false; } else { classFieldSet.disabled = true; } }); -classChaosInput.addEventListener('change', () => { - if (classChaosInput.checked === true){ +classChaosInput.addEventListener("change", () => { + if (classChaosInput.checked === true) { classFieldSet.disabled = true; classInput.value = 0; neutralInput.value = 0; @@ -318,8 +328,8 @@ classChaosInput.addEventListener('change', () => { } }); -classConsistentInput.addEventListener('change', () => { - if (classConsistentInput.checked === true){ +classConsistentInput.addEventListener("change", () => { + if (classConsistentInput.checked === true) { classFieldSet.disabled = true; classInput.value = 0; neutralInput.value = 0; @@ -328,25 +338,22 @@ classConsistentInput.addEventListener('change', () => { } }); - - // Enable/Disable Type Checkbox/Slider const typeFieldSet = document.getElementById("type-fieldset"); const typeCustomInput = document.getElementById("type-custom-input"); const typeChaosInput = document.getElementById("type-chaos-input"); const typeConsistentInput = document.getElementById("type-consistent-input"); - -typeCustomInput.addEventListener('change', () => { - if (typeCustomInput.checked === true){ +typeCustomInput.addEventListener("change", () => { + if (typeCustomInput.checked === true) { typeFieldSet.disabled = false; } else { typeFieldSet.disabled = true; } }); -typeChaosInput.addEventListener('change', () => { - if (typeChaosInput.checked === true){ +typeChaosInput.addEventListener("change", () => { + if (typeChaosInput.checked === true) { typeFieldSet.disabled = true; minionInput.value = 0; spellInput.value = 0; @@ -355,8 +362,8 @@ typeChaosInput.addEventListener('change', () => { } }); -typeConsistentInput.addEventListener('change', () => { - if (typeConsistentInput.checked === true){ +typeConsistentInput.addEventListener("change", () => { + if (typeConsistentInput.checked === true) { typeFieldSet.disabled = true; minionInput.value = 0; spellInput.value = 0; @@ -365,24 +372,24 @@ typeConsistentInput.addEventListener('change', () => { } }); - - // Enable/Disable Rarity Checkbox/Slider const rarityFieldSet = document.getElementById("rarity-fieldset"); const rarityCustomInput = document.getElementById("rarity-custom-input"); const rarityChaosInput = document.getElementById("rarity-chaos-input"); -const rarityConsistentInput = document.getElementById("rarity-consistent-input"); +const rarityConsistentInput = document.getElementById( + "rarity-consistent-input" +); -rarityCustomInput.addEventListener('change', () => { - if (rarityCustomInput.checked === true){ +rarityCustomInput.addEventListener("change", () => { + if (rarityCustomInput.checked === true) { rarityFieldSet.disabled = false; } else { rarityFieldSet.disabled = true; } }); -rarityChaosInput.addEventListener('change', () => { - if (rarityChaosInput.checked === true){ +rarityChaosInput.addEventListener("change", () => { + if (rarityChaosInput.checked === true) { rarityFieldSet.disabled = true; legendInput.value = 0; epicInput.value = 0; @@ -395,8 +402,8 @@ rarityChaosInput.addEventListener('change', () => { } }); -rarityConsistentInput.addEventListener('change', () => { - if (rarityConsistentInput.checked === true){ +rarityConsistentInput.addEventListener("change", () => { + if (rarityConsistentInput.checked === true) { rarityFieldSet.disabled = true; legendInput.value = 0; epicInput.value = 0; @@ -410,10 +417,10 @@ rarityConsistentInput.addEventListener('change', () => { }); // Make sliders resposive to each other within each filter category -const classInput = document.getElementById('classInput'); -const classOutput = document.getElementById('classOutput'); -const neutralInput = document.getElementById('neutralInput'); -const neutralOutput = document.getElementById('neutralOutput'); +const classInput = document.getElementById("classInput"); +const classOutput = document.getElementById("classOutput"); +const neutralInput = document.getElementById("neutralInput"); +const neutralOutput = document.getElementById("neutralOutput"); classInput.value = 0; neutralInput.value = 0; @@ -441,22 +448,22 @@ function handleNeutralInputRelative() { classOutput.value = classInput.value; } - -const legendInput = document.getElementById('legendInput'); -const legendOutput = document.getElementById('legendOutput'); -const epicInput = document.getElementById('epicInput'); -const epicOutput = document.getElementById('epicOutput'); -const rareInput = document.getElementById('rareInput'); -const rareOutput = document.getElementById('rareOutput'); -const commonInput = document.getElementById('commonInput'); -const commonOutput = document.getElementById('commonOutput'); +const legendInput = document.getElementById("legendInput"); +const legendOutput = document.getElementById("legendOutput"); +const epicInput = document.getElementById("epicInput"); +const epicOutput = document.getElementById("epicOutput"); +const rareInput = document.getElementById("rareInput"); +const rareOutput = document.getElementById("rareOutput"); +const commonInput = document.getElementById("commonInput"); +const commonOutput = document.getElementById("commonOutput"); legendInput.value = 0; epicInput.value = 0; rareInput.value = 0; // commonInput.value = 30; // commonOutput.value = 30; function handleLegendInput() { - const remainingSlots = 30 - (Number(epicInput.value) + Number(rareInput.value)); + const remainingSlots = + 30 - (Number(epicInput.value) + Number(rareInput.value)); if (legendInput.value > remainingSlots) { legendInput.value = remainingSlots; } @@ -466,7 +473,8 @@ function handleLegendInput() { } function handleLegendInputRelative() { - const remainingSlots = 100 - (Number(epicInput.value) + Number(rareInput.value)); + const remainingSlots = + 100 - (Number(epicInput.value) + Number(rareInput.value)); if (legendInput.value > remainingSlots) { legendInput.value = remainingSlots; } @@ -476,7 +484,8 @@ function handleLegendInputRelative() { } function handleEpicInput() { - const remainingSlots = 30 - (Number(legendInput.value) + Number(rareInput.value)); + const remainingSlots = + 30 - (Number(legendInput.value) + Number(rareInput.value)); if (epicInput.value > remainingSlots) { epicInput.value = remainingSlots; } @@ -486,7 +495,8 @@ function handleEpicInput() { } function handleEpicInputRelative() { - const remainingSlots = 100 - (Number(legendInput.value) + Number(rareInput.value)); + const remainingSlots = + 100 - (Number(legendInput.value) + Number(rareInput.value)); if (epicInput.value > remainingSlots) { epicInput.value = remainingSlots; } @@ -496,7 +506,8 @@ function handleEpicInputRelative() { } function handleRareInput() { - const remainingSlots = 30 - (Number(legendInput.value) + Number(epicInput.value)); + const remainingSlots = + 30 - (Number(legendInput.value) + Number(epicInput.value)); if (rareInput.value > remainingSlots) { rareInput.value = remainingSlots; } @@ -506,7 +517,8 @@ function handleRareInput() { } function handleRareInputRelative() { - const remainingSlots = 100 - (Number(legendInput.value) + Number(epicInput.value)); + const remainingSlots = + 100 - (Number(legendInput.value) + Number(epicInput.value)); if (rareInput.value > remainingSlots) { rareInput.value = remainingSlots; } @@ -518,7 +530,11 @@ function handleRareInputRelative() { function handleCommonInput() { commonInput.value = 30; commonOutput.value = 30; - const remainingSlots = 30 - (Number(legendInput.value) + Number(epicInput.value) + Number(rareInput.value)); + const remainingSlots = + 30 - + (Number(legendInput.value) + + Number(epicInput.value) + + Number(rareInput.value)); commonInput.value = remainingSlots; commonOutput.value = commonInput.value; } @@ -526,16 +542,19 @@ function handleCommonInput() { function handleCommonInputRelative() { commonInput.value = 100; commonOutput.value = 100; - const remainingSlots = 100 - (Number(legendInput.value) + Number(epicInput.value) + Number(rareInput.value)); + const remainingSlots = + 100 - + (Number(legendInput.value) + + Number(epicInput.value) + + Number(rareInput.value)); commonInput.value = remainingSlots; commonOutput.value = commonInput.value; } - -const minionInput = document.getElementById('minionInput'); -const minionOutput = document.getElementById('minionOutput'); -const spellInput = document.getElementById('spellInput'); -const spellOutput = document.getElementById('spellOutput'); +const minionInput = document.getElementById("minionInput"); +const minionOutput = document.getElementById("minionOutput"); +const spellInput = document.getElementById("spellInput"); +const spellOutput = document.getElementById("spellOutput"); minionInput.value = 0; spellInput.value = 0; @@ -565,9 +584,9 @@ function handleSpellInputRelative() { //Routes for absolute/relative modes -const relative = document.getElementById('relative-input'); -const absolute = document.getElementById('absolute-input'); +const relative = document.getElementById("relative-input"); +const absolute = document.getElementById("absolute-input"); -relative.addEventListener('onClick', () => { - axios.get('/setup/relative').then(res => res.json()) -}) +relative.addEventListener("onClick", () => { + axios.get("/setup/relative").then(res => res.json()); +}); diff --git a/server.js b/server.js index 62d5ce3..0de984d 100644 --- a/server.js +++ b/server.js @@ -1,21 +1,21 @@ const express = require("express"); const path = require("path"); const app = express(); -const bodyParser = require('body-parser'); -const nodemailer = require('nodemailer'); -const xoauth2 = require('xoauth2'); +const bodyParser = require("body-parser"); +const nodemailer = require("nodemailer"); +const xoauth2 = require("xoauth2"); const port = process.env.PORT || 8000; app.use(bodyParser.json({ extended: true })); app.use(bodyParser.urlencoded({ extended: true })); -app.use(express.static('resources')); +app.use(express.static("resources")); -require('./config/sessions')(app); +require("./config/sessions")(app); -app.set('view engine', 'ejs'); +app.set("view engine", "ejs"); -var routes_setter = require('./config/routes.js'); +var routes_setter = require("./config/routes.js"); routes_setter(app); app.listen(port, function() { - console.log('Listening on', port); + console.log("Listening on", port); }); diff --git a/views/account.ejs b/views/account.ejs index 5fe8d31..ba6d712 100644 --- a/views/account.ejs +++ b/views/account.ejs @@ -1,135 +1,255 @@ - - - - - DraftStone - - - - - - - - - - - - -<%- include partials/header.ejs %> - - - -
+ + + + + DraftStone + + + + + + + + + + + + <%- include partials/header.ejs %> + + + +
-
-
-
+
-
-

Account Details

-
+

+ Account Details +

+

Username:

-

<%= users[0].user_name %>

+

+ <%= users[0].user_name %> +

Email:

<%= users[0].email %>

-
-

For questions, comments, or to report errors/issues, please contact us at draftstonebeta@gmail.com

+
+

+ For questions, comments, or to report errors/issues, please + contact us at draftstonebeta@gmail.com +

-

Change Password

-
+

+ Change Password +

+
- - - - + + + +
- + <% for (const err of messages.resetError) { %> -

<%= err %>

- <% } %> - <% for (const suc of messages.resetSuccess) { %> -

<%= suc %>

- <% } %> -
+

<%= err %>

+ <% } %> <% for (const suc of messages.resetSuccess) { %> +

<%= suc %>

+ <% } %>
- +
-

click button to delete your user account

+

+ click button to delete your user account +

-
- -
-
-
+
- <%- include partials/modals.ejs %> - - - - + --> + @@ -261,12 +285,18 @@ <%- include partials/modals.ejs %> - - - - - - - - + + + + + + + diff --git a/views/export.ejs b/views/export.ejs index 0277f98..95c8ab5 100644 --- a/views/export.ejs +++ b/views/export.ejs @@ -1,92 +1,156 @@ - - - - - DraftStone - - - - - - - - - - - - - - - - - -<%- include partials/header.ejs %> - - - -
-
- - - -
- - - -
-
-
- - - -
-
-
-

You're done, go have some fun!

-
-
-

-
-
-            
-
-
-            
-          
-
- -

Click to access your custom deckstring for easy import into Hearthstone!

-
-
- -
-

Click to save your game mode to your account or the community

-

(Log in to save/publish game modes)

- + + + + + DraftStone + + + + + + + + + + + + + + + + + <%- include partials/header.ejs %> + + + +
+
+ + + +
+ + +
+
+ + + +
+
+
+

You're done, go have some fun!

+
+
+

+
+              
+
+              
+            
+
+ +

+ Click to access your custom deckstring for easy import into + Hearthstone! +

+
+
+ +
+

+ Click to save your game mode to your account or the community +

+

(Log in to save/publish game modes)

+
-
-
+
-
-
- - <%- include partials/modals.ejs %> - - - - - - - +
+ + <%- include partials/modals.ejs %> + + + + + + + diff --git a/views/index.ejs b/views/index.ejs index 35f4cbb..3155f1a 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -1,51 +1,72 @@ - - - - - DraftStone - - - - - - - - + - + gtag("config", "UA-127642798-1"); + + - + + <%- include partials/header.ejs %> -<%- include partials/header.ejs %> + - - -
+
-
-
-
+
-

Draft custom Hearthstone decks
to play against friends!

-
+

+ Draft custom Hearthstone decks
to play against friends! +

+

Step 1: Setup Draft

(Setup your own custom draft parameters)

Step 2: Select Draft

@@ -56,7 +77,9 @@ -
-
+
- <%- include partials/modals.ejs %> + <%- include partials/modals.ejs %> - - - - - - - + + + + + + + diff --git a/views/partials/header.ejs b/views/partials/header.ejs index 449c36d..4712dab 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -5,37 +5,84 @@