123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264 |
- /**
- * Express based http & https server
- *
- * Requires express >= 4
- */
-
- /*
- var common = require ('./server/common'),
- authorize = require ('./server/authorization'),
- dbs = require ('./server/dbs'),
- files = require ('./server/files');
- */
-
- const fs = require ('fs'),
- http = require ('http'),
- https = require ('https'),
- express = require ('express'),
- session = require ('express-session'), // session management
- morgan = require ('morgan'), // logger
- //serveFavicon = require ('serve-favicon'),
- bodyParser = require ('body-parser');
- //MongoStore = require ('connect-mongo')(session); // uss mongodb as session storage
- const Message = require('./message.model.js');
-
- var app = express();
-
- var http_port=8013;
- https_port=8889;
-
- /*
- * Init
- */
- /*ll
- common .init ();
- authorize.init (common);
- dbs .init (common);
- files .init (common);
- */
-
- // Security
- app.disable ('x-powered-by'); // TODO: Disable Header information: Powerd by Express -> Information disclosure
-
-
- /*
- * Route Control
- */
-
- // Logger
- app.use (morgan ('dev'));
- //app.use(express.logger ( { format: 'default', stream: output_stream } ));
-
- // Fastpaths
- //app.use (serveFavicon (__dirname + '/public/favicon.ico'));
-
- // Session Management
- app.use (session({
- secret: 'adluhohks',
- resave: false,
- saveUninitialized: false,
- cookie: {
- maxAge: 30*24*3600*1000, // TODO: ttl for session as well (Store)
- secure: false, // true for https only
- },
- name: 'om.sid',
- //store: new MongoStore ({mongooseConnection: dbs.mongoose.connection, ttl: 30*24*3600}), // mongoose + connect-mongo
- //store: new MemoryStore ({checkPeriod: 24*3600*1000}), // memorystore
- }));
-
- // Args
- app.use (bodyParser.json());
- app.use (bodyParser.urlencoded({extended: true}));
-
- // API
- //var api_routes = express.Router(); // express app-object routing
- //app.use ('/api', api_routes);
-
- app.use (function (req,res,done) {
- console.log (req.url);
- done();
- });
-
- //global.__basedir = __dirname;
-
- // Static Files
- app.use (express.static(__dirname + '/public')); // Allow server access to 'public' folder
-
- //app.use(express.static('resources'));
-
- // Configuring the database
- const dbConfig = require('./mongodb.config.js');
- const mongoose = require('mongoose');
-
- mongoose.Promise = global.Promise;
-
- // Connecting to the database
- mongoose.connect(dbConfig.url, {useNewUrlParser: true})
- .then(() => {
- console.log("Successfully connected to MongoDB.");
- }).catch(err => {
- console.log('Could not connect to MongoDB.');
- process.exit();
- });
-
- //require('./app/routes/message.route.js')(app);
-
- app.get ('/api/ids', function (req, res) {
- Message.find({},{id: true}) .exec () .then(results => {
- //selects id from message:
- var parsed = [];
- for (var i in results) {
- parsed.push (results[i].id);
- }
- //var parsed = results.map (x => x._id);
- res.send(parsed);
- } )
- .catch(err => {
- console.log (err);
- res .status(500) .json (err);
- });
- });
-
- app.get ("/api/msg/:id", function (req, res) {
- Message.findOne ({_id: req.params.id}) .exec (function (err, results){
- if (err) {
- console.log (err);
- res .status(404) .json (err);
- } else {
- console.log(JSON.stringify(results));
- res.json(results);
- }
- });
- });
-
- /*function makeid() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-
- for (var i = 0; i < 5; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
-
- return text;
- }*/
-
- app.post("/api/createMsg", function(req, res){
- //x = mongoose.Types.ObjectId();
- //y = x.toString();
- //var z = makeid();
- console.log("SUbject: "+JSON.stringify(req.body));
- var message = new Message( {subject: req.body.sub, message: req.body.mess, user: req.body.use, tag: req.body.ta } );
-
- message.save(function(err,result){
- if(err){
- return res .status(401) .send(err.message);
- }else{
- res.json({message: "Message created!!"});
- }
- });
- });
-
- // Other stuff is NOT authorized unless logged in
- //app.use (authorize.genCheckAuthorized ('user'));
-
- // Uploaded files
- //app.use ('/uploads', expr ess.static(__dirname + '/uploads'));
-
- // Other stuff is NOT authorized unless logged in
- //app.use (authorize.genCheckAuthorized ('user'));
-
- // Uploaded files
- //app.use ('/uploads', express.static(__dirname + '/uploads'));
-
- // Errors
- // No error so far? Then it's a 404!
- //app.use (function (req, res, next) { next (common.genError (404, req.url)); });
- //app.use (routes.errorHandler (true)); /* true: show stack traces */ // TODO: Error Handler
-
-
- /*
- * API
- */
- /*
- // API allowed for all
- api_routes.post ('/login', authorize.login); // /api/login
-
- // Validate all other API calls
- api_routes.use (authorize.genCheckAuthorized ('user'));
- api_routes.post ('/logout', authorize.logout);
-
- function addRoutes (r) {
- for (var e in r.routes) {
- var params = r.routes[e].params ? "/" + r.routes[e].params : "";
- console.log ("Adding routes for /" + e + params + ":" +
- (r.routes[e].get ? " get":" ") + (r.routes[e].post ? " post":" ") +
- (r.routes[e].put ? " put":" ") + (r.routes[e].delete ? " delete":" "));
- if (r.routes[e].get)
- api_routes.get ('/' + e + params, r.routes[e].get);
- if (r.routes[e].post)
- api_routes.post ('/' + e + params, r.routes[e].post);
- if (r.routes[e].put)
- api_routes.put ('/' + e + params, r.routes[e].put);
- if (r.routes[e].delete)
- api_routes.delete ('/' + e + params, r.routes[e].delete);
- }
- }
-
- addRoutes (dbs);
- addRoutes (files);
- */
-
- /*
- * Servers
- */
-
- http.createServer (app) .listen (http_port, function () {
- console.log ("Express http server listening on port " + http_port);
- });
-
- /*
- * SSL certificates
- *
- * Keys + Certificate in current dir (not servable!)
- * to create (self-signed) SSL certs:
- *
- * openssl genrsa -out privatekey.pem 1024
- * openssl req -new -key privatekey.pem -out certrequest.csr
- * openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
- * rm certrequest.csr
- */
-
- var options;
- try {
- try {
- // In case it's a real certificate: add CA chain cersts (TODO: use array if required)
- var ca = fs.readFileSync ('keys/ca_cert.pem');
- } catch (e) {
- ca = undefined;
- console.log ("Note: Can't read CA bundle: "+e);
- }
- if (ca != null) {
-
- options = {
- key: fs.readFileSync ('keys/omkey.pem'),
- cert: fs.readFileSync ('keys/certificate.pem'),
- ca: ca
- };
- https.createServer (options, app) .listen (https_port, function () {
- console.log ("Express https server listening on port " + https_port);
- });
- }
- } catch (e) {
- console.log ("Note: Can't read SSL keys/certs: "+e+"\nDisabling https server");
- }
-
-
- /*
- * Uncaught Exceptions
- */
-
- process.on ("uncaughtException", function (err) {
- console.error ("*** Uncaught Exception:");
- console.error (err.stack);
- });
-
|