Advertisement
Guest User

Untitled

a guest
Sep 13th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Global Variables
  2. var express = require("express"),
  3. bodyParser = require("body-parser"),
  4. mysql = require("mysql"),
  5. app = express();
  6.  
  7. // Setting up the static includes, the body parser, and the viewengine
  8. app.use(express.static("public"));
  9. app.use(bodyParser.urlencoded({extended: true}));
  10. app.set("view engine", "ejs");
  11.  
  12. // Establishes a connection to the mysql db
  13. var conn = mysql.createConnection({
  14.     host: "127.0.0.1",
  15.     user: "root",
  16.     password: "2a69sj4hJos",
  17.     database: "c9"
  18. });
  19.  
  20. // START ROUTES
  21.  
  22. app.get("/", function(req, res) {
  23.     // Connect to db
  24.     conn.connect();
  25.    
  26.     var posts;
  27.    
  28.     conn.query("SELECT * FROM posts", function(err, result) {
  29.         if(err) {
  30.             console.log(err);
  31.         } else {
  32.             posts = result;
  33.         }
  34.     });
  35.    
  36.     res.render("home", {posts: posts});
  37. });
  38.  
  39. app.get("/addPost/:password", function(req, res) {
  40.     res.render("addPost", {password: req.params.password});
  41. });
  42.  
  43. // Possible security risk (no verification when manually sending post request)
  44. app.post("/post/:password", function(req, res) {
  45.     if(req.params.password === "2a69sj4hJos") {
  46.         conn.connect();
  47.        
  48.         var post = {
  49.             title: req.body.title,
  50.             body: req.body.body,
  51.             link: req.body.link,
  52.             time: req.body.time
  53.         };
  54.        
  55.         // Inserts a row in the table and sets all the values from the "post" object
  56.         // Returns with a callback function to verify the post
  57.         conn.query("INSERT INTO posts SET ?", post, function(err, result) {
  58.             if(err) {
  59.                 console.error(err);
  60.             } else {
  61.                 console.log("Inserted post to db successfully!");
  62.             }
  63.         });
  64.        
  65.         res.redirect("/addPost/2a69sj4hJos");
  66.     } else {
  67.         res.send("INCORRECT PASSWORD!");
  68.     }
  69. });
  70.  
  71. app.get("*", function(req, res) {
  72.     res.send("404 Error (Page Not Found)");
  73. });
  74.  
  75. // END ROUTES
  76.  
  77. app.listen(process.env.PORT, process.env.IP);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement