Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Index Js

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

const express = require('express');

const multer = require('multer')


const path = require('path')
const mysql = require("mysql");
const bcrypt = require("bcrypt");
const session = require('express-session');
const app = express();
const pool = require("./dbPool.js");
const page = require("./controllers/page");
const menu = require("./controllers/menu");
const PageModel = require("./models/Page");
const MenuModel = require("./models/Menu");
const quotes = require('inspirational-quotes');

app.set("view engine", "ejs");


app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));

let saltRounds = 3

app.set('true proxy', 1);


app.use(session({
secret: 'top secret!',
resave: true,
saveUninitialized: true
}));

app.use(async function(req, res, next) {


res.locals.authenticated = req.session.authenticated || false;
res.locals.menu = await MenuModel.getMenu();
next();
});

//functions
async function executeSQL(sql, params) {
return new Promise(function(resolve, reject) {
pool.query(sql, params, function(err, rows, fields) {
if (err) throw err;
resolve(rows);
});
});
}//executeSQL

// lauis Navarro
//! Use of Multer
var storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/img/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})

// lauis Navarro
var upload = multer({
storage: storage
});

// routes
app.get('/', async (req, res) => {
let data = await PageModel.getRecentPages(req.path);
res.render('index', { "pages": data })
});

app.get('/admin/create', (req, res) => {


res.render('create')
});

// lauis Navarro
app.post('/admin/create', upload.fields([{ name: 'img', maxCount: 1 }, { name: 'authorImg', maxCount: 1 }]), async (req, res) => {

let title = req.body.title


let body = req.body.body
let authorInfo = req.body.authorInfo
let pageURL = req.body.pageURL
let gender = req.body.gender

if (!req.files) {

res.render('create', { 'error': 'No File upload' })


console.log("No file upload");

} else {

let img;
let authorImg;

Object.keys(req.files).forEach((k, i) => {
let file = req.files

if (file['img']) {
img = (file['img'][0].filename)
}

if (file['authorImg']) {
authorImg = file['authorImg'][0].filename
}
})

let sql = "INSERT INTO page_content(title, image_url, body, author_image_url, author_info, page_url, gender) VALUES (?, ?, ?, ?, ?, ?, ? )"

let params = [title, img, body, authorImg, authorInfo, pageURL, gender]

let row = await executeSQL(sql, params)

res.render('create', { "message": 'Successfully Inserted to Databases' })


}

})

// lauis Navarro
app.get('/signup', (req, res) => {
if (req.session.authenticated) {
return res.redirect('/admin')
}

res.render('signup')
})

// lauis Navarro
app.post('/signup', async (req, res) => {
let name = req.body.username;
let password = req.body.pwd;

let hashedPassword = await bcrypt.hash(password, saltRounds)

let sql = "INSERT INTO users(username, password) VALUES (? , ?)"

let params = [name, hashedPassword]

let row = await executeSQL(sql, params)

res.render('signup', { "message": "Successfully registered" })

})

app.get('/login', (req, res) => {


if (req.session.authenticated) {
return res.redirect('/admin')
}

res.render('login')
});

app.post('/login', async (req, res) => {


if (req.session.authenticated) {
return res.redirect('/admin')
}

let username = req.body.username;


let userPassword = req.body.pwd;

let sql = `SELECT *


FROM users
WHERE USERNAME = ?`;

let data = await executeSQL(sql, [username]);

let passwordHash = "";


if (data.length == 1) {
passwordHash = data[0].password;
}

const matchPassword = await bcrypt.compare(userPassword, passwordHash);

if (matchPassword) {
req.session.authenticated = true;
res.redirect("admin");
} else {
res.render("login", { "error": "Invalid credentials" });
}
});

app.get('/partials/quotes', (req, res) => {


let randomQuote = quotes.getQuote();
let quoteText = randomQuote.text;
let quoteAuthor = randomQuote.author;
res.render('quotes', { "quoteT": quoteText, "quoteA": quoteAuthor },)
});

app.get('/logout', isAuthenticated, (req, res) => {


req.session.authenticated = false;
req.session.destroy;
res.redirect('/login')
});

app.get('/admin', isAuthenticated, (req, res) => {


res.render('admin');
});

app.get('/admin/menu', isAuthenticated, async (req, res) => {

let sql = `SELECT *


FROM main_menu`;

let data = await executeSQL(sql);

let pageSql = `SELECT page_url, title, pid


FROM page_content`;
let pageData = await executeSQL(pageSql);

//res.render('admin', { "menu": data, "pages": pageData });


res.render('menu-edit', { "menu": data, "pages": pageData });
});

app.post('/admin/menu', isAuthenticated, (req, res) => {


// res.render('menu-edit');
res.render('admin');
});

app.get("/admin/addMenu", isAuthenticated, async function(req, res) {


let sql = `INSERT INTO main_menu (url_id, link_text, link_url) VALUES (?, ?, ?)`;
let pageSql = `SELECT pid, page_url, title
FROM page_content
WHERE pid = ${req.query.pid}`;

let pageData = await executeSQL(pageSql);

// let pagePid = pageData[0].pid;


// let pagP = pageData[0].page_url;
// let pagPid = pageData[0].title;
let params = [
pageData[0].pid,
pageData[0].title,
pageData[0].page_url
];

let data = await executeSQL(sql, params);

sql = `SELECT *
FROM main_menu`;
data = await executeSQL(sql);
pageSql = `SELECT page_url, title, pid
FROM page_content`;
pageData = await executeSQL(pageSql);
res.render("menu-edit", { "menu": data, "pages": pageData, "message": "Page Added to Menu!" });
});

app.get("/admin/removeMenu", isAuthenticated, async function(req, res) {


let sql = `DELETE FROM main_menu
WHERE url_id = ${req.query.pid}`;
let data = await executeSQL(sql);

sql = `SELECT *
FROM main_menu`;
data = await executeSQL(sql);
let pageSql = `SELECT page_url, title, pid
FROM page_content`;
let pageData = await executeSQL(pageSql);
res.render("menu-edit", { "menu": data, "pages": pageData, "message": "Page Deleted From Menu!" });

});

app.get('/admin/edit-menu-link', menu.renderEditMenuLink);
app.post('/admin/edit-menu-link', menu.editMenuLink, menu.renderEditMenuLink);
app.get('/admin/page-list', page.renderPageList);
app.get('/admin/edit-page', page.renderEditPage);
app.post('/admin/edit-page', upload.fields([{ name: 'image_url', maxCount: 1 }, { name: 'author_image_url', maxCount: 1 }]), page.editPage, page.renderEditPage);

app.get('/:dynamic', page.renderPage);

function isAuthenticated(req, res, next) {


if (req.session.authenticated) {
next();
}
else {
res.redirect("/login");
}
}

//start server
app.listen(3000, () => {
console.log("Expresss server running...")
})

You might also like