Added linting

Added the linter ESLint, added a custom set of rules and fixed linting issues
This commit is contained in:
RedDuckss 2018-10-11 04:09:13 -04:00
parent c67f9cce91
commit 26058d8fa9
11 changed files with 1344 additions and 407 deletions

38
.eslintrc.json Normal file
View File

@ -0,0 +1,38 @@
{
"env": {
"node": true,
"commonjs": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2017
},
"extends": "eslint:recommended",
"rules": {
"no-case-declarations": "off",
"no-empty": "off",
"no-console": "off",
"linebreak-style": "off",
"prefer-const": "error",
"no-var": "error",
"one-var": [
"error",
"never"
],
"indent": [
"error",
"tab",
{
"SwitchCase": 1
}
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
}

View File

@ -1,3 +1,5 @@
/* eslint-env browser */
/*
index.js -
@ -6,24 +8,21 @@ the main javascript file
*/
// set some variables
var bg = document.getElementById("hp-bg"),
index = 0,
imageList = [ "/assets/images/bg1.gif", "/assets/images/bg2.gif" ]
const bg = document.getElementById('hp-bg');
let index = 0;
const imageList = [ '/assets/images/bg1.gif', '/assets/images/bg2.gif' ];
// set the first image
bg.src = imageList[index]
index++
bg.src = imageList[index];
index++;
setInterval(() => {
if (index === imageList.length) {
index = 0
}
if (index === imageList.length) {
index = 0;
}
bg.src = imageList[index]
index++
}, 5000)
bg.src = imageList[index];
index++;
}, 5000);

View File

@ -6,58 +6,59 @@ blog post helper functionality
*/
//import filesystem
const fs = require("fs");
const fs = require('fs');
//import author list
const authors = require("../config.json").blog.authors;
const authors = require('../config.json').blog.authors;
//import markdown converter
const showdown = require('showdown'),
converter = new showdown.Converter({metadata: true});
const showdown = require('showdown');
const converter = new showdown.Converter({metadata: true});
function getAuthorByID(authorId) {
return authors[authorId];
return authors[authorId];
}
function getBlogPostAsMarkdown(postId) {
try {
return fs.readFileSync("posts/" + postId + ".md", {encoding: "utf8"});
} catch(exception) {
return null;
}
try {
return fs.readFileSync(`posts/${postId}.md`);
} catch(exception) {
return null;
}
}
function getBlogPostAsHtml(postId) {
const markdown = getBlogPostAsMarkdown(postId);
if (!markdown) return;
return converter.makeHtml(markdown);
const markdown = getBlogPostAsMarkdown(postId);
if (!markdown) return;
return converter.makeHtml(markdown);
}
function getBlogPostExpressReady(postId) {
const markdown = getBlogPostAsMarkdown(postId);
if (!markdown) return;
const html = converter.makeHtml(markdown);
const metadata = converter.getMetadata();
const hbsObject = {
content: html,
date: metadata.releaseDate,
category: metadata.category,
author: getAuthorByID(metadata.authorId)
};
const markdown = getBlogPostAsMarkdown(postId);
if (!markdown) return;
const html = converter.makeHtml(markdown);
const metadata = converter.getMetadata();
const hbsObject = {
content: html,
date: metadata.releaseDate,
category: metadata.category,
author: getAuthorByID(metadata.authorId)
};
return hbsObject;
return hbsObject;
}
function writeMarkdownToFile(text) {
fs.writeFileSync("posts/" + fs.readdirSync("posts").length + ".md", text);
const length = fs.readdirSync('posts').length;
fs.writeFileSync(`posts/${length}.md`, text);
}
// export the router
module.exports = {
getBlogPostAsHtml,
getBlogPostAsMarkdown,
getBlogPostExpressReady,
getAuthorByID,
writeMarkdownToFile
getBlogPostAsHtml,
getBlogPostAsMarkdown,
getBlogPostExpressReady,
getAuthorByID,
writeMarkdownToFile
};

View File

@ -6,49 +6,49 @@ common page functionality.
*/
function sendDefault404(req, res) {
res.status(404).send('404');
res.status(404).send('404');
}
function sendApi404(req, res) {
res.status(404).json({
error: {
code: 404,
message: "Endpoint not in use"
}
});
res.status(404).json({
error: {
code: 404,
message: 'Endpoint not in use'
}
});
}
function sendApiAuthError(req, res) {
res.status(401).json({
error: {
code: 401,
message: "Not authenticated"
}
});
res.status(401).json({
error: {
code: 401,
message: 'Not authenticated'
}
});
}
function sendApiGenericError(req, res) {
res.status(400).json({
error: {
code: 400,
message: "Bad request"
}
});
res.status(400).json({
error: {
code: 400,
message: 'Bad request'
}
});
}
function sendApiError(res, code, message) {
res.status(code).json({
error: {
code,
message
}
});
res.status(code).json({
error: {
code,
message
}
});
}
module.exports = {
sendDefault404,
sendApi404,
sendApiGenericError,
sendApiError,
sendApiAuthError
sendDefault404,
sendApi404,
sendApiGenericError,
sendApiError,
sendApiAuthError
};

View File

@ -1,11 +1,11 @@
const common = require("../helpers/common");
const common = require('../helpers/common');
function adminUserAuthenticationMiddleware(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
if (req.isAuthenticated()) {
return next();
}
common.sendApiAuthError(req, res);
common.sendApiAuthError(req, res);
}
module.exports = adminUserAuthenticationMiddleware;

View File

@ -5,56 +5,56 @@ file containing the model file for admin user
*/
const mongoose = require("mongoose"),
uniqueValidator = require("mongoose-unique-validator"),
bcrypt = require("bcrypt");
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcrypt');
const adminUserSchema = new mongoose.Schema({
username: {
type: String,
required: [true, "Username is required."],
minlength: [1, "Username must be at-least 1 character."],
maxlength: [42, "Username cannot be more than 42 characters long."],
unique: true,
trim: true,
},
password: {
type: String,
required: [true, "Password is required."],
minlength: [7, "Password must be at-least 7 characters."],
maxlength: [256, "Password cannot be more than 256 characters long."],
trim: true,
}
username: {
type: String,
required: [true, 'Username is required.'],
minlength: [1, 'Username must be at-least 1 character.'],
maxlength: [42, 'Username cannot be more than 42 characters long.'],
unique: true,
trim: true,
},
password: {
type: String,
required: [true, 'Password is required.'],
minlength: [7, 'Password must be at-least 7 characters.'],
maxlength: [256, 'Password cannot be more than 256 characters long.'],
trim: true,
}
});
adminUserSchema.plugin(uniqueValidator, {message: "{PATH} already in use."});
adminUserSchema.plugin(uniqueValidator, {message: '{PATH} already in use.'});
adminUserSchema.pre("save", function(next) {
// only hash the password if it has been modified (or is new)
if (!this.isModified("password")) {
return next();
}
adminUserSchema.pre('save', function(next) {
// only hash the password if it has been modified (or is new)
if (!this.isModified('password')) {
return next();
}
// Hash the password with 10 rounds.
bcrypt.hash(this.get("password"), 10, (err, hash) => {
if (err) {
return next(err);
}
// Hash the password with 10 rounds.
bcrypt.hash(this.get('password'), 10, (err, hash) => {
if (err) {
return next(err);
}
this.set("password", hash);
next();
});
this.set('password', hash);
next();
});
});
adminUserSchema.statics.findByUsername = function(username) {
return this.model("adminUser").findOne({
username
});
return this.model('adminUser').findOne({
username
});
};
const adminUserModel = mongoose.model("adminUser", adminUserSchema);
const adminUserModel = mongoose.model('adminUser', adminUserSchema);
module.exports = {
adminUserModel,
adminUserSchema
adminUserModel,
adminUserSchema
};

1384
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,8 +4,9 @@
"description": "The official website for the Pretendo Network.",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
"start": "node server.js",
"lint": "./node_modules/.bin/eslint .",
"lint-fix": "./node_modules/.bin/eslint . --fix"
},
"author": "The Pretendo Network (@PretendoNetwork)",
"authors": [
@ -25,5 +26,8 @@
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"showdown": "^1.8.6"
},
"devDependencies": {
"eslint": "^5.6.1"
}
}

View File

@ -9,9 +9,9 @@ file for handling admin panel routes
const router = require('express').Router();
// import dependencies
const common = require('../helpers/common'),
adminUserMiddleware = require("../middleware/admin-authentication"),
adminUser = require("../models/admin-user");
const common = require('../helpers/common');
const adminUserMiddleware = require('../middleware/admin-authentication');
const adminUser = require('../models/admin-user');
// display admin panel
router.get('/admin', (req, res) => {
@ -54,7 +54,7 @@ router.post('/admin/register', (req, res) => {
router.post('/admin/api/v1/ping', (req, res) => {
res.json({
success: true,
messsage: "pong!"
messsage: 'pong!'
});
});

View File

@ -7,24 +7,23 @@ file for handling routes regarding blog posts.
// import express' router
const router = require('express').Router();
const blogHelper = require("../helpers/blog-helper.js");
const blogHelper = require('../helpers/blog-helper.js');
// display blog post
router.get('/news/:id', async (req, res) => {
if (isNaN(req.params.id)) {
res.statusCode = 404;
res.render('404');
return;
}
if (isNaN(req.params.id)) {
res.statusCode = 404;
res.render("404");
return;
}
const hbsObject = blogHelper.getBlogPostExpressReady(req.params.id);
const hbsObject = blogHelper.getBlogPostExpressReady(req.params.id);
if (!hbsObject) {
res.statusCode = 404;
res.render("404");
return;
}
if (!hbsObject) {
res.statusCode = 404;
res.render('404');
return;
}
res.render('post', hbsObject);
});

View File

@ -7,27 +7,27 @@ the file that contains the code to run the server
// module imports, and
// some important variable defs
const express = require("express"),
handlebars = require("express-handlebars"),
session = require("express-session"),
passport = require("passport"),
LocalStrategy = require("passport").Strategy,
bcrypt = require("bcrypt"),
mongoose = require("mongoose"),
bodyParser = require("body-parser");
config = require("./config.json"),
app = express(),
common = require('./helpers/common'),
adminUserModel = require("./models/admin-user").adminUserModel;
const express = require('express');
const handlebars = require('express-handlebars');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport').Strategy;
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const config = require('./config.json');
const app = express();
const common = require('./helpers/common');
const adminUserModel = require('./models/admin-user').adminUserModel;
// import the colors module
require("colors");
require('colors');
// locations for some files
const locations = {
home: require("./routes/home"),
posts: require("./routes/blog"),
admin: require("./routes/admin")
home: require('./routes/home'),
posts: require('./routes/blog'),
admin: require('./routes/admin')
};
// setup body parser
@ -36,18 +36,18 @@ app.use(bodyParser.urlencoded({ extended: false }));
// setup database
mongoose.connect(config.database.url);
const connection = mongoose.connection;
connection.on("error", console.error.bind(console, "connection error:"));
connection.on('error', console.error.bind(console, 'connection error:'));
// setup session
app.use(session({
secret: config.secrets.session,
/*cookie: { secure: true } // use when https is enabled*/
//cookie: { secure: true } // use when https is enabled
}));
// setup authentication
app.use(passport.initialize());
app.use(passport.session());
passport.use("adminUserStrategy", new LocalStrategy(
passport.use('adminUserStrategy', new LocalStrategy(
(username, password, done) => {
// find user in database
adminUserModel.findByUsername(username).then((user) => {
@ -76,20 +76,20 @@ passport.use("adminUserStrategy", new LocalStrategy(
));
// load the handlebars module
app.engine(".hbs", handlebars({
extname: ".hbs",
layoutsDir: "views",
partialsDir: "views/partials"
app.engine('.hbs', handlebars({
extname: '.hbs',
layoutsDir: 'views',
partialsDir: 'views/partials'
}));
// set express to use handlebars
// as the templating engine
app.set("view engine", ".hbs");
app.set('view engine', '.hbs');
// set some routes on the server
// assets folder serving
app.use("/assets", express.static("assets"));
app.use('/assets', express.static('assets'));
// website root
app.use('/', locations.home);
@ -106,5 +106,5 @@ app.use(common.sendDefault404);
// start the server
app.listen(config.http.port, () => {
console.log(`started the server on port: ${ new String(config.http.port).green }`);
console.log(`started the server on port: ${new String(config.http.port).green}`);
});