Guest User

server.js

a guest
Mar 21st, 2018
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var morgan = require('morgan');
  3. var path = require('path');
  4. var Pool = require('pg').Pool;
  5. var crypto = require('crypto');
  6. var bodyParser = require('body-parser');
  7. var session = require('express-session');
  8.  
  9. var config = {
  10.     user: 'vimalsingh992',
  11.     database: 'vimalsingh992',
  12.     host: 'db.imad.hasura-app.io',
  13.     port: '5432',
  14.     password: process.env.DB_PASSWORD
  15. };
  16.  
  17. var app = express();
  18. app.use(morgan('combined'));
  19. app.use(bodyParser.json());
  20. app.use(session({
  21.     secret: 'someRandomSecretValue',
  22.     cookie: { maxAge: 1000 * 60 * 60 * 24 * 30}
  23. }));
  24.  
  25. var articles = {
  26.     'article-1': {
  27.         title: 'Article One',
  28.         date: 'Feb 18,2018',
  29.         heading: 'Article One',
  30.         content: `  <p>
  31.                         This is the content for my first article.
  32.                     </p>
  33.                     <p>
  34.                         This is the content for my first article.This is the content for my first article.This is the content for my first article.
  35.                     </p>
  36.                     <p>
  37.                         This is the content for my first article.Bingo!!!!!!
  38.                     </p>`
  39.     },
  40.     'article-TWO': {
  41.         title: 'Article Two | VIMAL',
  42.         date: 'Feb 18,2018',
  43.         heading: 'Article Two',
  44.         content: `  <p>
  45.                         This is the content for my Second article.
  46.                     </p>
  47.                     <p>
  48.                         This is the content for my second article.This is the content for my second article.This is the content article.
  49.                     </p>
  50.                     <p>
  51.                         This is the content for my  article.Bingo!!!!!!
  52.                     </p>`
  53.     },
  54.     'article-3': {
  55.         title: 'Article Three | Vimal',
  56.         date: 'Feb 18,2018',
  57.         heading: 'Article Three',
  58.         content: `  <p>
  59.                         This is the content for my first article.
  60.                     </p>
  61.                     <p>
  62.                         This is the content for my first article.This is the content for my first article.This is the content for my first article.
  63.                     </p>
  64.                     <p>
  65.                         This is the content for my first article.Bingo!!!!!!
  66.                     </p>`
  67.     }
  68. };
  69.  
  70. function createTemplate (data) {
  71.     var title = data.title;
  72.     var heading = data.heading;
  73.     var content = data.content;
  74.    
  75.     var htmlTemplate = `<html>
  76.         <head>
  77.             <title>
  78.                 ${title}
  79.             </title>
  80.             <meta name='viewport' content="width=device-width, initial-scale=1" />
  81.             <link href="/ui/style.css" rel="stylesheet" />
  82.             <style>
  83.                
  84.             </style>
  85.         </head>
  86.         <body>
  87.             <div class="container">
  88.                 <div>
  89.                     <a href='/'>Home</a>
  90.                 </div>
  91.                 <hr/>
  92.                 <h3>
  93.                     ${heading}
  94.                 </h3>
  95.                 <div>
  96.                     articleOne.date;    
  97.                 </div>
  98.                 <div>
  99.                     ${content}
  100.                 </div>
  101.             </div>
  102.         </body>
  103.     </html>
  104.     `;
  105.     return htmlTemplate;
  106. }
  107.  
  108. app.get('/', function (req, res) {
  109.   res.sendFile(path.join(__dirname, 'ui', 'index.html'));
  110. });
  111.  
  112. function hash(input, salt) {
  113.     var hashed = crypto.pbkdf2Sync(input, salt, 10000, 512, 'sha512');
  114.     return ["pbkdf2Sync", "10000", salt, hashed.toString('hex')].join('$');
  115. }
  116.  
  117. app.get('/hash/:input', function(req, res) {
  118.     var hashedString = hash(req.params.input, 'this-is-some-random-string');
  119.     res.send(hashedString);
  120. });
  121.  
  122. app.post('/create-user', function(req, res)  {
  123.    //username, password
  124.    //JSON
  125.    var username = req.body.username;
  126.    var password = req.body.password;
  127.    var salt = crypto.randomBytes(128).toString('hex');
  128.    var dbString = hash(password, salt);
  129.    pool.query('INSERT INTO "user" (username, password) VALUES ($1, $2)', [username, dbString], function(err, result) {
  130.        if (err) {
  131.            //res.status(500).send(err.toString());
  132.            res.setHeader('Content-Type', 'application/json');
  133.            res.status(500).send(JSON.stringify({"error":err.toString()}));
  134.        } else {
  135.            res.setHeader('Content-Type', 'application/json');
  136.            res.send(JSON.parse('{"message":"User successfully created: ' + username + ' "} ') );
  137.        }
  138.    });
  139. });
  140.  
  141. app.post('/login', function (req, res) {
  142.    var username = req.body.username;
  143.    var password = req.body.password;
  144.    pool.query('SELECT * FROM "user" WHERE username = $1', [username], function(err, result) {
  145.        if (err) {
  146.            //res.status(500).send(err.toString());
  147.            res.setHeader('Content-Type', 'application/json');
  148.            res.status(500).send(JSON.stringify({"error":err.toString()}));
  149.        } else {
  150.            if (result.rows.length === 0) {
  151.                //res.status(403).send('username/password is invalid'); //.send(403)
  152.                //For app
  153.                res.setHeader('Content-Type', 'application/json');
  154.                res.status(403).send(JSON.parse('{"error": "username/password is invalid"}'));
  155.            } else {
  156.                //Password matching here
  157.                var dbString = result.rows[0].password;
  158.                var salt = dbString.split('$')[2];
  159.                var hashedPassword = hash(password, salt);
  160.                if (hashedPassword === dbString) {
  161.                    
  162.                    //Set a session
  163.                    req.session.auth = {userId: result.rows[0].id};
  164.                    
  165.                    //res.send('Credentials correct!');
  166.                    //for app
  167.                    res.setHeader('Content-Type', 'application/json');
  168.                    res.send(JSON.parse('{"message":"You have successfully logged in"}'));
  169.                    
  170.                    
  171.                } else {
  172.                    //res.status(403).send('INVALIDDDDDDDD');
  173.                    //For app
  174.                    res.setHeder('Content-Type', 'application/json');
  175.                    res.status(403).send(JSON.parse('{"error": "username/password is invalid server"}'));
  176.                }
  177.            }
  178.            // res.send('User successfully created: ' + username);
  179.        }
  180.    });
  181. });
  182.  
  183. app.get('/check-login', function(req, res) {
  184.     if (req.session && req.session.auth && req.session.auth.userId) {
  185.         res.send('You are logged in: ' + req.session.auth.userId.toString());
  186.     } else {
  187.         res.send('not logged in');
  188.     }
  189. });
  190.  
  191. app.get('/logout', function (req,res) {
  192.     delete req.session.auth;
  193.     res.send('Logged out');
  194. });
  195.  
  196. var pool = new Pool(config);
  197. app.get('/test-db', function(req, res) {
  198.    //make a select request
  199.    //return a response with the results
  200.    pool.query('SELECT * FROM test', function(err, result) {
  201.        if (err) {
  202.            res.status(500).send(err.toString());
  203.        } else {
  204.            res.send(JSON.stringify(result.rows));
  205.        }
  206.    });
  207. });
  208.  
  209. var counter = 0;
  210. app.get('/counter', function(req, res) {
  211.     counter = counter + 1;
  212.     res.send(counter.toString());
  213. });
  214.  
  215. var names = [];
  216. app.get('/submit-name', function(req, res) {//URL: /submit-name?name=xxxxx
  217.     //Get the name from the request
  218.     var name = req.query.name; //To do
  219.    
  220.     names.push(name);
  221.     //JSON js object notation
  222.     res.send(JSON.stringify(names));
  223. });
  224.  
  225.  
  226. app.get('/articles/:articleName', function (req, res) {     //Doubt here
  227.     //articleName = article-one
  228.     pool.query("SELECT * FROM article WHERE title = $1" , [req.params.articleName], function (err, result) {
  229.         if (err) {
  230.             res.status(500).send(err.toString());
  231.         } else {
  232.             if (result.rows.length === 0) {
  233.                 res.status(404).send('Article not fnd');
  234.             } else {
  235.                 var articleData = result.rows[0];
  236.                 res.send(createTemplate(articleData));
  237.             }
  238.         }
  239.     });
  240. });
  241.  
  242. app.get('/ui/style.css', function (req, res) {
  243.   res.sendFile(path.join(__dirname, 'ui', 'style.css'));
  244. });
  245.  
  246. app.get('/ui/main.js', function (req, res) {
  247.   res.sendFile(path.join(__dirname, 'ui', 'main.js'));
  248. });
  249.  
  250. app.get('/ui/madi.png', function (req, res) {
  251.   res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
  252. });
  253.  
  254.  
  255. // Do not change port, otherwise your app won't run on IMAD servers
  256. // Use 8080 only for local development if you already have apache running on 80
  257.  
  258. var port = 80;
  259. app.listen(port, function () {
  260.   console.log(`IMAD course app listening on port ${port}!`);
  261. });
Add Comment
Please, Sign In to add comment