initial commit - backend basic skeleton

This commit is contained in:
Markus Schubert 2020-03-12 18:23:27 +01:00
commit 278415ce32
11 changed files with 2045 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/node_modules

67
app.js Normal file
View file

@ -0,0 +1,67 @@
const createError = require('http-errors');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const cookieSession = require('cookie-session');
const apiRouter = require('./app/routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieSession({
name: 'session',
secret: 'flkasjgoeeovneogsfafjasdjfslkjlgjs',
maxAge: 365 * 24 * 60 * 60 * 1000 // 1 year
}));
app.use('/api', apiRouter);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
function main() {
console.log('startup Quarantale');
const dbUrl = 'mongodb://localhost:27017';
const dbName = 'quarantale';
let client = new MongoClient(dbUrl, { useUnifiedTopology: true });
client.connect(function (err) {
assert.equal(null, err);
app.locals.database = client.db(dbName);
});
};
main();
module.exports = app;

30
app/Authenticator.js Normal file
View file

@ -0,0 +1,30 @@
const bcrypt = require('bcryptjs');
class Authenticator {
constructor(database) {
this.database = database;
};
getAuthenticatedUser(req, callback) {
if (req.session.userId) {
let collection = this.database.collection('users');
collection.findOne({ id: req.session.userId }, {}, function (dbErr, dbRes) {
if (dbErr === null) {
if (dbRes === null) {
callback(null);
} else {
callback(dbRes);
}
} else {
callback(null);
}
});
} else {
callback(null);
}
};
};
module.exports = Authenticator;

View file

@ -0,0 +1,107 @@
const uuidv4 = require('uuid/v4');
const bcrypt = require('bcryptjs');
class UserController {
constructor(database) {
this.database = database;
};
createUser(data, scb, ecb) {
console.log('UserController: create user: ' + data.username);
let collection = this.database.collection('users');
collection.findOne({ username: data.username }, {}, function (dbErr, dbRes) {
if (dbErr === null) {
if (dbRes === null) {
bcrypt.hash(data.password, 10, (err, hash) => {
if (err) {
ecb({
code: 'app error',
message: 'could not hash password'
});
}
let user = {
id: uuidv4(),
username: data.username,
passwordHash: hash,
role: 'user'
};
collection.insertOne(user, function (insertErr, insertRes) {
if (insertErr === null) {
let res = {
id: user.id,
username: user.username,
role: user.role
};
scb(res);
} else {
ecb({
code: 'database error. could not create user',
message: insertErr.message
});
}
});
});
} else {
ecb({
code: 'app error',
message: 'user already exists'
})
}
} else {
ecb({
code: 'database error',
message: dbErr.message
});
}
});
};
login(data, scb, ecb) {
console.log('UserController: create user: ' + data.username);
let collection = this.database.collection('users');
collection.findOne({ username: data.username }, {}, function (dbErr, user) {
if (dbErr === null) {
if (user === null) {
ecb({
code: 'app error',
message: 'user already exists'
});
} else {
bcrypt.compare(data.password, user.passwordHash, (cryptErr, cryptRes) => {
if (cryptErr) {
ecb({
code: 'app error',
message: 'could not hash password'
});
} else {
if (cryptRes === true) {
let res = {
id: user.id,
username: user.username,
role: user.role
};
scb(res);
} else {
ecb({ code: 'user error', message: 'authentication failed' });
}
}
});
}
} else {
ecb({
code: 'database error',
message: dbErr.message
});
}
});
};
getUserData(user, scb, ecb) {
scb({});
};
};
module.exports = UserController;

107
app/routes/api.js Normal file
View file

@ -0,0 +1,107 @@
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/UserController');
const Authenticator = require('../Authenticator');
router.get('/', function (req, res, next) {
let rnd = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
res.send('respond with some api calls - ' + rnd);
});
router.get('/user', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
let ctrl = new UserController(db);
let scb = function (data) {
res.json(data);
};
let ecb = function (err) {
res.status(400).send(err);
};
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
ctrl.getUserData(user, scb, ecb);
} else {
ecb({ code: 'app error', message: 'user not logged in.' });
}
});
});
router.post('/user', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
let ctrl = new UserController(db);
let scb = function (data) {
req.session.userId = data.id;
res.json(data);
};
let ecb = function (err) {
console.error(err.code + ': ' + err.message);
res.status(400).send(err);
};
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
ecb({ code: 'app error', message: 'user already logged in.' });
} else {
ctrl.createUser(req.body, scb, ecb);
}
});
});
router.post('/user/login', function (req, res, next) {
app = req.app;
db = app.locals.database;
let authenticator = new Authenticator(db);
let ctrl = new UserController(db);
let scb = function (data) {
req.session.userId = data.id;
res.json(data);
};
let ecb = function (err) {
console.error(err.code + ': ' + err.message);
res.status(400).send(err);
};
authenticator.getAuthenticatedUser(req, function (user) {
if (user) {
ecb({ code: 'app error', message: 'user already logged in.' });
} else {
ctrl.login(req.body, scb, ecb);
}
});
});
router.get('/user/logout', function (req, res, next) {
req.session = null;
res.end();
// app = req.app;
// db = app.locals.database;
// let authenticator = new Authenticator(db);
// authenticator.getAuthenticatedUser(req, function (user) {
// if (user) {
// req.session = null;
// res.json({});
// }
// });
});
module.exports = router;

90
bin/www Executable file
View file

@ -0,0 +1,90 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('nodeproto:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

25
package.json Normal file
View file

@ -0,0 +1,25 @@
{
"name": "nodeproto",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "PORT=9051 node ./bin/www",
"dev": "PORT=9051 nodemon ./bin/www"
},
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cookie-parser": "~1.4.4",
"cookie-session": "^1.4.0",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongodb": "^3.5.5",
"morgan": "~1.9.1",
"uuid": "^7.0.2"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}

View file

@ -0,0 +1,8 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}

9
routes/index.js Normal file
View file

@ -0,0 +1,9 @@
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

9
routes/users.js Normal file
View file

@ -0,0 +1,9 @@
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;

1592
yarn.lock Normal file

File diff suppressed because it is too large Load diff