Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finished ponz Project #8

Open
wants to merge 32 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
086bf45
setting up project
bsoung Aug 16, 2017
3c07cbc
making hbs stuff
Alex-Willenbrink Aug 16, 2017
0e88214
creating and registering users
bsoung Aug 16, 2017
cdeaa8c
added a ponz user to database
Alex-Willenbrink Aug 16, 2017
ff34fb6
doing local passport
bsoung Aug 16, 2017
c74c3ae
messing with routes
Alex-Willenbrink Aug 16, 2017
58ba241
local auth working
bsoung Aug 16, 2017
3f996e7
can add referrals somewhat, no only parents
Alex-Willenbrink Aug 16, 2017
931eb60
updating one field
bsoung Aug 16, 2017
697a048
population issues with parents
Alex-Willenbrink Aug 16, 2017
77b0607
got basic referrals
bsoung Aug 16, 2017
b8ceb3e
child population for ponzvert page working
Alex-Willenbrink Aug 16, 2017
107f2dd
finished displaying children
bsoung Aug 16, 2017
a678dfd
revamped cover page for a nice UI, added D3 presentation of the data,…
bsoung Aug 17, 2017
889e693
added css to input text
bsoung Aug 17, 2017
3b917c5
fixed input position
bsoung Aug 17, 2017
1569d68
updatd scripts
bsoung Aug 17, 2017
23a236d
working on styling
Alex-Willenbrink Aug 17, 2017
f9bbc37
changing node colors
bsoung Aug 17, 2017
c5a3b24
trying color layers
Alex-Willenbrink Aug 17, 2017
1abc47c
finished some styling
bsoung Aug 17, 2017
caa18e3
trying to get flash messages up
Alex-Willenbrink Aug 17, 2017
1a0043f
added clear to referral and rainbow text
bsoung Aug 17, 2017
db2e543
pyramid stuff work
Alex-Willenbrink Aug 17, 2017
00c0385
got d3 overflow working
bsoung Aug 17, 2017
d6bd769
sockets are up and running
Alex-Willenbrink Aug 17, 2017
f24494b
more socket stuff
bsoung Aug 17, 2017
74c97ed
lol fixed svg
bsoung Aug 18, 2017
a8a81ad
fixed nested comments
bsoung Aug 18, 2017
9350c5b
fixed d3 labels, added nested labels
bsoung Aug 18, 2017
0a180b1
fixed alerts
bsoung Aug 18, 2017
e761b00
socket working properly
bsoung Aug 18, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/node_modules/
.env
58 changes: 58 additions & 0 deletions auth/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const { User } = require('../models');
const io = require('../io').getIO();

module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});

passport.use(
'local-login',
new LocalStrategy(
{
// local strategy uses username and password
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// callback password from our form
// find a user whose username is the same as the forms username
// we are checking to see if the user trying to login already exists
User.findOne({ username: username }, function(err, user) {
// if there are any errors, return the error before anything else
if (err) return done(err);
// if no user is found, return the message
if (!user) {
io.on('connection', client => {
client.emit('invalid_login');
});

return done(null, false);
} // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong

if (!bcrypt.compareSync(password, user.password)) {
io.on('connection', client => {
client.emit('invalid_login');
});

return done(null, false);
}

// create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}
)
);
};
177 changes: 177 additions & 0 deletions controllers/UserController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
const { User } = require('../models');
const shortid = require('shortid');
const moment = require('moment');
const io = require('../io').getIO();
// const client = require('../io').getClient();

module.exports = {
index: async (req, res) => {
try {
const users = await User.findAll({ order: ['id'] });

return res.json({
confirmation: 'success',
result: users
});
} catch (e) {
return res.json({
confirmation: 'fail',
message: e.message
});
}
},

view: async (req, res) => {
const id = req.params.id;

try {
const user = await User.findById(id);

return res.json({
confirmation: 'success',
result: user
});
} catch (e) {
return res.json({
confirmation: 'fail',
message: e.message
});
}
},

viewPonzvert: async (req, res) => {
let id = req.user._id;

// do a map user on the first user's parent
// { user: 'Bob, parent: susan } { user:susna } //
try {
const user = await User.findById(id).populate('children').populate('parent');

const mapUser = user => {
return {
name: user.username,
parent: user.parent ? user.parent.username : 'null',
children: user.children.map(mapUser)
};
};

return res.render('ponzvert/index', { user, tree: [mapUser(user)] });
} catch (e) {
return res.json({
confirmation: 'fail',
message: e.message
});
}
},

createUser: async (req, res, next) => {
// check if user exists
let existingUser;
try {
existingUser = await User.findOne({
username: req.body.username
});

if (existingUser) {
io.on('connection', client => {
client.emit('user_exists');
});

return res.redirect('/');
}
} catch (e) {
return res.json({
confirmation: 'fail',
message: e.message
});
}

// create our user with random id
try {
// registering for another user
if (req.session.shortid) {
createChildUser(req, res);
return;
}

let id = shortid.generate();
req.body.shortid = id;

let user = await User.create(req.body);

io.on('connection', client => {
client.emit('user_registered');
});

return res.redirect('/ponzvert');
} catch (e) {
console.error(e.stack);
return res.json({
confirmation: 'fail',
message: e.message
});
}
}
};

async function createChildUser(req, res) {
let parentUser;
try {
parentUser = await User.findOne({ shortid: req.session.shortid });
const id = shortid.generate();
req.body.shortid = id;
req.body.parent = parentUser._id;

const childUser = await User.create(req.body);

parentUser = await User.findByIdAndUpdate(
parentUser._id,
{ $push: { children: childUser._id } },
{ new: true, upsert: true }
);

updatePoints(parentUser, 40);

io.on('connection', client => {
client.emit('user_registered');
});

return res.redirect('/ponzvert');
} catch (e) {
return res.json({
confirmation: 'fail',
message: e.message
});
}
}

async function updatePoints(parentUser, points) {
let newParentUser;
try {
if (!parentUser) return;
await User.findByIdAndUpdate(parentUser._id, { $inc: { points: points } });
newParentUser = await User.findById(parentUser.parent);

if (points > 1) {
points /= 2;
points = Math.floor(points);
}

console.log(points, 'what is points?');
} catch (err) {
console.error(err);
}
return updatePoints(newParentUser, points);
}

// User.findOne({ _id: req.params.id }, function(err, node) {
// populateParents(node).then(function() {
// // Do something with user
// });
// });

// function populateParents(user) {
// return User.populate(user, { parent: "parent" }).then(function(user) {
// return user.parent ? populateParents(user.parent) : Promise.fulfill(user);
// });
// }
3 changes: 3 additions & 0 deletions controllers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
users: require("./UserController")
};
102 changes: 102 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const app = require("./io").getApp();
const server = require("./io").getServer();
const express = require("express");
// const express = require("express");
// const app = express();

const path = require("path");
const logger = require("morgan");
const bodyParser = require("body-parser");
const exphbs = require("express-handlebars");
const session = require("express-session");
const passport = require("passport");
// const server = require("http").createServer(app);

// const io = require("./io")(server);

app.use(
"/socket.io",
express.static(__dirname + "node_modules/socket.io-client/dist/")
);

app.use(
session({
secret: "123fljwejflkkwjelk23jlkf23fl2k3jl23kfjlk23j329f4",
resave: true,
saveUninitialized: true
})
);

app.use(passport.initialize());
app.use(passport.session());

const mongoose = require("mongoose");
const Promise = require("bluebird");

const localAuth = require("./auth/passport")(passport);

if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}

// bluebird mongoose
mongoose.Promise = Promise;

// connect to mongoose
const beginConnection = mongoose.connect(process.env.DB_URL, {
useMongoClient: true
});

beginConnection
.then(db => {
console.log("DB CONNECTION SUCCESS");
})
.catch(err => {
console.error(err);
});

// express session

// handlebars view
app.set("views", path.join(__dirname, "views"));

// hbs
app.engine(
"handlebars",
exphbs({
defaultLayout: "main",
helpers: {
toJSON: function(object) {
return JSON.stringify(object);
}
}
})
);

app.set("view engine", "handlebars");

// middleware
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));

// routes
app.use("/api", require("./routes/api"));
app.use("/ponzvert", require("./routes/ponzvert"));
app.use("/", require("./routes/index"));
app.use("/logout", require("./routes/logout"));

app.post(
"/login",
passport.authenticate("local-login", {
successRedirect: "/ponzvert",
failureRedirect: "/",
failureFlash: true
})
);

// listen to server
server.listen(3000, () => {
console.log(`Listening at port 3000`);
});
25 changes: 25 additions & 0 deletions io.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const socket = require('socket.io');
const app = require('express')();
const server = require('http').createServer(app);
let io = socket.listen(server);

function waitForConnection() {
let c = io.on('connection', client => {
return client;
});

return c;
}

const c = waitForConnection();

// client.emit('hello');

// constructor function - should only be called once and passed the http server
module.exports.getServer = () => server;

module.exports.getApp = () => app;

module.exports.getIO = () => io;

module.exports.getClient = () => c;
3 changes: 3 additions & 0 deletions middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
isLoggedIn: require("./login")
}
7 changes: 7 additions & 0 deletions middleware/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = function(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) return next();

// if they aren't redirect them to the home page
res.redirect("/");
};
3 changes: 3 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
User: require("./user")
}
Loading