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 7.4KB

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