Advertisement
Guest User

Untitled

a guest
May 8th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.04 KB | None | 0 0
  1. const express = require('express');
  2. const router = express.Router();
  3. const passport = require('passport');
  4. const User = require('../models/user');
  5. const Book = require('../models/book');
  6. const books = require('google-books-search');
  7. const option = require('../config/bookAPI');
  8. const nodemailer = require('nodemailer');
  9.  
  10. // create reusable transporter object using the default SMTP transport
  11. const transporter = nodemailer.createTransport({
  12. host: 'smtp.gmail.com',
  13. port: 465,
  14. secure: true,
  15. auth: {
  16. user: process.env.GMAIL_USER,
  17. pass: process.env.GMAIL_PASS
  18. }
  19. });
  20.  
  21. function isLoggedIn(req, res, next) {
  22. if(!req.isAuthenticated()) {
  23. req.flash("error", "You must be logged in to do that.");
  24. res.redirect("/login");
  25. }
  26. else{
  27. next();
  28. }
  29. }
  30.  
  31. function isVerified(req, res, next) {
  32. // console.log(req.user.verified);
  33. if(!req.user.verified) {
  34. // console.log(req.user.verified);
  35. req.logout();
  36. req.flash("warning", "Please check your email to verify your account before logging in.");
  37. res.redirect("/login");
  38. } else {
  39. next();
  40. }
  41. }
  42.  
  43. function usernameToLowerCase(req, res, next){
  44. req.body.username = req.body.username.toLowerCase();
  45. next();
  46. }
  47.  
  48.  
  49. // Define a route to the root of the application.
  50. router.get('/', (req, res) => {
  51. res.render('home', {currentUser: req.user});
  52. });
  53.  
  54.  
  55. // Sign up routes
  56. router.get('/signup', (req, res) => {
  57. res.render('signup');
  58. });
  59.  
  60. router.post('/signup', usernameToLowerCase, (req, res) => {
  61. var newUser = new User(
  62. {
  63. verified: false,
  64. first: req.body.first_name,
  65. last: req.body.last_name,
  66. username: req.body.username,
  67. library: [],
  68. wishlist: []
  69.  
  70. });
  71. // Confirm new user's email address to avoid spam registration
  72. var mailOptions,host,link,email;
  73. User.register(newUser, req.body.password, function(err, user) {
  74. if(err) {
  75. // req.flash("error", err);
  76. req.flash("error", "A user with that email already exists.");
  77. res.redirect('signup');
  78. } else {
  79. // A verification link is emailed to user
  80. host = req.get('host');
  81.  
  82. // User ID is the database id
  83. var userID = user.id;
  84.  
  85. // host = "localhost:3000";
  86.  
  87. link ="http://"+host+"/verify/"+userID;
  88.  
  89. // setup email data
  90. email = {
  91. to : req.body.username,
  92. subject : "Bookhunter: Please confirm your Email account",
  93. html : "Hello,<br> Please Click on the link to verify your email for Bookhunter account.<br><a href="+link+">Click here to verify</a>"
  94. };
  95. // send mail with defined transport object
  96. transporter.sendMail(email, (error, info) => {
  97. if (error) {
  98. return console.log(error);
  99. }
  100. console.log('Message sent: %s', info.messageId);
  101. });
  102. req.flash("warning", "Please check your email to verify your account.")
  103. res.redirect('login');
  104. }
  105. });
  106. });
  107.  
  108. router.get('/verify/:id', (req, res) => {
  109. // Search database for user by the id
  110. User.findById(req.params.id, function(err, foundUser){
  111. if (err) {
  112. req.flash("error", JSON.stringify(err));
  113. res.redirect('login');
  114. } else {
  115. //if user exists, set their verified value to true
  116. passport.authenticate('local');
  117. foundUser.verified = true;
  118. foundUser.save();
  119. req.flash("success", "Email verification successful.")
  120. res.redirect('/login');
  121. }
  122. });
  123. });
  124.  
  125.  
  126. // Log in routes
  127. router.get('/login', (req, res) => {
  128. res.render('login');
  129. });
  130.  
  131.  
  132. router.post('/login', usernameToLowerCase, passport.authenticate('local',
  133. {
  134. successRedirect: '/profile',
  135. failureRedirect: 'login',
  136. failureFlash: true
  137. }), (req, res) => {
  138.  
  139. });
  140.  
  141.  
  142. // Log out route
  143. router.get("/logout", function(req, res) {
  144. req.logout();
  145. req.flash("success", "Successfully logged out.");
  146. res.redirect("/login");
  147. });
  148.  
  149. // All Books route
  150. router.get('/allbooks', isLoggedIn, isVerified, (req, res) => {
  151. User.find({}, function(err, allUsers) {
  152. if(err) {
  153. console.log(err);
  154. } else {
  155. res.render("allbooks", {users: allUsers, currentUser: req.user});
  156. }
  157. });
  158. });
  159.  
  160. // Help Page route
  161. router.get('/help', (req, res) => {
  162. res.render('help', {currentUser: req.user});
  163. });
  164.  
  165. // Contact form submission route
  166. router.post('/send', (req, res) => {
  167. const output = `
  168. <p>You have a new contact request:</p>
  169. <h3>Contact Details</h3>
  170. <ul>
  171. <li>Name: ${req.body.contact_name}</li>
  172. <li>Email: ${req.body.contact_email}</li>
  173. <li>Subject: ${req.body.contact_subject}</li>
  174. </ul>
  175. <h3>Message</h3>
  176. <p>${req.body.contact_message}</p>
  177. `;
  178.  
  179. // setup email data with unicode symbols
  180. let mailOptions = {
  181. from: '"Nodemailer Contact" <test@bookhunter.com', // sender address
  182. to: 'bookhunter.huntercollege@gmail.com', // list of receivers
  183. subject: 'New message from contact form at BookHunter.com',
  184. text: "Hello Boookhunter!",
  185. html: output
  186. };
  187.  
  188. // send mail with defined transport object
  189. transporter.sendMail(mailOptions, (error, info) => {
  190. if (error) {
  191. return console.log(error);
  192. }
  193. console.log('Message sent: %s', info.messageId);
  194. console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
  195.  
  196. // rerender our home page with message
  197. res.render('home', {msg: "Thank you! Email has been sent."});
  198. });
  199.  
  200. });
  201.  
  202. // Testing profile page
  203. router.get('/profile', isLoggedIn, isVerified, (req, res) => {
  204.  
  205. User.find({}, function(err, allUsers) {
  206. if(err) {
  207. console.log(err);
  208. }
  209. Book.find( {book_owner: req.user.id, inLibrary: true}, function(err, librarybooks){
  210.  
  211. if(err){
  212. console.log(err);
  213. }
  214. else {
  215. Book.find( {book_owner: req.user.id, inWishlist: true}, function(err, wishlistbooks){
  216. if(err){
  217. console.log(err);
  218. }
  219. else {// console.log(books);
  220. res.render("profile", {
  221. librarybooks: librarybooks,
  222. wishlistbooks: wishlistbooks,
  223. users: allUsers,
  224. currentUser: req.user
  225. });
  226. }
  227. })
  228. }
  229. });
  230.  
  231. });
  232. });
  233. // Testing Add Book page
  234. // router.get('/addbook', isLoggedIn, (req, res) => {
  235. // res.render('addbook', {currentUser: req.user});
  236. // });
  237.  
  238. // SEARCH ROUTE FOR BOOKS TO ADD THEM TO THE LIBRARY
  239. router.get('/search', isLoggedIn, (req, res) => {
  240. var title = req.query.title;
  241. // console.log(title);
  242. books.search(title, option, function(error, results, apiResponse){
  243. if(!error){
  244. //console.log(results);
  245. res.render('search', {
  246. currentUser: req.user,
  247. title: req.query.title,
  248. books: results
  249. })
  250. } else {
  251. //console.log(error);
  252. res.status(404).send('File Not Found!');
  253. }
  254. })
  255. });
  256.  
  257. //ADD A BOOK TO USER'S LIBRARY
  258. router.post('/toLibrary',isLoggedIn, function(req,res){
  259. var newBook = new Book({
  260. book_id: req.body.book_id,
  261. book_title: req.body.book_title,
  262. book_link: req.body.book_link,
  263. book_publisher: req.body.book_publisher,
  264. book_thumbnail: req.body.book_thumbnail,
  265. book_owner: req.user._id,
  266. inWishlist: false,
  267. inLibrary: true
  268. });
  269.  
  270. newBook.save(function(err){
  271. if(err){
  272. console.log(err);
  273. }
  274. User.findById(req.user._id, function(err, foundUser){
  275. if(err){
  276. console.log(err);
  277. return;
  278. }
  279. foundUser.library.push(newBook);
  280. foundUser.save(function(err){
  281. if(err){
  282. console.log(err);
  283. return;
  284. }
  285. res.redirect('/profile');
  286. })
  287. })
  288. })
  289. });
  290.  
  291. //ADD A BOOK TO USER'S WISHLIST
  292. router.post('/toWishlist',isLoggedIn, function(req,res){
  293. var newBook = new Book({
  294. book_id: req.body.book_id,
  295. book_title: req.body.book_title,
  296. book_link: req.body.book_link,
  297. book_publisher: req.body.book_publisher,
  298. book_thumbnail: req.body.book_thumbnail,
  299. book_owner: req.user._id,
  300. inWishlist: true,
  301. inLibrary: false
  302. });
  303.  
  304. newBook.save(function(err){
  305. if(err){
  306. console.log(err);
  307. }
  308. User.findById(req.user._id, function(err, foundUser){
  309. if(err){
  310. console.log(err);
  311. return;
  312. }
  313. foundUser.wishlist.push(newBook);
  314. foundUser.save(function(err){
  315. if(err){
  316. console.log(err);
  317. return;
  318. }
  319. res.redirect('/profile');
  320. })
  321. })
  322. })
  323. });
  324.  
  325. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement