diff --git a/config/passport.js b/config/passport.js index d8b51b8..3ace09d 100644 --- a/config/passport.js +++ b/config/passport.js @@ -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, }; diff --git a/config/passportLocal.js b/config/passportLocal.js index cc0da44..2b69e93 100644 --- a/config/passportLocal.js +++ b/config/passportLocal.js @@ -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); }); -} \ No newline at end of file + }); +}; diff --git a/helpers/getCompanyNameAndLogo.js b/helpers/getCompanyNameAndLogo.js index 833e1dc..7463a4c 100644 --- a/helpers/getCompanyNameAndLogo.js +++ b/helpers/getCompanyNameAndLogo.js @@ -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; }; diff --git a/helpers/getOverview.js b/helpers/getOverview.js index f35b80c..b72dfeb 100644 --- a/helpers/getOverview.js +++ b/helpers/getOverview.js @@ -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}` @@ -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", { @@ -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); diff --git a/helpers/getPrice.js b/helpers/getPrice.js index 18ae469..18877da 100644 --- a/helpers/getPrice.js +++ b/helpers/getPrice.js @@ -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; }; diff --git a/middleware/auth.js b/middleware/auth.js index bb38a58..2226f9b 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -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) { diff --git a/routes/api/addBalance.js b/routes/api/addBalance.js index 389214b..7fe0d7b 100644 --- a/routes/api/addBalance.js +++ b/routes/api/addBalance.js @@ -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"); } }); diff --git a/routes/api/auth.js b/routes/api/auth.js index f5a41a7..221ac66 100644 --- a/routes/api/auth.js +++ b/routes/api/auth.js @@ -21,13 +21,13 @@ router.get( } ); -router.post('/signin', (req, res, next) => { - passport.authenticate('local', { - successRedirect: '/portfolio', - failureRedirect: '/', - failureFlash: true - })(req, res, next) -}) +router.post("/signin", (req, res, next) => { + passport.authenticate("local", { + successRedirect: "/portfolio", + failureRedirect: "/", + failureFlash: true, + })(req, res, next); +}); // @desc Logout user // @route /auth/logout diff --git a/routes/api/cart.js b/routes/api/cart.js index 3324d45..a2ac132 100644 --- a/routes/api/cart.js +++ b/routes/api/cart.js @@ -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 diff --git a/routes/api/done.js b/routes/api/done.js index 2ef5466..c8c0327 100644 --- a/routes/api/done.js +++ b/routes/api/done.js @@ -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; \ No newline at end of file +module.exports = router; diff --git a/routes/api/user.js b/routes/api/user.js index 4efffba..3874ef0 100644 --- a/routes/api/user.js +++ b/routes/api/user.js @@ -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 @@ -11,68 +11,89 @@ 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 -router.post('/signup', (req, res) => { - const { firstName, lastName, password1, password2, email } = req.body; - let errors = []; +router.post("/signup", (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 -router.post('/signin', (req, res, next) => { - passport.authenticate('local', { - successRedirect: '/portfolio', - failureRedirect: '/', - failureFlash: true, - })(req, res, next) -}) +router.post("/signin", (req, res, next) => { + passport.authenticate("local", { + successRedirect: "/portfolio", + failureRedirect: "/", + failureFlash: true, + })(req, res, next); +}); -module.exports = router; \ No newline at end of file +module.exports = router; diff --git a/routes/api/view.js b/routes/api/view.js index cf634cf..da88452 100644 --- a/routes/api/view.js +++ b/routes/api/view.js @@ -70,7 +70,7 @@ router.get("/:symbol", ensureAuth, async (req, res) => { res.status(200).render("view", { layout: "layouts/app", - href: '/market', + href: "/market", avatar: req.user.image, symbol, data, diff --git a/views/addBalance.ejs b/views/addBalance.ejs index 9f05175..2076304 100644 --- a/views/addBalance.ejs +++ b/views/addBalance.ejs @@ -1,14 +1,27 @@