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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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:
  87. var parsed = [];
  88. for (var i in results) {
  89. parsed.push (results[i].id);
  90. }
  91. //var parsed = results.map (x => x._id);
  92. res.send(parsed);
  93. } )
  94. .catch(err => {
  95. console.log (err);
  96. res .status(500) .json (err);
  97. });
  98. });
  99. app.get ("/api/msg/:id", function (req, res) {
  100. Message.findOne ({_id: req.params.id}) .exec (function (err, results){
  101. if (err) {
  102. console.log (err);
  103. res .status(404) .json (err);
  104. } else {
  105. console.log(JSON.stringify(results));
  106. res.json(results);
  107. }
  108. });
  109. });
  110. function makeid() {
  111. var text = "";
  112. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  113. for (var i = 0; i < 5; i++)
  114. text += possible.charAt(Math.floor(Math.random() * possible.length));
  115. return text;
  116. }
  117. app.post("/api/createMsg", function(req, res){
  118. //x = mongoose.Types.ObjectId();
  119. //y = x.toString();
  120. //var z = makeid();
  121. console.log("SUbject: "+JSON.stringify(req.body));
  122. var message = new Message( {subject: req.body.sub, message: req.body.mess, user: req.body.use, tag: req.body.ta } );
  123. message.save(function(err,result){
  124. if(err){
  125. return res .status(401) .send(err.message);
  126. }else{
  127. res.json({message: "Message created!!"});
  128. }
  129. });
  130. });
  131. // Other stuff is NOT authorized unless logged in
  132. //app.use (authorize.genCheckAuthorized ('user'));
  133. // Uploaded files
  134. //app.use ('/uploads', expr ess.static(__dirname + '/uploads'));
  135. // Other stuff is NOT authorized unless logged in
  136. //app.use (authorize.genCheckAuthorized ('user'));
  137. // Uploaded files
  138. //app.use ('/uploads', express.static(__dirname + '/uploads'));
  139. // Errors
  140. // No error so far? Then it's a 404!
  141. //app.use (function (req, res, next) { next (common.genError (404, req.url)); });
  142. //app.use (routes.errorHandler (true)); /* true: show stack traces */ // TODO: Error Handler
  143. /*
  144. * API
  145. */
  146. /*
  147. // API allowed for all
  148. api_routes.post ('/login', authorize.login); // /api/login
  149. // Validate all other API calls
  150. api_routes.use (authorize.genCheckAuthorized ('user'));
  151. api_routes.post ('/logout', authorize.logout);
  152. function addRoutes (r) {
  153. for (var e in r.routes) {
  154. var params = r.routes[e].params ? "/" + r.routes[e].params : "";
  155. console.log ("Adding routes for /" + e + params + ":" +
  156. (r.routes[e].get ? " get":" ") + (r.routes[e].post ? " post":" ") +
  157. (r.routes[e].put ? " put":" ") + (r.routes[e].delete ? " delete":" "));
  158. if (r.routes[e].get)
  159. api_routes.get ('/' + e + params, r.routes[e].get);
  160. if (r.routes[e].post)
  161. api_routes.post ('/' + e + params, r.routes[e].post);
  162. if (r.routes[e].put)
  163. api_routes.put ('/' + e + params, r.routes[e].put);
  164. if (r.routes[e].delete)
  165. api_routes.delete ('/' + e + params, r.routes[e].delete);
  166. }
  167. }
  168. addRoutes (dbs);
  169. addRoutes (files);
  170. */
  171. /*
  172. * Servers
  173. */
  174. http.createServer (app) .listen (http_port, function () {
  175. console.log ("Express http server listening on port " + http_port);
  176. });
  177. /*
  178. * SSL certificates
  179. *
  180. * Keys + Certificate in current dir (not servable!)
  181. * to create (self-signed) SSL certs:
  182. *
  183. * openssl genrsa -out privatekey.pem 1024
  184. * openssl req -new -key privatekey.pem -out certrequest.csr
  185. * openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
  186. * rm certrequest.csr
  187. */
  188. var options;
  189. try {
  190. try {
  191. // In case it's a real certificate: add CA chain cersts (TODO: use array if required)
  192. var ca = fs.readFileSync ('keys/ca_cert.pem');
  193. } catch (e) {
  194. ca = undefined;
  195. console.log ("Note: Can't read CA bundle: "+e);
  196. }
  197. options = {
  198. key: fs.readFileSync ('keys/omkey.pem'),
  199. cert: fs.readFileSync ('keys/certificate.pem'),
  200. ca: ca
  201. };
  202. https.createServer (options, app) .listen (https_port, function () {
  203. console.log ("Express https server listening on port " + https_port);
  204. });
  205. } catch (e) {
  206. console.log ("Note: Can't read SSL keys/certs: "+e+"\nDisabling https server");
  207. }
  208. /*
  209. * Uncaught Exceptions
  210. */
  211. process.on ("uncaughtException", function (err) {
  212. console.error ("*** Uncaught Exception:");
  213. console.error (err.stack);
  214. });