menuserver/server.js
2020-02-17 16:49:59 +00:00

78 lines
1.9 KiB
JavaScript

const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const path = require('path');
const helmet = require('helmet');
const cors = require('cors');
const db = require('./server/lib/loginmanager');
// create express app
const app = express();
require('dotenv').config();
const serverPort = process.env.PORT || 3000;
const sitePath = 'dist';
app.use(cors());
app.use(helmet());
app.use(session({
'secret': 'rBLH5#Q89Z4',
'resave': true,
'saveUninitialized': true
}));
app.get('/', function(request, response) {
if (request.session.loggedin !== true)
response.sendFile(path.join(`${__dirname }/server/static/login.html`));
else
response.redirect('/recipes.html');
});
app.use(express.static(path.join(__dirname, sitePath)));
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ 'extended': true }));
// parse requests of content-type - application/json
app.use(bodyParser.json());
app.post('/auth', function(request, response) {
const username = request.body.u;
const password = request.body.p;
if (username && password)
db.getOne(username, password)
.then((data) => {
if (!data)
response.send('Incorrect Username and/or Password!');
else {
request.session.loggedin = true;
request.session.username = username;
response.redirect('/recipes.html');
}
})
.catch((err) => {
console.log(err);
response.status(500).send({
'message': err.message || 'Some error occurred while querying the database.'
});
});
else {
response.send('Please enter Username and Password!');
response.end();
}
});
require('./server/routes/recipe.routes')(app);
require('./server/routes/view.routes')(app);
// listen for requests
app.listen(serverPort, () => {
console.log(`Server is listening on port ${serverPort}`);
});