Browse Source

outsource db routes, schemata and logic into dbs.js

master
Erik Römmelt 5 years ago
parent
commit
82f8e4bbde

+ 0
- 15
database/message.model.js View File

const mongoose = require('mongoose');

//const Schema = mongoose.Schema,
//ObjectId = Schema.ObjectId;

const MessageSchema = mongoose.Schema({
subject: { type: String, required: true },
message: { type: String, required: true },
user: { type: String, required: true },
tag: [{type: String }],
//createtime: { type: Date, default: Date.now },
});
MessageSchema.index({tag:'text'});

module.exports = mongoose.model('Message', MessageSchema);

+ 0
- 8
database/tag.model.js View File

const mongoose = require('mongoose');


const TagSchema = mongoose.Schema({
name: { type: String, required: true }, //unique
});

module.exports = mongoose.model('Tag', TagSchema);

+ 0
- 21
database/user.model.js View File

const mongoose = require('mongoose');


const UserSchema = mongoose.Schema({
// _id: { type: String },
name: { type: String, required: true },
pwd: { type: String },
// hash: { type: String },
// salt: { type: String },
// type: { type: String },
roles: { type: [String], required: true },
tags: { type: [String] },
// deactivated: { type: Boolean },
// participating: { type: [String] },
// host: { type: Boolean },
bookmarks: { type: [String] },
});
//tags as index:
//UserSchema.index({tags:'text'});

module.exports = mongoose.model('User', UserSchema);

+ 0
- 3
mongodb.config.js.example View File

module.exports = {
url: 'mongodb://localhost:27017/mydb'
}

+ 48
- 2
public/index.html View File

<a class="logo-img" href="index.html"><img src="img/app_icon.png" width=45px height=45px></a> <a class="logo-img" href="index.html"><img src="img/app_icon.png" width=45px height=45px></a>
<form class="om-searchbar"> <form class="om-searchbar">
<b-field> <b-field>
<b-input placeholder="Suche..."
<b-input
type="search" type="search"
icon="magnify">
icon="magnify"
placeholder="Suche...">
</b-input> </b-input>
<!--<b-autocomplete
v-model="name"
:data="filteredTagArray"
type="search"
icon="magnify"
placeholder="Suche..."
@blur="evaluate">
</b-autocomplete>-->
</b-field> </b-field>
</form> </form>
</div> </div>
methods: { methods: {
} }
}); });
const search_data = [];
/*
export.default {
data: function () {
return {
selected: [],
taglist: data,
};
},
computed: {
filteredTagArray() {
this.taglist = data.filter((option) => {
return option
.toString()
.toLowerCase()
.indexOf(this.name.toLowerCase()) >= 0
})
},

},
methods: {
evaluate(text) {
this.taglist = data.filter((option) => {
return option
.toString()
.toLowerCase()
.indexOf(text.toLowerCase()) >= 0
})
},
},
mounted: function () {
if ($(this).bootstrapMaterialDesign)
$(this).bootstrapMaterialDesign();
},
};
*/

</script> </script>


<!-- CDN_Vue.js minified lib --> <!-- CDN_Vue.js minified lib -->

+ 17
- 16
public/routes/createMessage.js View File

<b-field label="Tags"> <b-field label="Tags">
<b-taginput <b-taginput
v-model="selected" v-model="selected"
:data=items
:data=taglist
autocomplete autocomplete
allow-new:false allow-new:false
icon="label" icon="label"
</b-field> </b-field>


<b-button @click="$router.go(-1)">ABBRECHEN</b-button> <b-button @click="$router.go(-1)">ABBRECHEN</b-button>
<b-button type="is-primary" @click="$router.push('/home')">SENDEN</b-button>
<b-button type="is-primary" @click="createMsg">SENDEN</b-button>






data: function () { data: function () {
return { return {
selected: [], selected: [],
items: data
taglist: data,
}; };
}, },
methods: { methods: {
createMsg: function () { createMsg: function () {
var subject = $("#subject").val();
var message = $("#message").val();
var tag = $("#tag").val();
var user = $("#user").val();
console.log("Message Created: " + tag + " " + message + " " + user);
var _subject = $("#subject").val();
var _message = $("#message").val();
var _tag = $("#tag").val();
var _user = $("#user").val();
//console.log("Message Created: " + _tag + " " + _message + " " + _user);
$.ajax({ $.ajax({
url: "api/createMsg",
url: "api/msg",
data: { data: {
sub: subject,
mess: message,
use: user,
ta: tag
subject: _subject,
message: _message,
user: _user,
tag: _tag
}, },
method: "POST" method: "POST"
}).done(have_result).fail(have_error); }).done(have_result).fail(have_error);


function have_result(res) { function have_result(res) {
console.log(res);
//console.log(res);
router.push('/home')
} }


function have_error(err) { function have_error(err) {
} }
}, },
getFilteredTags(text) { getFilteredTags(text) {
this.items = data.filter((option) => {
this.taglist = data.filter((option) => {
return option return option
.toString() .toString()
.toLowerCase() .toLowerCase()
.indexOf(text.toLowerCase()) >= 0 .indexOf(text.toLowerCase()) >= 0
}) })
},
},
}, },
mounted: function () { mounted: function () {
if ($(this).bootstrapMaterialDesign) if ($(this).bootstrapMaterialDesign)

+ 4
- 4
public/routes/home.js View File

}); });
},*/ },*/
list_messages: function () { list_messages: function () {
$.ajax({url: "api/ids", method: "GET"})
$.ajax({url: "api/msg/ids", method: "GET"})
.done(jd => { .done(jd => {
// NICHT SO wg. Vue: _messagelist = jd; // NICHT SO wg. Vue: _messagelist = jd;
_messagelist.splice(0, _messagelist.length); _messagelist.splice(0, _messagelist.length);
_messagelist.push.apply(_messagelist, jd); _messagelist.push.apply(_messagelist, jd);
console.log("jd: "+jd);
//console.log("jd: "+jd);
for (var e in jd) { for (var e in jd) {
if (!_messages[jd[e]]) { if (!_messages[jd[e]]) {
get_insert_message(jd[e]); get_insert_message(jd[e]);
} }
}*/ }*/
}).fail(function (e, f, g) { }).fail(function (e, f, g) {
console.log("err: " + e + f + g);
console.log("list_msg: err: " + e + f + g);
}); });
} }
}, },
}; };


function get_insert_message(id) { function get_insert_message(id) {
$.ajax({ url: "api/msg/"+id, method: "GET" }).done(function (msg) {
$.ajax({ url: "api/msg/id/"+id, method: "GET" }).done(function (msg) {
Vue.set(_messages, id, msg); Vue.set(_messages, id, msg);
}).fail(function (e, f, g) { }).fail(function (e, f, g) {
console.log("cannot load " + id + ".json: " + e + f + g); console.log("cannot load " + id + ".json: " + e + f + g);

+ 115
- 183
server.js View File

// Original file created by Prof.Dr. Matthias Hopf

/** /**
* Express based http & https server * Express based http & https server
* *
* Requires express >= 4 * Requires express >= 4
*/ */
var common = require ('./server/common'),
authorize = require ('./server/authorization');
var common = require('./server/common'),
authorize = require('./server/authorization'),
dbs = require('./server/dbs');
/* /*
dbs = require ('./server/dbs'), dbs = require ('./server/dbs'),
files = require ('./server/files'); files = require ('./server/files');
*/ */
const fs = common.fs, // file sync, read certificates
http = common.http, // http handler
https = require ('https'), // https handler
express = require ('express'), // node server framework
session = require ('express-session'), // session management (security)
morgan = require ('morgan'), // logger
//serveFavicon = require ('serve-favicon'),
bodyParser = require ('body-parser'), // post request bodyparser
MongoStore = require ('connect-mongo')(session), // use mongodb as session storage
Message = require('./database/message.model.js');
const fs = common.fs, // file sync, read certificates
http = common.http, // http handler
https = require('https'), // https handler
express = require('express'), // node server framework
session = require('express-session'), // session management (security)
morgan = require('morgan'), // logger
mong = common.mongoose, // mongoose
// serveFavicon = require('serve-favicon'), // provide favicon
bodyParser = require('body-parser'), // post request bodyparser
MongoStore = require('connect-mongo')(session); // use mongodb as session storage


var app = express(); var app = express();


/* /*
* Init * Init
*/ */
common .init ();
authorize.init (common);
//dbs .init (common);
common .init();
authorize .init(common);
dbs .init (common);
//files .init (common); //files .init (common);
mong.Promise = global.Promise;


/* /*
* Security * Security
* (Disable Header information: Powerd by Express) * (Disable Header information: Powerd by Express)
* -> Information disclosure * -> Information disclosure
*/ */
app.disable ('x-powered-by');

// Session Management
app.set('trust proxy', 1) // trust first proxy, neccessary for cookie secure: true flag
app.use (session({
secret: 'ahhgylhuvh', // caesar(3) 2 letter surname
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 30*24*3600*1000, // TODO: ttl for session as well (Store)
secure: true, // true for https only (since our app works only with https)
},
name: 'om.sid',
store: new MongoStore ({mongooseConnection: common.mongoose.connection, ttl: 30*24*3600}), // mongoose + connect-mongo
//store: new MemoryStore ({checkPeriod: 24*3600*1000}), // memorystore
}));
app.disable('x-powered-by');




/* /*
* Route Control * Route Control
*/ */
// Session Management
app.set('trust proxy', 1) // trust first proxy, neccessary for cookie secure: true flag
app.use(session({
secret: 'ahhgylhuvh', // caesar(3) 2 letter surname
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 30 * 24 * 3600 * 1000, // TODO: ttl for session as well (Store)
secure: true, // true for https only (since our app works only with https)
},
name: 'om.sid',
store: new MongoStore({
mongooseConnection: mong.connection,
ttl: 30 * 24 * 3600
}), // mongoose + connect-mongo
//store: new MemoryStore ({checkPeriod: 24*3600*1000}), // memorystore
}));


// Fastpaths
// TODO Favicon for Desktop
//app.use (serveFavicon (__dirname + '/public/favicon.ico')); //app.use (serveFavicon (__dirname + '/public/favicon.ico'));



// Minimal Logging // Minimal Logging
//app.use (morgan ('dev')); //app.use (morgan ('dev'));
// Advanced Logging // Advanced Logging
morgan.token ('user', function (req, res) { return (req.session && req.session.user) || '-'; });
morgan.token ('userColored', function (req, res) {
var color = 0;
if (req.session && req.session.roles)
color = req.session.roles.admin ? 31 // red
: req.session.roles.user ? 34 // blue
: 0; // no color
return '\x1b[' + color + 'm' + ((req.session && req.session.user) || '-') + '\x1b[0m';
morgan.token('user', function (req, res) {
return (req.session && req.session.user) || '-';
});
morgan.token('userColored', function (req, res) {
var color = 0;
if (req.session && req.session.roles)
color = req.session.roles.admin ? 31 // red
: req.session.roles.user ? 34 // blue
: 0; // no color
return '\x1b[' + color + 'm' + ((req.session && req.session.user) || '-') + '\x1b[0m';
}); });
morgan.token ('statusColored', function (req, res) {
var color = res.statusCode >= 500 ? 31 // red
: res.statusCode >= 400 ? 33 // yellow
: res.statusCode >= 300 ? 36 // cyan
: res.statusCode >= 200 ? 32 // green
: 0; // no color
return '\x1b[' + color + 'm' + (res.headersSent ? res.statusCode : '-') + '\x1b[0m';
morgan.token('statusColored', function (req, res) {
var color = res.statusCode >= 500 ? 31 // red
: res.statusCode >= 400 ? 33 // yellow
: res.statusCode >= 300 ? 36 // cyan
: res.statusCode >= 200 ? 32 // green
: 0; // no color
return '\x1b[' + color + 'm' + (res.headersSent ? res.statusCode : '-') + '\x1b[0m';
}); });
app.use (morgan (':date[iso] :statusColored :method :url :userColored :response-time ms :res[content-length]'));
app.use(morgan(':date[iso] :statusColored :method :url :userColored :response-time ms :res[content-length]'));


// BodyParser // BodyParser
// Returns middleware that only parses json bodies. // Returns middleware that only parses json bodies.
// (https://www.npmjs.com/package/body-parser#bodyparserjsonoptions) // (https://www.npmjs.com/package/body-parser#bodyparserjsonoptions)
app.use (bodyParser.json());
app.use(bodyParser.json());
// Returns middleware that only parses urlencoded bodies // Returns middleware that only parses urlencoded bodies
// with qs library (https://www.npmjs.com/package/qs#readme) // with qs library (https://www.npmjs.com/package/qs#readme)
app.use (bodyParser.urlencoded({extended: true}));
app.use(bodyParser.urlencoded({
extended: true
}));


// API // API
var api_routes = express.Router(); // express app-object routing var api_routes = express.Router(); // express app-object routing
app.use('/api', api_routes);


app.use ('/api', api_routes);

// Static Files
// Allow server access to 'public' folder
// Static Files - Allow access to 'public' folder
app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/public'));


// Other stuff is NOT authorized unless logged in // Other stuff is NOT authorized unless logged in
//app.use (authorize.genCheckAuthorized ('user')); //app.use (authorize.genCheckAuthorized ('user'));


// Uploaded files
//app.use ('/uploads', express.static(__dirname + '/uploads'));

// Configuring the database
//var dbConfig = require('./mongodb.config.js');

common.mongoose.Promise = global.Promise;

// Connecting to the database
// Local db: common.config.dbLocalConn
// Efi db: common.config.dbConn
common.mongoose.connect (common.config.dbLocalConn, {useNewUrlParser: true}) .then( () => {
console.log("Successfully connected to MongoDB.");
}).catch( err => {
console.log('Could not connect to MongoDB.');
process.exit();
});

// No error so far? Then it's a 404! // No error so far? Then it's a 404!
//app.use (function (req, res, next) { next (common.genError (404, req.url)); });
app.use(function (req, res, next) {
next(common.genError(404, req.url));
});
//app.use (routes.errorHandler (true)); /* true: show stack traces */ //app.use (routes.errorHandler (true)); /* true: show stack traces */



/* /*
* API * API
*/ */
/*
// API allowed for all // API allowed for all
api_routes.post ('/login', authorize.login); // /api/login
api_routes.post('/login', authorize.login);


// Validate all other API calls // 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);
}
//api_routes.use(authorize.genCheckAuthorized('user'));
api_routes.post('/logout', authorize.logout);

// Add API routes
function addRoutes(r) {
for (var e in r.routes) {
var route = '/' + e + (r.routes[e].params ? "/" + r.routes[e].params : "");
var log = "Adding routes for " + route + ":";
/*
var auth = r.routes[e].auth || r.auth;
if (auth) {
log += " [auth]";
api_routes.use (route, function (req, res, next) {
if (! auth(req))
return next (common.genError (403, "Unauthorized"));
next ();
});
}
*/
/*
var role = r.routes[e].role || r.role;
if (role) {
log += " [role:"+role+"]";
api_routes.use (route, authorize.genCheckAuthorized (role));
}
*/
const methods = ["get", "post", "put", "delete"];
for (var m in methods) {
if (r.routes[e][methods[m]]) {
log += " " + methods[m];
api_routes[methods[m]](route, r.routes[e][methods[m]]);
}
}
console.log(log);
}
} }
*/

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);
}
});
});

/*app.get ("/api/msg/search/:phrase", function (req, res) {
Message.find ({$text: {$search: req.params.phrase}) .then (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!!"});
}
});
});


/*
addRoutes (dbs);
addRoutes (admin);
addRoutes (files);
*/
addRoutes(dbs);


/* /*
* Servers * Servers
*/ */
http.createServer (app) .listen (common.config.httpPort, function () {
console.log ("Express http server listening on port " + common.config.httpPort);
http.createServer(app).listen(common.config.httpPort, function () {
console.log("Express http server listening on port " + common.config.httpPort);
}); });


/* /*
try { try {
try { try {
// In case it's a real certificate: add CA chain cersts (TODO: use array if required) // In case it's a real certificate: add CA chain cersts (TODO: use array if required)
var ca = fs.readFileSync ('keys/ca_cert.pem');
var ca = fs.readFileSync('keys/ca_cert.pem');
} catch (e) { } catch (e) {
ca = undefined; ca = undefined;
console.log ("Note: Can't read CA bundle: "+e);
console.log("Note: Can't read CA bundle: " + e);
} }
if (ca != undefined) { if (ca != undefined) {
options = { options = {
key: fs.readFileSync ('keys/omkey.pem'),
cert: fs.readFileSync ('keys/certificate.pem'),
key: fs.readFileSync('keys/omkey.pem'),
cert: fs.readFileSync('keys/certificate.pem'),
ca: ca ca: ca
};
https.createServer (options, app) .listen (common.config.httpsPort, function () {
console.log ("Express https server listening on port " + common.config.httpsPort);
};
https.createServer(options, app).listen(common.config.httpsPort, function () {
console.log("Express https server listening on port " + common.config.httpsPort);
}); });
} }
} catch (e) { } catch (e) {
console.log ("Note: Can't read SSL keys/certs: "+e+"\nDisabling https server");
console.log("Note: Can't read SSL keys/certs: " + e + "\nDisabling https server");
} }
} else { } else {
console.log("Note: https server disabled by config"); console.log("Note: https server disabled by config");
/* /*
* Uncaught Exceptions * Uncaught Exceptions
*/ */
process.on ("uncaughtException", function (err) {
console.error ("*** Uncaught Exception:");
console.error (err.stack);
process.on("uncaughtException", function (err) {
console.error("*** Uncaught Exception:");
console.error(err.stack);
}); });



+ 8
- 9
server/authorization.js View File

// Original file created by Prof.Dr. Matthias Hopf

/* /*
* Authorization * Authorization
*/ */

var common, User; var common, User;
const ldap = require ('./ldap_ohm');
//const crypto = require ("./crypto");
const ldap = require ('./ldap_ohm'),
crypto = require ("../server/crypto");


// deactivated is not used yet // deactivated is not used yet
const serverVisibleSession = { user: true, name: true, type: true, mail: true, roles: true, deactivated: true, host: true }; const serverVisibleSession = { user: true, name: true, type: true, mail: true, roles: true, deactivated: true, host: true };
return returnError(); return returnError();
return returnSession (); return returnSession ();
} }
// check local database
/*
// check local database, then ldap
User.findById (req.body.user) .exec (function (err, entry) { User.findById (req.body.user) .exec (function (err, entry) {
// If there is a local user AND it has a password associated, test against this, and only this // If there is a local user AND it has a password associated, test against this, and only this
/*
if (entry != null && entry.pwd) { if (entry != null && entry.pwd) {
if (crypto.checkLocalAuth (entry, req.body.pwd)) { if (crypto.checkLocalAuth (entry, req.body.pwd)) {
return fillSession (req, entry, common.arrayToHash(entry.roles), returnSession); return fillSession (req, entry, common.arrayToHash(entry.roles), returnSession);
} }
return returnError (); return returnError ();
} }
*/


// check ldap // check ldap
ldap.authorize (user.toLowerCase(), pwd, function (found) { ldap.authorize (user.toLowerCase(), pwd, function (found) {
// Otherwise create standard user entry // Otherwise create standard user entry
return fillSession (req, found, {user:true}, returnSession); return fillSession (req, found, {user:true}, returnSession);
}); });
});
});*/
}, },
logout: function (req, res, next) { logout: function (req, res, next) {
fillSession (req, undefined, undefined, function (err) { fillSession (req, undefined, undefined, function (err) {
init: function (_common) { init: function (_common) {
common = _common; common = _common;
ldap.init (_common); ldap.init (_common);
User = require('../database/user.model.js');;
//User = require('../database/user.model.js');;
}, },
}; };



+ 2
- 0
server/common.js View File

// Original file created by Prof.Dr. Matthias Hopf

/* /*
* Common functions and imports * Common functions and imports
*/ */

+ 31
- 0
server/crypto.js View File

// Original file created by Prof.Dr. Matthias Hopf

/*
* Crypto routines for Authorization
*/

const crypto = require ("crypto");

const defaultHash = "sha256";
const defaultSaltLen = 16; // More (e.g. 256) for extra paranoia

const mod = {
encodePwd: function (entry, pwd) {
return crypto.createHash (entry.hash) .update (entry.salt + ":" + pwd, 'utf8') .digest ('base64');
},
checkLocalAuth: function (entry, pwd) {
if (!entry || !entry._id || !entry.hash || !entry.salt || !entry.hash || !entry.pwd ||
!pwd || pwd === '')
return false;
return mod.encodePwd (entry, pwd) === entry.pwd;
},
fillLocalAuth: function (entry, pwd) {
if (!entry.hash)
entry.hash = defaultHash;
entry.salt = crypto.randomBytes (defaultSaltLen) .toString('base64');
entry.pwd = mod.encodePwd (entry, pwd);
},
}


module.exports = mod;

+ 222
- 0
server/dbs.js View File

/*
* Main database access functions
*/
var common,
model = {};

const dbs = {
/* Method API route
* <- to server
* -> to client
* Description
*/
routes: {
"msg/ids": {
/* GET /api/msg/ids [no args]
* -> Array of message schema object ids
* Get ALL known message ids
*/
get: function(req, res) {
model.Messages.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);
});
},
},
"msg/id": {
params: ":id",
/* GET /api/msg/id/[massage-id]
* -> Message schema
* Get a particular message
*/
get: function(req, res) {
model.Messages.findById(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);
}
});
},
},
"msg/search": {},
"msg": {
/* POST /api/msg
* <- Message schema
* -> Message schema
* Create a new message
*/
post: function(req, res) {
/*
if ( !(req.body.tags instanceof Array) ) {
return res.status(400).json({ error: "bad request" });
}*/
console.log("Subject: "+JSON.stringify(req.body));
model.Messages.create({
subject: req.body.subject,
message: req.body.message,
user: req.body.user,
tags: req.body.tag
}, function(err, result) {
if (err) {
return res.status(401).json(err.message);
} else {
res.json({message: "Message created!!"});
}
if (result == null) {
return res.status(500).json("Can not create message.")
}
});
},
/* PUT /api/msg
* <-
* ->
* Update a message
*/
//put: function(req, res) {},
},
"tag/ids": {},
"tag": {},
},
/* Initialize requirements
* - DB connection
* - DB schemata
*/
init: function (_common) {
common = _common;

/* DB Connection
* Local db: common.config.dbLocalConn
* TH db: common.config.dbConn
*/
common.mongoose.connect (common.config.dbLocalConn, {
useNewUrlParser: true
}).then(() => {
console.log("Database connected successfully.");
}).catch(err => {
console.log('Database connection error.');
process.exit();
});

/* DB Schemata
* Privat fields:
* - per model: _list: Elements that are included in list fetch
* - per entry: _comment: Comment for Admin UI - TODO: not working yet
*/
var messageSchema = common.mongoose.Schema({
subject: { type: String, required: true,
_comment: "" },
message: { type: String, required: true,
_comment: "" },
user: { type: String, required: true,
_comment: "" },
tags: { type: [String],
_comment: "" },
//createtime: { type: Date, default: Date.now },
});
messageSchema.index({ tag:'text' });
model.Messages = common.mongoose.model('messages', messageSchema);
model.Messages._list = [ "" ];

var tagSchema = common.mongoose.Schema({
name: { type: String, required: true,
_comment: "" }, //unique
});
model.Tags = common.mongoose.model('tags', messageSchema);
model.Tags._list = [ "" ];

var userSchema = common.mongoose.Schema({
//_id: { type: String },
name: { type: String, required: true,
_comment: "" },
pwd: { type: String,
_comment: "" },
//hash: { type: String },
//salt: { type: String },
//type: { type: String },
roles: { type: [String], required: true,
_comment: "" },
tags: { type: [String],
_comment: "" },
//deactivated: { type: Boolean },
//participating: { type: [String] },
//host: { type: Boolean },
bookmarks: { type: [String],
_comment: "" },
});
model.Users = common.mongoose.model('users', userSchema);
model.Users._list = [ "" ];
},
models: model,
};



/*
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);
}
});
});

/*app.get ("/api/msg/search/:phrase", function (req, res) {
Message.find ({$text: {$search: req.params.phrase}) .then (function (err, results){
if (err) {
console.log (err);
res .status(404) .json (err);
} else {
console.log(JSON.stringify(results));
res.json(results);
}
});
});
*/
/*
app.post("/api/createMsg", function(req, res){
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!!"});
}
});
});
*/
module.exports = dbs;

+ 2
- 0
server/ldap_ohm.js View File

// Original file created by Prof.Dr. Matthias Hopf

/* /*
* Valdiate ohm logins with ldap service * Valdiate ohm logins with ldap service
*/ */

Loading…
Cancel
Save