Skip to content

Commit

Permalink
Merge branch 'master' of TradeByte into fix/iampavangandhi#46
Browse files Browse the repository at this point in the history
  • Loading branch information
fabcodingzest committed Aug 22, 2020
2 parents 424667d + 0b99ae5 commit 3ccea18
Show file tree
Hide file tree
Showing 18 changed files with 1,188 additions and 726 deletions.
3 changes: 2 additions & 1 deletion config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ module.exports = function (passport) {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
email: profile.emails[0].value,
password: "google-oauth-MOGicvVFYPzk9O7Y1vAo",
password:
process.env.OAUTH_PASS || "google-oauth-MOGicvVFYPzk9O7Y1vAo",
image: profile.photos[0].value,
balance: 10000,
};
Expand Down
64 changes: 32 additions & 32 deletions config/passportLocal.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");

// Load User model
const User = require('../models/User');
const User = require("../models/User");

module.exports = function (passport) {
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// Match User
User.findOne({
email: email
}).then(user => {
if (!user) {
return done(null, false, { message: 'That email is not registered' })
}
passport.use(
new LocalStrategy({ usernameField: "email" }, (email, password, done) => {
// Match User
User.findOne({
email: email,
}).then((user) => {
if (!user) {
return done(null, false, { message: "That email is not registered" });
}

// Match user Password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
done(null, user);
} else {
return done(null, false, { message: 'That password is incorrect' })
}
})
})
})
)
// Match user Password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
done(null, user);
} else {
return done(null, false, { message: "That password is incorrect" });
}
});
});
})
);

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

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
}
});
};
30 changes: 18 additions & 12 deletions helpers/getCompanyNameAndLogo.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@
const axios = require("axios");

module.exports = async function getCompanyNameAndLogo(symbol) {

let data = await axios
let data = await axios
.get(
`https://www.alphavantage.co/query?function=OVERVIEW&symbol=${symbol}&apikey=${process.env.ALPHA_VANTAGE_KEY}`
)
.then(async (resp) => {
let companyName = resp.data.Name;
let logoSrc = await axios
.get(
`https://www.alphavantage.co/query?function=OVERVIEW&symbol=${symbol}&apikey=${process.env.ALPHA_VANTAGE_KEY}`
`https://autocomplete.clearbit.com/v1/companies/suggest?query=:${
companyName.split(" ")[0]
}`
)
.then(async (resp) => {
let companyName = resp.data.Name;
let logoSrc = await axios.get(`https://autocomplete.clearbit.com/v1/companies/suggest?query=:${companyName.split(' ')[0]}`).then((resp) => resp.data[0].logo).catch(err => console.log(err));
return { companyName, logoSrc };
})
.catch((err) => {
console.log(err);
});
.then((resp) => resp.data[0].logo)
.catch((err) => console.log(err));
return { companyName, logoSrc };
})
.catch((err) => {
console.log(err);
});

return data;
return data;
};
7 changes: 3 additions & 4 deletions helpers/getOverview.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
const axios = require("axios");

module.exports = async function getOverview(symbol) {

let data = await axios
.get(
`https://www.alphavantage.co/query?function=OVERVIEW&symbol=${symbol}&apikey=${process.env.ALPHA_VANTAGE_KEY}`
Expand All @@ -14,8 +13,8 @@ module.exports = async function getOverview(symbol) {
Exchange: resp.data.Exchange,
Currency: resp.data.Currency,
Country: resp.data.Country,
weeksHigh: resp.data['52WeekHigh'],
weeksLow: resp.data['52WeekLow'],
weeksHigh: resp.data["52WeekHigh"],
weeksLow: resp.data["52WeekLow"],
Desc: resp.data.Description,
Sector: resp.data.Sector,
MarketCap: new Intl.NumberFormat("en-US", {
Expand All @@ -32,7 +31,7 @@ module.exports = async function getOverview(symbol) {
DividendYield: resp.data.DividendYield,
BookValue: resp.data.BookValue,
ProfitMargin: resp.data.ProfitMargin,
RevenueTTM: resp.data.RevenueTTM
RevenueTTM: resp.data.RevenueTTM,
}))
.catch((err) => {
console.log(err);
Expand Down
2 changes: 1 addition & 1 deletion helpers/getPrice.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = async function getPrice(symbol) {
let latestPrice = res["Global Quote"]["05. price"];
let low = res["Global Quote"]["04. low"];
let high = res["Global Quote"]["03. high"];
return {latestPrice,high,low};
return { latestPrice, high, low };
});
return stockPrice;
};
4 changes: 2 additions & 2 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ module.exports = {
if (req.isAuthenticated()) {
return next();
} else {
req.flash('error_msg', 'Password or Email does not match');
res.redirect('/');
req.flash("error_msg", "Password or Email does not match");
res.redirect("/");
}
},
ensureGuest: function (req, res, next) {
Expand Down
26 changes: 13 additions & 13 deletions routes/api/addBalance.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,34 @@ const User = require("../../models/User");
// @route GET /
// @access Private
router.get("/", ensureAuth, (req, res) => {
let user = req.user
res.status(200).render("addBalance"), {
user,
}

let user = req.user;
res.status(200).render("addBalance"),
{
user,
};
});

// TODO
router.post("/", ensureAuth, async (req, res) => { // why ensureGuest here?
let amount = Number(req.body.addAmount); // type cast amount to number as body parser take it as string
router.post("/", ensureAuth, async (req, res) => {
// why ensureGuest here?
let amount = Number(req.body.addAmount); // type cast amount to number as body parser take it as string
let finalAmont = amount + req.user.balance;

try {
req.body.user = req.user.id;
const updateBalance = await User.findOneAndUpdate(
{ _id: req.user.id },
{ balance: finalAmont},
{ balance: finalAmont },
{
new: true, // it will create a new one, if it doesn't exist
new: true, // it will create a new one, if it doesn't exist
runValidators: true, // it check weather the fields are valid or not
}
)
);
console.log(updateBalance);
res.redirect("/");

} catch (err) {
console.error(err)
res.render('error/500')
console.error(err);
res.render("error/500");
}
});

Expand Down
12 changes: 11 additions & 1 deletion routes/api/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,17 @@ router.get("/:symbol", ensureAuth, async (req, res) => {
const symbol = req.params.symbol;
const { latestPrice } = await getPrice(symbol);
const { companyName, logoSrc } = await getCompanyNameAndLogo(symbol);
res.status(200).render("cart", { layout: "layouts/app", symbol, latestPrice, logoSrc, companyName, href: '/market', avatar: req.user.image });
res
.status(200)
.render("cart", {
layout: "layouts/app",
symbol,
latestPrice,
logoSrc,
companyName,
href: "/market",
avatar: req.user.image,
});
});

// @desc To buy
Expand Down
7 changes: 2 additions & 5 deletions routes/api/done.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ const { ensureAuth, ensureGuest } = require("../../middleware/auth");
// @route GET /done
// @access Private
router.get("/", ensureAuth, (req, res) => {
res.status(200)
.render("done");
res.status(200).render("done");
});



module.exports = router;
module.exports = router;
115 changes: 68 additions & 47 deletions routes/api/user.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const express = require("express");
const router = express.Router();
const passport = require("passport")
const passport = require("passport");
const bcrypt = require("bcryptjs");
const {v4: uuidv4} = require("uuid");
const { v4: uuidv4 } = require("uuid");
const { ensureGuest } = require("../../middleware/auth");

// Load User Model
Expand All @@ -11,9 +11,9 @@ const User = require("../../models/User");
// @desc Sign Up Page
// @route GET /user/signup
// @access Public
router.get('/signup', ensureGuest, (req, res) => {
res.status(200).render('signup', { layout: 'layouts/login' })
})
router.get("/signup", ensureGuest, (req, res) => {
res.status(200).render("signup", { layout: "layouts/login" });
});

// @desc Submit Sign Up Form
// @route GET /user/signup
Expand All @@ -22,49 +22,70 @@ router.post('/signup', ensureGuest, (req, res) => {
const { firstName, lastName, password1, password2, email } = req.body;
let errors = [];

if (!firstName || !lastName || !password1 || !password2 || !email) {
errors.push({ msg: 'Please enter all fields' });
}
if (password1 !== password2) {
errors.push({ msg: 'Passwords do not match' })
}
if (password1.length < 6) {
errors.push({ msg: 'Password must be longer than 6 characters' })
}
if (!firstName || !lastName || !password1 || !password2 || !email) {
errors.push({ msg: "Please enter all fields" });
}
if (password1 !== password2) {
errors.push({ msg: "Passwords do not match" });
}
if (password1.length < 6) {
errors.push({ msg: "Password must be longer than 6 characters" });
}

if (errors.length > 0) {
res.render('signup', { layout: 'layouts/login', errors, firstName, lastName, password1, password2 })
} else {
User.findOne({ email: email }).then((user) => {
if (user) {
errors.push({ msg: 'Email already exists' })
res.render('signup', { layout: 'layouts/login', errors, firstName, lastName, password1, password2 })
} else {
const newUser = new User({
googleId: uuidv4(),
displayName: `${firstName} ${lastName}`,
firstName,
lastName,
email,
image: 'https://t3.ftcdn.net/jpg/00/64/67/52/240_F_64675209_7ve2XQANuzuHjMZXP3aIYIpsDKEbF5dD.jpg',
password: password1,
balance: 10000,
})
if (errors.length > 0) {
res.render("signup", {
layout: "layouts/login",
errors,
firstName,
lastName,
password1,
password2,
});
} else {
User.findOne({ email: email }).then((user) => {
if (user) {
errors.push({ msg: "Email already exists" });
res.render("signup", {
layout: "layouts/login",
errors,
firstName,
lastName,
password1,
password2,
});
} else {
const newUser = new User({
googleId: uuidv4(),
displayName: `${firstName} ${lastName}`,
firstName,
lastName,
email,
image:
"https://t3.ftcdn.net/jpg/00/64/67/52/240_F_64675209_7ve2XQANuzuHjMZXP3aIYIpsDKEbF5dD.jpg",
password: password1,
balance: 10000,
});

bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save().then(user => {
req.flash('success_msg', 'You are now registered and can log in')
res.status(200).redirect('/')
}).catch((err) => console.log(err))
})
})
}
})
}
})
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then((user) => {
req.flash(
"success_msg",
"You are now registered and can log in"
);
res.status(200).redirect("/");
})
.catch((err) => console.log(err));
});
});
}
});
}
});

// @desc Submit Sign In Form
// @route GET /user/signin
Expand All @@ -76,4 +97,4 @@ router.post('/signin', ensureGuest, (req, res, next) => {
})(req, res, next)
})

module.exports = router;
module.exports = router;
Loading

0 comments on commit 3ccea18

Please sign in to comment.