pruned security vulnerabilities and added mail route

This commit is contained in:
Robert Jeutter 2020-03-31 14:57:20 +02:00
parent 492b4ceee5
commit dcb81052fa
15 changed files with 1182 additions and 240 deletions

View File

@ -1,12 +0,0 @@
{
"development": {
"env": "development",
"IP": "localhost",
"PORT": "8080"
// add all environment variables for your development server
},
"production": {
"env": "production",
// add all environment variables for your production server
}
}

3
.vs/ProjectSettings.json Normal file
View File

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

BIN
.vs/slnx.sqlite Normal file

Binary file not shown.

49
app.js
View File

@ -2,64 +2,61 @@
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
path = require('path'),
session = require('express-session'),
flash = require('connect-flash'),
favicon = require('serve-favicon'),
methodOverride= require('method-override'),
morgan = require('morgan');
//link your route files here
/*## link your route files here ##*/
const indexRoute = require('./routes/index'),
apiRoute = require('./routes/api');
//Now your app configuration
/*## Now your app configuration ##*/
if (app.get('env') === 'development'){
app.use(morgan('dev')); // log every request to the console for development
}
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname,'public','favicon.png')));
app.use(cookieParser('ChooseAStringForYourCookies'));
app.use(express.static(path.join(__dirname, 'public'))); // folder for public serving (images, files, scripts)
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var sess = {
secret: "ChooseASessionString",
secret: "ChooseSessionString", //change this to your custom string
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 } //how long should cookies been saved
};
if (app.get('env') === 'production') {
if (app.get('env') === 'production') { //secure sessions for production
app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}
app.use(session(sess));
app.use(session(sess)); //init sessions with above configuration
app.set('views', __dirname + '/views');
app.set("view engine", "pug");
app.set('view options', {
layout: false
app.set('views', __dirname + '/views'); //folder with view pages
app.set("view engine", "pug"); //set view engine to pug
app.set('view options', { //set custom view options
layout: false //set layout to false to use more than one and use pug
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(flash());
app.use(methodOverride("_method")); //use ?_YourMethod for your method changes
app.use(flash()); //to use connect-flash in your environment
app.use(methodOverride("_method")); //override with POST having ?_method=CUSTOM
/*## repeated actions for each website call ##*/
app.use(function(req, res, next){
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
res.locals.currentUser = req.user;
res.locals.success = req.flash('success'); //save your flash-success-messages locally
res.locals.error = req.flash('error'); //save your flash-error-messages locally
res.locals.currentUser = req.user; //save your current user locally for quick l
next();
});
//Routes
app.use("/", indexRoute);
/*## Routes ##*/
// note that NodeJS will choose the first option available that matches the pattern
app.use("/api", apiRoute);
app.get('*', (req,res)=>{ res.redirect("/"); });
app.use("/", indexRoute);
app.get('*', (req,res)=>{ res.redirect("/"); }); //fallback: redirect all website calls with no matching route to homesite (or 404 page)
/*## PORT ##*/
app.listen(process.env.PORT, process.env.IP, function(){
/*## init server ##*/
app.listen(process.env.PORT, process.env.IP, function(){ //start your server
console.log("Server is listening at " + process.env.IP + ":" + process.env.PORT + " with Environment: " + process.env.env);
});

12
config/.env-cmdrc.json Normal file
View File

@ -0,0 +1,12 @@
{
"development": {
"desc": "all environment variables for your development server",
"env": "development",
"IP": "localhost",
"PORT": 8080
},
"production": {
"desc": "all environment variables for your production server",
"env": "production"
}
}

168
package-lock.json generated
View File

@ -1,6 +1,6 @@
{
"name": "nodejs-boilerplate",
"version": "1.0.0",
"version": "1.0.1",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@ -115,11 +115,6 @@
"picomatch": "^2.0.4"
}
},
"append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY="
},
"array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
@ -255,43 +250,6 @@
"fill-range": "^7.0.1"
}
},
"buffer-from": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
"integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A=="
},
"busboy": {
"version": "0.2.14",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz",
"integrity": "sha1-bCpiLvz0fFe7vh4qnDetNseSVFM=",
"requires": {
"dicer": "0.2.5",
"readable-stream": "1.1.x"
},
"dependencies": {
"isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="
},
"readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
"integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "0.0.1",
"string_decoder": "~0.10.x"
}
},
"string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ="
}
}
},
"bytes": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
@ -400,17 +358,6 @@
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
},
"concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"requires": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"configstore": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz",
@ -533,38 +480,6 @@
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"dicer": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz",
"integrity": "sha1-WZbAhrszIYyBLAkL3cCc0S+stw8=",
"requires": {
"readable-stream": "1.1.x",
"streamsearch": "0.1.2"
},
"dependencies": {
"isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="
},
"readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
"integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "0.0.1",
"string_decoder": "~0.10.x"
}
},
"string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ="
}
}
},
"doctypes": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/doctypes/-/doctypes-1.1.0.tgz",
@ -1137,19 +1052,6 @@
"brace-expansion": "^1.1.7"
}
},
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
},
"mkdirp": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"requires": {
"minimist": "0.0.8"
}
},
"morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
@ -1174,21 +1076,6 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"multer": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.2.tgz",
"integrity": "sha512-xY8pX7V+ybyUpbYMxtjM9KAiD9ixtg5/JkeKUTD6xilfDv0vzzOFcCp4Ljb1UU3tSOM3VTZtKo63OmzOrGi3Cg==",
"requires": {
"append-field": "^1.0.0",
"busboy": "^0.2.11",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.1",
"object-assign": "^4.1.1",
"on-finished": "^2.3.0",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
}
},
"mysql": {
"version": "2.18.1",
"resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
@ -1535,20 +1422,6 @@
}
}
},
"readable-stream": {
"version": "2.3.6",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz",
"integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"readdirp": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz",
@ -1650,30 +1523,6 @@
}
}
},
"serve-favicon": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/serve-favicon/-/serve-favicon-2.5.0.tgz",
"integrity": "sha1-k10kDN/g9YBTB/3+ln2IlCosvPA=",
"requires": {
"etag": "~1.8.1",
"fresh": "0.5.2",
"ms": "2.1.1",
"parseurl": "~1.3.2",
"safe-buffer": "5.1.1"
},
"dependencies": {
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
},
"safe-buffer": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz",
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg=="
}
}
},
"serve-static": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
@ -1723,11 +1572,6 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
"streamsearch": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
"integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo="
},
"string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
@ -1817,11 +1661,6 @@
"mime-types": "~2.1.24"
}
},
"typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c="
},
"uglify-js": {
"version": "2.8.29",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz",
@ -2003,11 +1842,6 @@
"resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz",
"integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ="
},
"xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="
},
"yallist": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",

View File

@ -1,6 +1,6 @@
{
"name": "nodejs-boilerplate",
"version": "1.0.0",
"version": "1.0.1",
"description": "NodeJS boilerplate for express apps",
"main": "app.js",
"dependencies": {
@ -12,23 +12,18 @@
"express-session": "^1.17.0",
"method-override": "^3.0.0",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"mysql": "^2.18.1",
"nodemailer": "^6.4.6",
"nodemon": "^2.0.2",
"pug": "^2.0.4",
"serve-favicon": "^2.5.0"
"pug": "^2.0.4"
},
"devDependencies": {},
"scripts": {
"initPackage": "sh ./config/init.sh",
"createDB": "sh ./config/initDB.sh",
"startServer": "env-cmd -e development nodemon app.js",
"startDevServer": "env-cmd -e development -r ./config/.env-cmdrc.json nodemon app.js",
"startDevDB": "sudo /etc/init.d/mysql start",
"stopDevDB": "sudo /etc/init.d/mysql stop",
"dev": "npm run startDevDB && npm run startDevServer",
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1",
"testDB": "node ./config/db-test.js"
},
"repository": {
@ -41,7 +36,7 @@
"boilerplate"
],
"author": "Robert Jeutter",
"license": "SEE LICENSE IN LICENSE",
"license": "GNU GENERAL PUBLIC LICENSE",
"bugs": {
"url": "https://github.com/wieerwill/nodejs-boilerplate/issues"
},

View File

@ -1,3 +1,14 @@
body{
background-color: blue;
background-color: #94efef;
color: #000000;
text-align: center;
margin: 0 20% 0 20%;
padding: 10%;
}
form {
border: 3px solid #00ff21;
}
.input{
margin: 15px;
}

View File

@ -1,25 +1,48 @@
# NodeJS Boilerplate for Express Apps
This repository show you a simple but powerful way to start up your NodeJS Projects with Express.
## Get started
1. Clone/Fork this repository to your computer
2. install all requirements
1. node
2. mysql
2. set the config files
1. change "mail.js" credentials
2. change "database.js" credentials
3. start your development server with "npm run dev"
4. feel free to do what you want to do
## Routing
| URL | Method | Desc |
| --- | --- | --- |
| / | GET | Index Site |
| / | POST | nothing yet, work on it |
| / | DELETE | nothing yet, work on it |
| /mail | GET | view Mail form |
| /mail | SEND | send mail via nodemailer |
| /api | GET | Your API starts here |
## Requirements
-
#### npm Packages
- express
- ejs
- [nodemailer](https://www.npmjs.com/package/advanced-sitemap-generator)
- mysql
- body-parser
-
## npm Packages
Name | Version | Description
--- | --- | ---
[body-parser](https://www.npmjs.com/package/body-parser) | ^1.19.0 | Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
[connect-flash](https://www.npmjs.com/package/connect-flash) | ^0.1.1 | The flash is a special area of the session used for storing messages
[cookie-parser](https://www.npmjs.com/package/cookie-parser) | ^1.4.5 | Parse Cookie header and populate req.cookies with an object keyed by the cookie names
[env-cmd](https://www.npmjs.com/package/env-cmd) | ^10.1.0 | A simple node program for executing commands using an environment from an env file
[express](https://www.npmjs.com/package/express) | ^4.17.1 | Fast, unopinionated, minimalist web framework for node
[express-session](https://www.npmjs.com/package/express-session) | ^1.17.0 | Create a session middleware
[method-override](https://www.npmjs.com/package/method-override) | ^3.0.0 | Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it
[morgan](https://www.npmjs.com/package/morgan) | ^1.10.0 | HTTP request logger middleware for node.js
[mysql](https://www.npmjs.com/package/mysql) | ^2.18.1 | This is a node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.
[nodemailer](https://www.npmjs.com/package/nodemailer) | ^6.4.6 | Send e-mails from Node.js easy as cake!
[nodemon](https://www.npmjs.com/package/nodemon) | ^2.0.2 | nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
[pug](https://www.npmjs.com/package/pug) | ^2.0.4 | Pug is a high performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers
## Folder Overview
- config: all your apps configuration files for databases, connections and other
- .env-cmdrc.json: all environment variables for your servers
- database.js: your database connections and table overview
- db-test.js: test your database connection with this js
- mail.js: your mail connection
@ -38,7 +61,6 @@
- index: all files for index routes
- index.pug: the index routes view
- layout.pug: make it easy with a standarized layout for all your files
- .env-cmdrc.json: all environment variables for your servers
- app.js: entry file to start everything up
- gitignore: ignore some files in your git repository that don't matter
- package.json: overview and scripts for your packages

View File

@ -1,24 +1,64 @@
const express = require('express'),
/*## Get all necassary packages for this route ##*/
const express = require('express'),
router = express(),
mysql = require('mysql'),
bodyParser= require('body-parser'),
nodemailer = require('nodemailer'),
session = require('express-session'),
flash = require('connect-flash'),
cookieParser = require('cookie-parser'),
dbconfig = require('../config/database'),
mailconfig = require('../config/mail'),
middlewear = require('./middlewear'),
con = mysql.createConnection(dbconfig.connection);
mailconfig = require('../config/mail');
/*## SETUP nodemailer ''*/
var transporter = nodemailer.createTransport({
host: mailconfig.connection.host,
port: mailconfig.connection.port,
secure: mailconfig.connection.secure,
auth: {
user: mailconfig.connection.auth.user,
pass: mailconfig.connection.auth.pass
},
});
// verify mail connection configuration
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
/*## Start with routing ##*/
// Index
router.route("/")
.get((req, res)=> { // you got a GET request
res.render('index/index'); // get your index view file
router.route("/")//all routes from url "/"
.get((req, res) => { // you got a GET request to "/"
res.render('index/index'); // get your index view file
})
.post((req, res) => {
.post((req, res) => { //you got a POST request to "/"
//do something with a POST request
})
.delete((req, res) => { //you got a POST request to '/?method="DELETE"' but is overritten with DELETE request
//delete something
});
// MAIL
router.route("/mail")
.get((req, res) => { //GET request to "/mail"
//do something
res.render('index/mail');
})
.post((req, res) => { //you got a POST request to "/mail"
let mailOptions = {
from: req.body.email,
to: mailconfig.connection.auth.user,
subject: "Mail from NodeJS boilerplate",
text: req.body.message
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
req.flash('error', "Mail error. Please try again");
} else {
req.flash('success', "Thanks for your Mail");
}
});
res.redirect("/");
});
module.exports = router;

View File

@ -3,3 +3,5 @@ extends ../layout
block body
div
p Aspernatur laboriosam dolor praesentium soluta. Veniam soluta rerum fugit non vel est et fuga. Molestias a rerum nisi. Commodi explicabo est soluta quia doloribus deserunt nesciunt et. Consequatur necessitatibus deleniti eius ipsa voluptates tenetur. Molestiae ratione animi aut harum ex. Assumenda ad aperiam consequatur. Non exercitationem vel molestiae ut quas alias et suscipit. Aut nihil dolorum quo ipsa perspiciatis labore modi. Recusandae facere rerum aut totam. Quis ut dolorem sit corporis voluptate amet. Earum quo mollitia voluptas vitae est quo harum. Temporibus dolorem nam eum. Iure tempore rerum omnis. Eius quasi qui nostrum. Sequi dolorem labore ipsam et ut et quo. Explicabo aut praesentium voluptatem enim. Voluptatem sed cupiditate ea. Autem architecto maxime molestiae distinctio. Perferendis omnis aut dolorem.
a(href="/mail") to mail form

17
views/index/mail.pug Normal file
View File

@ -0,0 +1,17 @@
extends ../layout
block body
form(action="/mail" method="POST")
.input
label(for="email") Your Email
input(type="email" id="email" name="email" placeholder="example@web.com" required)
.input
label(for="message") Your message
textarea(name="message" id="message")
.input
input(type="submit" id="submit" value="send mail")
a(href="/") go back

View File

@ -18,8 +18,8 @@ html(lang='de')
block body
footer
small Get me on
a(href="") Github
h3 Get me on
a(href="https://github.com/wieerwill/nodejs-boilerplate") Github
script(src='js/index.js')