Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.js 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /**
  2. * Express based http & https server
  3. *
  4. * Requires express >= 4
  5. */
  6. /*
  7. var common = require ('./server/common'),
  8. authorize = require ('./server/authorization'),
  9. dbs = require ('./server/dbs'),
  10. files = require ('./server/files');
  11. */
  12. const fs = require ('fs'),
  13. http = require ('http'),
  14. https = require ('https'),
  15. express = require ('express'),
  16. session = require ('express-session'), // session management
  17. morgan = require ('morgan'), // logger
  18. //serveFavicon = require ('serve-favicon'),
  19. bodyParser = require ('body-parser');
  20. //MongoStore = require ('connect-mongo')(session); // uss mongodb as session storage
  21. const Message = require('./message.model.js');
  22. var app = express();
  23. var http_port=8888;
  24. https_port=8889;
  25. /*
  26. * Init
  27. */
  28. /*ll
  29. common .init ();
  30. authorize.init (common);
  31. dbs .init (common);
  32. files .init (common);
  33. */
  34. // Security
  35. app.disable ('x-powered-by'); // TODO: Disable Header information: Powerd by Express -> Information disclosure
  36. /*
  37. * Route Control
  38. */
  39. // Logger
  40. app.use (morgan ('dev'));
  41. //app.use(express.logger ( { format: 'default', stream: output_stream } ));
  42. // Fastpaths
  43. //app.use (serveFavicon (__dirname + '/public/favicon.ico'));
  44. // Session Management
  45. app.use (session({
  46. secret: 'adluhohks',
  47. resave: false,
  48. saveUninitialized: false,
  49. cookie: {
  50. maxAge: 30*24*3600*1000, // TODO: ttl for session as well (Store)
  51. secure: false, // true for https only
  52. },
  53. name: 'om.sid',
  54. //store: new MongoStore ({mongooseConnection: dbs.mongoose.connection, ttl: 30*24*3600}), // mongoose + connect-mongo
  55. //store: new MemoryStore ({checkPeriod: 24*3600*1000}), // memorystore
  56. }));
  57. // Args
  58. app.use (bodyParser.json());
  59. app.use (bodyParser.urlencoded({extended: true}));
  60. // API
  61. //var api_routes = express.Router(); // express app-object routing
  62. //app.use ('/api', api_routes);
  63. app.use (function (req,res,done) {
  64. console.log (req.url);
  65. done();
  66. });
  67. //global.__basedir = __dirname;
  68. // Static Files
  69. app.use (express.static(__dirname + '/public')); // Allow server access to 'public' folder
  70. //app.use(express.static('resources'));
  71. // Configuring the database
  72. const dbConfig = require('./mongodb.config.js');
  73. const mongoose = require('mongoose');
  74. mongoose.Promise = global.Promise;
  75. // Connecting to the database
  76. mongoose.connect(dbConfig.url)
  77. .then(() => {
  78. console.log("Successfully connected to MongoDB.");
  79. }).catch(err => {
  80. console.log('Could not connect to MongoDB.');
  81. process.exit();
  82. });
  83. //require('./app/routes/message.route.js')(app);
  84. app.get ('/api/ids', function (req, res) {
  85. Message.find({},{_id: true}) .exec () .then(results => {
  86. /* selects id from message: var parsed = [];
  87. for (var i in results) {
  88. parsed.push (results[i]._id);
  89. } */
  90. var parsed = results.map (x => x._id);
  91. res.send(parsed);
  92. } )
  93. .catch(err => {
  94. console.log (err);
  95. res .status(500) .json (err);
  96. });
  97. });
  98. app.get ("/api/msg/:id", function (req, res) {
  99. Message.findOne ({_id: req.params.id}) .exec (function (err, results){
  100. if (err) {
  101. console.log (err);
  102. res .status(404) .json (err);
  103. } else {
  104. console.log(JSON.stringify(results));
  105. res.json(results);
  106. }
  107. });
  108. });
  109. app.post("/api/createMsg", function(req, res){
  110. var message = new Message(req.body);
  111. message.save(function(err,result){
  112. if(err)
  113. return res .status(401) .send(err.message);
  114. res.json({message: "Message created!!"});
  115. });
  116. });
  117. // Other stuff is NOT authorized unless logged in
  118. //app.use (authorize.genCheckAuthorized ('user'));
  119. // Uploaded files
  120. //app.use ('/uploads', expr ess.static(__dirname + '/uploads'));
  121. // Other stuff is NOT authorized unless logged in
  122. //app.use (authorize.genCheckAuthorized ('user'));
  123. // Uploaded files
  124. //app.use ('/uploads', express.static(__dirname + '/uploads'));
  125. // Errors
  126. // No error so far? Then it's a 404!
  127. //app.use (function (req, res, next) { next (common.genError (404, req.url)); });
  128. //app.use (routes.errorHandler (true)); /* true: show stack traces */ // TODO: Error Handler
  129. /*
  130. * API
  131. */
  132. /*
  133. // API allowed for all
  134. api_routes.post ('/login', authorize.login); // /api/login
  135. // Validate all other API calls
  136. api_routes.use (authorize.genCheckAuthorized ('user'));
  137. api_routes.post ('/logout', authorize.logout);
  138. function addRoutes (r) {
  139. for (var e in r.routes) {
  140. var params = r.routes[e].params ? "/" + r.routes[e].params : "";
  141. console.log ("Adding routes for /" + e + params + ":" +
  142. (r.routes[e].get ? " get":" ") + (r.routes[e].post ? " post":" ") +
  143. (r.routes[e].put ? " put":" ") + (r.routes[e].delete ? " delete":" "));
  144. if (r.routes[e].get)
  145. api_routes.get ('/' + e + params, r.routes[e].get);
  146. if (r.routes[e].post)
  147. api_routes.post ('/' + e + params, r.routes[e].post);
  148. if (r.routes[e].put)
  149. api_routes.put ('/' + e + params, r.routes[e].put);
  150. if (r.routes[e].delete)
  151. api_routes.delete ('/' + e + params, r.routes[e].delete);
  152. }
  153. }
  154. addRoutes (dbs);
  155. addRoutes (files);
  156. */
  157. /*
  158. * Servers
  159. */
  160. http.createServer (app) .listen (http_port, function () {
  161. console.log ("Express http server listening on port " + http_port);
  162. });
  163. /*
  164. * SSL certificates
  165. *
  166. * Keys + Certificate in current dir (not servable!)
  167. * to create (self-signed) SSL certs:
  168. *
  169. * openssl genrsa -out privatekey.pem 1024
  170. * openssl req -new -key privatekey.pem -out certrequest.csr
  171. * openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
  172. * rm certrequest.csr
  173. */
  174. var options;
  175. try {
  176. try {
  177. // In case it's a real certificate: add CA chain cersts (TODO: use array if required)
  178. var ca = fs.readFileSync ('keys/ca_cert.pem');
  179. } catch (e) {
  180. ca = undefined;
  181. console.log ("Note: Can't read CA bundle: "+e);
  182. }
  183. options = {
  184. key: fs.readFileSync ('keys/omkey.pem'),
  185. cert: fs.readFileSync ('keys/certificate.pem'),
  186. ca: ca
  187. };
  188. https.createServer (options, app) .listen (https_port, function () {
  189. console.log ("Express https server listening on port " + https_port);
  190. });
  191. } catch (e) {
  192. console.log ("Note: Can't read SSL keys/certs: "+e+"\nDisabling https server");
  193. }
  194. /*
  195. * Uncaught Exceptions
  196. */
  197. process.on ("uncaughtException", function (err) {
  198. console.error ("*** Uncaught Exception:");
  199. console.error (err.stack);
  200. });