Commit 070bed36 authored by katjaq's avatar katjaq
Browse files

Merge remote-tracking branch 'OpenNeuroLab/master'

parents 7a5ac1cb b6c4e14c
"use strict";
'use strict';
/*
Atlas Maker Server
Roberto Toro, 25 July 2014
Launch using > node atlasMakerServer.js
*/
var debug = 1;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mustacheExpress = require('mustache-express');
var crypto = require('crypto');
var request = require("request");
var url = require("url");
var async = require("async");
var mongo = require('mongodb');
var monk = require('monk');
var MONGO_DB;
var DOCKER_DB = process.env.DB_PORT;
var DOCKER_DEVELOP = process.env.DEVELOP;
if ( DOCKER_DB ) {
MONGO_DB = DOCKER_DB.replace( 'tcp', 'mongodb' ) + '/brainbox';
const debug = 1;
const fs = require('fs');
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mustacheExpress = require('mustache-express');
const crypto = require('crypto');
const request = require('request');
const url = require('url');
const async = require('async');
const mongo = require('mongodb');
const monk = require('monk');
let MONGO_DB;
const DOCKER_DB = process.env.DB_PORT;
const DOCKER_DEVELOP = process.env.DEVELOP;
if (DOCKER_DB) {
MONGO_DB = DOCKER_DB.replace('tcp', 'mongodb') + '/brainbox';
} else {
MONGO_DB = 'localhost:27017/brainbox'; //process.env.MONGODB;
MONGO_DB = 'localhost:27017/brainbox'; // Process.env.MONGODB;
}
var db = monk(MONGO_DB);
var fs = require('fs');
var expressValidator = require('express-validator');
const db = monk(MONGO_DB);
const expressValidator = require('express-validator');
var atlasMakerServer = require('./js/atlasMakerServer.js');
const atlasMakerServer = require('./js/atlasMakerServer.js');
// init web server
//var routes = require('./routes/index');
// Init web server
// var routes = require('./routes/index');
// var users = require('./routes/users');
/*jslint nomen: true*/
var dirname = __dirname; // local directory
/*jslint nomen: false*/
/* jslint nomen: true */
const dirname = __dirname; // Local directory
/* jslint nomen: false */
if ( DOCKER_DEVELOP == '1' ) {
var livereload = require('livereload');
if (DOCKER_DEVELOP == '1') {
const livereload = require('livereload');
// Create a livereload server
const hotServer = livereload.createServer({
// Reload on changes to these file extensions.
exts: [ 'json', 'mustache' ],
exts: ['json', 'mustache'],
// Print debug info
debug: true
debug: true
});
// Specify the folder to watch for file-changes.
hotServer.watch(__dirname);
console.log('Watching: ' + __dirname)
console.log('Watching: ' + __dirname);
}
var app = express();
const app = express();
app.engine('mustache', mustacheExpress());
app.set('views', path.join(dirname, 'views'));
app.set('view engine', 'mustache');
app.use(favicon(dirname + '/public/favicon.png'));
app.set('trust proxy', 'loopback');
app.use(logger(':remote-addr :method :url :status :response-time ms - :res[content-length]'));//app.use(logger('dev'));
app.use(logger(':remote-addr :method :url :status :response-time ms - :res[content-length]'));// App.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(dirname, 'public')));
if ( DOCKER_DEVELOP == '1') {
if (DOCKER_DEVELOP == '1') {
app.use(require('connect-livereload')());
}
app.use(function (req, res, next) {
app.use((req, res, next) => {
req.dirname = dirname;
req.db = db;
req.tokenDuration = 24 * (1000 * 3600); // token duration in milliseconds
req.tokenDuration = 24 * (1000 * 3600); // Token duration in milliseconds
next();
});
//app.use('/', routes);
// App.use('/', routes);
// app.use('/users', users);
//{-----passport
var session = require('express-session');
var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;
// {-----passport
const session = require('express-session');
const passport = require('passport');
const GithubStrategy = require('passport-github').Strategy;
passport.use(new GithubStrategy(
JSON.parse(fs.readFileSync(dirname + "/github-keys.json")),
function (accessToken, refreshToken, profile, done) {return done(null, profile); }
JSON.parse(fs.readFileSync(dirname + '/github-keys.json')),
(accessToken, refreshToken, profile, done) => {
return done(null, profile);
}
));
app.use(session({
secret: "a mi no me gusta la sémola",
secret: 'a mi no me gusta la sémola',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// add custom serialization/deserialization here (get user from mongo?) null is for errors
passport.serializeUser(function (user, done) {done(null, user); });
passport.deserializeUser(function (user, done) {done(null, user); });
// Add custom serialization/deserialization here (get user from mongo?) null is for errors
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
// Simple authentication middleware. Add to routes that need to be protected.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
......@@ -115,111 +122,115 @@ function ensureAuthenticated(req, res, next) {
}
res.redirect('/');
}
app.get('/secure-route-example', ensureAuthenticated, function (req, res) {res.send("access granted"); });
app.get('/logout', function (req, res) {
app.get('/secure-route-example', ensureAuthenticated, (req, res) => {
res.send('access granted');
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
});
app.get('/loggedIn', function (req, res) {
app.get('/loggedIn', (req, res) => {
if (req.isAuthenticated()) {
res.send({loggedIn: true, username: req.user.username});
} else {
res.send({loggedIn: false});
}
});
// start the GitHub Login process
app.get('/auth/github',passport.authenticate('github'));
// Start the GitHub Login process
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback',
passport.authenticate('github', {failureRedirect: '/'}),
function (req, res) {
// successfully loged in. Check if user is new
db.get('user').findOne({nickname: req.user.username}, "-_id")
.then(function (json) {
(req, res) => {
// Successfully loged in. Check if user is new
db.get('user').findOne({nickname: req.user.username}, '-_id')
.then(json => {
if (!json) {
// insert new user
// Insert new user
json = {
name: req.user.displayName,
nickname: req.user.username,
url: req.user._json.blog,
brainboxURL: "/user/" + req.user.username,
brainboxURL: '/user/' + req.user.username,
avatarURL: req.user._json.avatar_url,
joined: (new Date()).toJSON()
};
db.get('user').insert(json);
} else {
console.log("Update user data from GitHub");
db.get('user').update({nickname: req.user.username},{$set:{
console.log('Update user data from GitHub');
db.get('user').update({nickname: req.user.username}, {$set: {
name: req.user.displayName,
url: req.user._json.blog,
avatarURL: req.user._json.avatar_url
}});
}
});
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
});
//-----}
// -----}
global.tokenAuthentication = function (req, res, next) {
console.log(">> Check token");
var token;
if(req.params.token)
console.log('>> Check token');
let token;
if (req.params.token) {
token = req.params.token;
if(req.query.token)
}
if (req.query.token) {
token = req.query.token;
}
if(!token) {
console.log(">> No token");
if (!token) {
console.log('>> No token');
next();
return;
}
req.db.get("log").findOne({"token":token})
.then(function (obj) {
if(obj) {
req.db.get('log').findOne({token})
.then(obj => {
if (obj) {
// Check token expiry date
var now = new Date();
if(obj.expiryDate.getTime()-now.getTime() < req.tokenDuration) {
console.log(">> Authenticated by token");
const now = new Date();
if (obj.expiryDate.getTime() - now.getTime() < req.tokenDuration) {
console.log('>> Authenticated by token');
req.isTokenAuthenticated = true;
req.tokenUsername = obj.username;
} else {
console.log(">> Token expired");
console.log('>> Token expired');
}
}
next();
})
.catch(function(err) {
console.log("ERROR:",err);
.catch(err => {
console.log('ERROR:', err);
next();
});
}
};
// GUI routes
app.get('/', function (req, res) { // /auth/github
var login = (req.isAuthenticated()) ?
("<a href='/user/" + req.user.username + "'>" + req.user.username + "</a> (<a href='/logout'>Log Out</a>)")
: ("<a href='/auth/github'>Log in with GitHub</a>");
app.get('/', (req, res) => { // /auth/github
const login = (req.isAuthenticated()) ?
('<a href=\'/user/' + req.user.username + '\'>' + req.user.username + '</a> (<a href=\'/logout\'>Log Out</a>)') :
('<a href=\'/auth/github\'>Log in with GitHub</a>');
// store return path in case of login
// Store return path in case of login
req.session.returnTo = req.originalUrl;
res.render('index', {
title: 'BrainBox',
login: login
login
});
});
app.use('/mri', require('./controller/mri/'));
app.use('/project', require('./controller/project/'));
app.use('/user', require('./controller/user/'));
app.get('/api/getLabelsets', function (req, res) {
var i, arr = fs.readdirSync(dirname + "/public/labels/"), info = [];
app.get('/api/getLabelsets', (req, res) => {
let i,
arr = fs.readdirSync(dirname + '/public/labels/'),
info = [];
for (i in arr) {
var json = JSON.parse(fs.readFileSync(dirname + "/public/labels/" + arr[i]));
const json = JSON.parse(fs.readFileSync(dirname + '/public/labels/' + arr[i]));
info.push({
name: json.name,
source: arr[i]
......@@ -227,35 +238,35 @@ app.get('/api/getLabelsets', function (req, res) {
}
res.send(info);
});
app.post('/api/log', function (req, res) {
var loggedUser = req.isAuthenticated()?req.user.username:"anonymous";
var json = req.body;
var obj;
switch(json.key) {
case "annotationLength":
app.post('/api/log', (req, res) => {
const loggedUser = req.isAuthenticated() ? req.user.username : 'anonymous';
const json = req.body;
let obj;
switch (json.key) {
case 'annotationLength':
obj = {
key: "annotationLength",
key: 'annotationLength',
username: loggedUser,
"value.source": json.value.source,
"value.atlas": json.value.atlas
'value.source': json.value.source,
'value.atlas': json.value.atlas
};
req.db.get('log').findOne(obj)
.then(function(result) {
var length = 0;
if(result) {
.then(result => {
let length = 0;
if (result) {
length = parseFloat(result.value.length);
}
var sum = parseFloat(json.value.length) + length;
req.db.get('log').update(obj,{$set:{
"value.length":sum,
const sum = parseFloat(json.value.length) + length;
req.db.get('log').update(obj, {$set: {
'value.length': sum,
date: (new Date()).toJSON()
}}, {upsert: true});
res.send({length: sum});
})
.catch(function(err) {
console.log("ERROR",err);
res.send({error:JSON.stringify(err)});
.catch(err => {
console.log('ERROR', err);
res.send({error: JSON.stringify(err)});
});
break;
default:
......@@ -274,49 +285,48 @@ app.post('/api/log', function (req, res) {
req.db.get('mri').update({
source: json.value.source,
"mri.atlas":{$elemMatch:{filename:json.value.atlas}}
'mri.atlas': {$elemMatch: {filename: json.value.atlas}}
}, {
$set: {
"mri.atlas.$.modified": (new Date()).toJSON(),
"mri.atlas.$.modifiedBy": loggedUser
'mri.atlas.$.modified': (new Date()).toJSON(),
'mri.atlas.$.modifiedBy': loggedUser
}
});
});
// init web socket server
// Init web socket server
atlasMakerServer.initSocketConnection();
atlasMakerServer.dataDirectory = dirname + "/public";
// check that the 'anyone' user exists. Insert it otherwise
db.get('user').findOne({nickname:'anyone'})
.then(function(obj) {
if(!obj) {
var anyone = {
name:'Any BrainBox User',
nickname:'anyone',
brainboxURL:'/user/anyone',
joined:(new Date()).toJSON()
atlasMakerServer.dataDirectory = dirname + '/public';
// Check that the 'anyone' user exists. Insert it otherwise
db.get('user').findOne({nickname: 'anyone'})
.then(obj => {
if (!obj) {
const anyone = {
name: 'Any BrainBox User',
nickname: 'anyone',
brainboxURL: '/user/anyone',
joined: (new Date()).toJSON()
};
console.log("WARNING: 'anyone' user absent: inserting it");
console.log('WARNING: \'anyone\' user absent: inserting it');
db.get('user').insert(anyone);
} else {
console.log("'anyone' user correctly configured.");
console.log('\'anyone\' user correctly configured.');
}
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
// Catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// Error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
......@@ -324,9 +334,9 @@ if (app.get('env') === 'development') {
});
});
}
// production error handler
// Production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
......@@ -334,4 +344,4 @@ app.use(function (err, req, res, next) {
});
});
module.exports = app;
\ No newline at end of file
module.exports = app;
#!/usr/bin/env node
var debug = require('debug')('xt');
var app = require('../app');
const debug = require('debug')('xt');
const app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
const server = app.listen(app.get('port'), () => {
debug('Express server listening on port ' + server.address().port);
});
var express = require('express');
var controller = require('./mri.controller');
var upload_controller = require('./upload.controller');
const express = require('express');
const controller = require('./mri.controller');
const upload_controller = require('./upload.controller');
var multer = require('multer');
var router = express.Router();
const multer = require('multer');
const router = express.Router();
router.get('', controller.validator, controller.mri);
router.get('/json', controller.validator, tokenAuthentication, controller.api_mri_get);
......@@ -12,11 +13,11 @@ router.post('/json', controller.validator_post, tokenAuthentication, controller.
router.get('/upload', upload_controller.token);
router.post('/upload',
multer({ dest: './tmp/'}).array('atlas'),
multer({dest: './tmp/'}).array('atlas'),
upload_controller.validator,
upload_controller.other_validations,
upload_controller.upload);
router.get('/reset', controller.reset);
module.exports = router;
\ No newline at end of file
module.exports = router;
This diff is collapsed.
"use strict";
'use strict';
var fs = require('fs');
var atlasMakerServer = require('../../js/atlasMakerServer');
//expressValidator = require('express-validator')
const fs = require('fs');
const atlasMakerServer = require('../../js/atlasMakerServer');
// ExpressValidator = require('express-validator')
var validator = function (req, res, next) {
const validator = function (req, res, next) {
req.checkBody('url', 'please enter a valid URL')
.notEmpty()
.isURL();
......@@ -15,9 +15,9 @@ var validator = function (req, res, next) {
.notEmpty()
.isAlphanumeric();
req.checkBody('atlasLabelSet', 'please enter an Atlas Project')
.notEmpty()
.notEmpty();
req.checkBody('token', 'please enter an upload token')
.notEmpty()
.notEmpty();
/*
Check for all these required fields:
url: url
......@@ -26,118 +26,119 @@ var validator = function (req, res, next) {
atlasProject: Alphanumeric string
atlasLabelSet: One of the labels available inside the /public/labels/ directory
*/
var errors = req.validationErrors();
console.log("errors 33:",errors);
const errors = req.validationErrors();
console.log('errors 33:', errors);
if (errors) {
return res.send(errors).status(403).end();
} else {
return next();
}
return next();
};
var other_validations = function(req, res, next) {
var token = req.body.token;
req.db.get("log").findOne({"token":token})
.then(function (obj) {
if(obj) {
const other_validations = function (req, res, next) {
const token = req.body.token;
req.db.get('log').findOne({token})
.then(obj => {
if (obj) {
// Check token expiry date
var now = new Date();
if(obj.expiryDate.getTime()-now.getTime() < req.tokenDuration) {
req.db.get('mri').findOne({source:req.body.url, backup: {$exists: false}})
.then(function (json) {
const now = new Date();
if (obj.expiryDate.getTime() - now.getTime() < req.tokenDuration) {
req.db.get('mri').findOne({source: req.body.url, backup: {$exists: false}})
.then(json => {
if (json && req.files.length > 0) {
req.atlasUpload = {
mri: json,
username: obj.username
};
next();