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

Maddie R completed assignment #19

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,11 @@
# Ponz.io
Building Ponz.io, with its endearingly upside-down-triangle-shaped business model.

## Maddie Rajavasireddy

### Assignment Description:
Once a user signs up with Ponz.io—a name derived from our original coupons idea—they will be presented with their referral link. Their friends can follow this link to a custom signup form. Once a friend signs up, the original user will be awarded 40 Ponz points. When their friend, in turn, signs up another Ponvert, the original user will receive 20 Ponz points. This pattern will continue down the pyram—err, down the chain of opportunity forever, with the amount of rewarded Ponz points decreasing in the following pattern:
Ponzversion Distance --> Ponz points (1 --> 40, 2 --> 20, 3 --> 10, 4 --> 5, 5 --> 2, 6+ --> 1)

#### Packages used:
Express, Mongoose, Moment, Passport
122 changes: 122 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const app = require("express")();
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const expressSession = require("express-session");
const flash = require("express-flash");
const moment = require("moment");

// User and Mongoose code
const mongoose = require("mongoose");
var models = require("./models");
var User = mongoose.model("User");
const cleanDb = require("./seeds/clean")

// Connect to our mongo server
app.use((req, res, next) => {
if (mongoose.connection.readyState) {
next();
} else {
require("./mongo")().then(() => {
// cleanDb().then(() => {
next()
// });
});
}
});

// cookie and parser
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());
app.use(
expressSession({
secret: process.env.secret || "keyboard cat",
saveUninitialized: false,
resave: false
})
);


// require Passport and the Local Strategy
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());

// Local Strategy Set Up
const LocalStrategy = require("passport-local").Strategy;

passport.use(
new LocalStrategy(
{
usernameField: "email"
},
function(email, password, done) {
User.findOne({ email }, function(err, user) {
if (err) return done(err);
if (!user || !user.validPassword(password))
return done(null, false, { message: "Invalid email/password" });
return done(null, user);
});
})
);

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

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


// Method Override
const methodOverride = require("method-override");
const getPostSupport = require("express-method-override-get-post-support");
app.use(
methodOverride(
getPostSupport.callback,
getPostSupport.options // { methods: ['POST', 'GET'] }
)
);

// Logging
var morgan = require("morgan");
var morganToolkit = require("morgan-toolkit")(morgan);
app.use(morganToolkit());

/// ----------------------------------------
// Template Engine
// ----------------------------------------
var expressHandlebars = require('express-handlebars');

var hbs = expressHandlebars.create({
partialsDir: 'views/',
defaultLayout: 'application',
helpers: {
formatDate: function(date) {
return moment(date).format("MMM Do YY, h:mm:ss a");
}
}
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');


// routes
var loginRouter = require("./routers/login");
app.use("/", loginRouter);

var ponziRouter = require("./routers/ponzi");
app.use("/", ponziRouter);

var schemeRouter = require("./routers/scheme");
app.use("/", schemeRouter);


let port = 4000;
app.listen(port, (res, req) => {
console.log(`Project Ponz running on ${port}`);
});
13 changes: 13 additions & 0 deletions config/mongoose.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"development": {
"database": "project_ponz_dev",
"host": "localhost"
},
"test": {
"database": "project_ponz_test",
"host": "localhost"
},
"production": {
"use_env_variable": "MONGODB_URI"
}
}
67 changes: 67 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcrypt");
const uniqueValidator = require("mongoose-unique-validator");

const UserSchema = mongoose.Schema(
{
email: { type: String, required: true, unique: true },
passwordHash: { type: String },
fname: { type: String },
lname: { type: String },
points: { type: Number },
parent: { type: Schema.Types.ObjectId, ref: "User" },
children: [{ type: Schema.Types.ObjectId, ref: "User" }]
},
{
timestamps: true
}
);

UserSchema.plugin(uniqueValidator);

UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.passwordHash);
};

UserSchema.virtual("password")
.get(function() {
return this._password;
})
.set(function(value) {
this._password = value;
this.passwordHash = bcrypt.hashSync(value, 8);
});

// infinitely populate children
const populateChildren = function(next) {
this.populate("children");
next();
};
UserSchema.pre("find", populateChildren).pre("findOne", populateChildren);

// transverse pyramid
function pointFinder(distance) {
const points = [40, 20, 10, 5, 2];
var value;
distance < 5 ? (value = points[distance]) : (value = 1);
return value;
}

UserSchema.methods.addPoints = async function() {
var distance = 0;
var user = this;
while (user.parent) {
var parent = await User.findById(user.parent);
if (parent) {
parent.points += pointFinder(distance);
parent.save();
distance++;
}
user = parent;
}
};

const User = mongoose.model("User", UserSchema);

module.exports = User;
11 changes: 11 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mongoose = require("mongoose");
const bluebird = require("bluebird");

mongoose.Promise = bluebird;

const models = {};

// Load models and attach to models here
models.User = require("./User");

module.exports = models;
11 changes: 11 additions & 0 deletions mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var mongoose = require('mongoose');
var env = process.env.NODE_ENV || 'development';
var config = require('./config/mongoose')[env];

module.exports = () => {
var envUrl = process.env[config.use_env_variable];
var localUrl = `mongodb://${ config.host }/${ config.database }`;
var mongoUrl = envUrl ? envUrl : localUrl;

return mongoose.connect(mongoUrl);
};
Loading