Advertisement
PavelPetrov

PPetrov Nodejs CRUD3

Apr 5th, 2019
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //ver.7_4
  2. //https://getbootstrap.com/docs/4.0/components/modal/
  3.  
  4. fs = require('fs');
  5. if (!fs.existsSync('./images')){
  6.     fs.mkdirSync('./images');
  7. }
  8.  
  9. bcrypt = require('bcryptjs');
  10. sqlite3 = require('sqlite3');
  11. db = new sqlite3.Database('7_3.sqlitedb');
  12. db.serialize();
  13. db.run(`CREATE TABLE IF NOT EXISTS guestbook(
  14.     id INTEGER PRIMARY KEY,
  15.     user TEXT NOT NULL,
  16.     msg TEXT,
  17.     url TEXT,
  18.     date_created TEXT,
  19.     date_modified TEXT)`
  20. );
  21. db.parallelize();
  22.  
  23. express = require('express');
  24. bodyParser = require('body-parser');
  25. cookieParser = require('cookie-parser');
  26. session = require('express-session');
  27. pug = require('pug');
  28. fileUpload = require('express-fileupload');
  29.  
  30. app = express();
  31. app.use(bodyParser.urlencoded({ extended: true }));
  32. app.set('view engine', 'pug');
  33. app.set('views','./');
  34. app.use(cookieParser());
  35. app.use(session({
  36.     secret: 'random string',
  37.     resave: true,
  38.     saveUninitialized: true,
  39. }));
  40. app.use(fileUpload());
  41. app.use('/images', express.static('./images'));
  42.  
  43. app.listen(8080);
  44.  
  45. //......>node
  46. //>require('bcryptjs').hash('demo', 5, (err, hash) => {console.log(hash);});
  47. //>.exit
  48.  
  49. users = {
  50.     ivan: '$2a$05$FIsj86AKAr5JnYg6DujY4.96JBPQCBT/POVh5LJH3hea6I3UvG5D6',   //123
  51.     radka: '$2a$05$zcGdceWWgx8zoAeznnRC2.j5HsZH4Z2W1AOIv/aYCWsDIs4QU6iMa',  //888
  52.     nasko: '$2a$05$6OBgnb6tpI4GmlrTvaxPB.fR0QhOieMyvN4EDmhSacU4bP0TsqzGW',  //777
  53.     demo: '$2a$05$8/jm5CN0Er1iqkyoNlosQu5M7Acq.9wS6yNVhd7e72L7nThMTmQRW'    //demo
  54. };
  55.  
  56. app.get('/login', function(req, res) {
  57. //If template is in file login.pug
  58. //res.render('login', {info: 'PLEASE LOGIN'});
  59.     res.send(pug.render(login, {info: 'PLEASE LOGIN'}));
  60. });
  61.  
  62. app.post('/login', function(req, res){
  63.     bcrypt.compare(req.body.password, users[req.body.username] || "", function(err, is_match) {
  64.         if(err) throw err;
  65.         if(is_match === true) {
  66.             req.session.username = req.body.username;
  67.             req.session.count = 0;
  68.             res.redirect("/guestbook");
  69.         } else {
  70.             res.send(pug.render(login, {warn: 'TRY AGAIN'}));
  71.         }
  72.     });
  73. });
  74.  
  75. app.get('/logout', (req, res) => {
  76.     req.session.destroy();
  77.     res.redirect("/");
  78. });
  79.  
  80. app.all('*', function(req, res, next) {
  81.     if(req.session.username) return next();
  82.     else res.redirect("/login");
  83. });
  84.  
  85. //CRUD
  86. //cREADud
  87. app.get('/guestbook', (req, res) => {
  88.     req.session.count++;
  89.     s = "User: " + req.session.username + " Count: " + req.session.count;
  90.     s += " :: <a href=''>reload</a> :: <a href='logout'>LOGOUT</a> :: ";
  91.     s += new Date();
  92.     let rows = [];
  93.     db.all('SELECT * FROM guestbook ORDER BY date_modified DESC;', function(err, rows) {
  94.         if(err) throw err;
  95.         res.send(pug.render(gb, {'info': s, rows: rows}));
  96.     });
  97. });
  98.  
  99. //CREATErud Add message Picture URL
  100. app.post('/save',(req, res) => {
  101.     db.run(`
  102.         INSERT INTO guestbook(
  103.             user,
  104.             msg,
  105.             url,
  106.             date_created,
  107.             date_modified
  108.         ) VALUES (
  109.             ?,
  110.             ?,
  111.             ?,
  112.             DATETIME('now','localtime'),
  113.             DATETIME('now','localtime'));
  114.         `,
  115.         [req.session.username, req.body.msg || "", req.body.url],
  116.         (err) => {
  117.             if(err) throw err;
  118.             res.redirect('/guestbook');
  119.         });
  120. });
  121.  
  122. //CREATErud2 Add message2 Picture upload
  123. app.post('/upload',(req, res) => {
  124.     url = "";
  125.     if(req.files && req.files.file) {
  126.         req.files.file.mv('./images/' + req.files.file.name, (err) => {
  127.             if (err) throw err;
  128.         });
  129.         url = '/images/' + req.files.file.name;
  130.     }
  131.        
  132.     db.run(`
  133.         INSERT INTO guestbook(
  134.             user,
  135.             msg,
  136.             url,
  137.             date_created,
  138.             date_modified
  139.         ) VALUES (
  140.             ?,
  141.             ?,
  142.             ?,
  143.             DATETIME('now','localtime'),
  144.             DATETIME('now','localtime'));
  145.         `,
  146.         [req.session.username, req.body.msg || "", url],
  147.         (err) => {
  148.             if(err) throw err;
  149.             res.redirect('/guestbook');
  150.         });
  151. });
  152.  
  153. //cruDELETE
  154. app.post('/delete',(req, res) => {
  155.     db.run('DELETE FROM guestbook WHERE id = ?', req.body.id, (err) => {
  156.         if(err) throw err;
  157.         res.redirect('/guestbook');
  158.     });
  159. });
  160.  
  161. //crUPDATEd POST
  162. app.post('/update',(req, res) => {
  163.     db.run(`UPDATE guestbook
  164.             SET user = ?,
  165.                 msg = ?,
  166.                 url = ?,
  167.                 date_modified = DATETIME('now','localtime')
  168.             WHERE id = ?;`,
  169.         req.session.username,
  170.         req.body.msg,
  171.         req.body.url,
  172.         req.body.id,
  173.         (err) => {
  174.             if(err) throw err;
  175.             res.redirect('/guestbook');
  176.     });
  177. });
  178.  
  179.  
  180. app.all('*', function(req, res) {
  181.     res.send("No such page! Go to: <a href='/guestbook'>main page</a>");
  182. });
  183.  
  184. login = `
  185. html
  186.     head
  187.         link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css")
  188.     body
  189.         if info
  190.             h1.alert.alert-info=info
  191.         if warn
  192.             h1.alert.alert-warning #{warn}
  193.         form.mx-auto.border.border-primary.w-25.p-3(method="post")
  194.             div.form-group
  195.                 label Username:
  196.                 input.form-control(type="text" name="username" placeholder=" Enter user name " value="demo")
  197.             div.form-group
  198.                 label Password:
  199.                 input.form-control(type="password" name="password" value="demo")
  200.             div.form-group
  201.                 input.btn.btn-primary(type="submit" value="Login")
  202. `;
  203.  
  204. gb = `
  205. html
  206.     head
  207.         link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css")
  208.     body
  209.         if info
  210.             h1.alert.alert-info!= info 
  211.         div.container
  212.             h2 Guest Book
  213.             button.btn.btn-success(data-toggle="modal" data-target="#modalAdd") + Add New Message (with URL) +
  214.             span &nbsp;&nbsp;&nbsp;
  215.             button.btn.btn-success(data-toggle="modal" data-target="#modalAdd2") + Add New Message2 (Picture upload) +
  216.             table.table.table-striped.table-hover#mytable
  217.                 thead.bg-warning.text-uppercase.font-weight-bold
  218.                     tr
  219.                         td id
  220.                         td user
  221.                         td msg
  222.                         td img
  223.                         td date_created
  224.                         td ^date_modified^
  225.                         td action
  226.                 tbody
  227.                     each row in rows
  228.                         tr
  229.                             td= row.id
  230.                             td= row.user
  231.                             td
  232.                                 pre= row.msg
  233.                             td
  234.                                 img.img-fluid.rounded-circle.img-thumbnail(src=row.url)
  235.                             td= row.date_created
  236.                             td= row.date_modified
  237.                             td
  238.                                 div.row
  239.                                     a.btn.btn-info.edit(href="javascript:void(0);" data-id=row.id data-msg=row.msg data-url=row.url) EDIT
  240.                                     span &nbsp;&nbsp;&nbsp;
  241.                                     a.btn.btn-danger.delete(href="javascript:void(0);" data-id=row.id) X
  242.  
  243.             //modal form ADD - Picture URL
  244.             form(action="/save" method="post")
  245.                 div.modal.fade#modalAdd(tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true")
  246.                     div.modal-dialog(role="document")
  247.                         div.modal-content
  248.                             div.modal-header
  249.                                 h5.modal-title#exampleModalLabel Add New Message
  250.                                 button.close(type="button" data-dismiss="modal" aria-label="Close")
  251.                                     span(aria-hidden="true") &times;
  252.                             div.modal-body
  253.                                 div.form-group
  254.                                     textarea.form-control(name="msg" placeholder=" Your message " required)
  255.                                 div.form-group
  256.                                     input.form-control(type="text" name="url" placeholder=" Picture URL ")
  257.                             div.modal-footer
  258.                                 button.btn.btn-secondary(type="button" data-dismiss="modal") Cancel
  259.                                 button.btn.btn-success(type="submit") Save
  260.  
  261.             //modal form ADD2 - File upload
  262.             form(action="/upload" method="post" enctype="multipart/form-data")
  263.                 div.modal.fade#modalAdd2(tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true")
  264.                     div.modal-dialog(role="document")
  265.                         div.modal-content
  266.                             div.modal-header
  267.                                 h5.modal-title#exampleModalLabel Add New Message2
  268.                                 button.close(type="button" data-dismiss="modal" aria-label="Close")
  269.                                     span(aria-hidden="true") &times;
  270.                             div.modal-body
  271.                                 div.form-group
  272.                                     textarea.form-control(name="msg" placeholder=" Your message " required)
  273.                                 div.form-group
  274.                                     input.form-control(type="file" name="file")
  275.                             div.modal-footer
  276.                                 button.btn.btn-secondary(type="button" data-dismiss="modal") Cancel
  277.                                 button.btn.btn-success(type="submit") Save
  278.  
  279.             //modal form DELETE
  280.             form#add-row-form(action="/delete" method="post")
  281.                 div.modal.fade#DeleteModal(tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true")
  282.                     div.modal-dialog
  283.                         div.modal-content
  284.                             div.modal-header
  285.                                 h5.modal-title#modalLabel Delete Confirmation
  286.                                 button.close(type="button" data-dismiss="modal" aria-label="Close")
  287.                                     span(aria-hidden="true") &times;
  288.                             div.modal-body
  289.                                 strong Are you sure to delete this message?
  290.                             div.modal-footer
  291.                                 input.form-control.id(type="hidden" name="id" required)
  292.                                 button.btn.btn-secondary(type="button" data-dismiss="modal") Cancel
  293.                                 button.btn.btn-danger(type="submit") Delete
  294.  
  295.             //modal form EDIT/UPDATE
  296.             form(action="/update" method="post")
  297.                 div.modal.fade#EditModal(tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true")
  298.                     div.modal-dialog(role="document")
  299.                         div.modal-content
  300.                             div.modal-header
  301.                                 h5.modal-title#modalLabel Edit Message
  302.                                 button.close(type="button" data-dismiss="modal" aria-label="Close")
  303.                                     span(aria-hidden="true") &times;
  304.                             div.modal-body
  305.                                 div.form-group
  306.                                     textarea.form-control.msg(name="msg" placeholder=" Your message " required)
  307.                                 div.form-group
  308.                                     input.form-control.url(type="text" name="url" placeholder=" Picture URL ")
  309.                             div.modal-footer
  310.                                 input.form-control.id(type="hidden" name="id" required)
  311.                                 button.btn.btn-secondary(type="button" data-dismiss="modal") Cancel
  312.                                 button.btn.btn-info(type="submit") Update                                  
  313.  
  314.             script(src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js")
  315.             script(src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js")
  316.             script.
  317.                 $(document).ready(function(){
  318.                     //showing modal form DELETE
  319.                     $('#mytable').on('click','.delete',function(){
  320.                         $('#DeleteModal').modal('show');
  321.                         $('.id').val($(this).data('id'));
  322.                     });
  323.                    
  324.                     //showing modal form EDIT
  325.                     $('#mytable').on('click','.edit',function(){
  326.                         $('#EditModal').modal('show');
  327.                         $('.id').val($(this).data('id'));
  328.                         $('.msg').val($(this).data('msg'));
  329.                         $('.url').val($(this).data('url'));
  330.                     });                
  331.                 });
  332.             hr.mx-auto(width="80%")
  333. `;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement