2016-10-04 21:40:56 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var _ = require('underscore');
|
|
|
|
var AuthApi = require('../auth/auth_api');
|
|
|
|
|
2018-02-19 20:24:44 +08:00
|
|
|
function authenticatedMiddleware(userDatabaseService, forceToBeAuthenticated = false) {
|
2016-10-04 21:40:56 +08:00
|
|
|
return function middleware(req, res, next) {
|
|
|
|
req.profiler.start('sqlapi.job');
|
|
|
|
req.profiler.done('init');
|
|
|
|
|
|
|
|
// clone so don't modify req.params or req.body so oauth is not broken
|
2018-02-19 20:24:44 +08:00
|
|
|
const params = _.extend({}, res.locals, req.query, req.body);
|
|
|
|
|
|
|
|
const { user } = res.locals;
|
2016-10-04 21:40:56 +08:00
|
|
|
|
2018-02-16 00:23:35 +08:00
|
|
|
var authApi = new AuthApi(req, res, params);
|
2018-02-19 20:24:44 +08:00
|
|
|
userDatabaseService.getConnectionParams(authApi, user, function (err, dbParams, authDbParams, userLimits) {
|
2016-10-04 21:40:56 +08:00
|
|
|
req.profiler.done('setDBAuth');
|
|
|
|
|
|
|
|
if (err) {
|
2018-02-17 01:21:06 +08:00
|
|
|
return next(err);
|
2016-10-04 21:40:56 +08:00
|
|
|
}
|
|
|
|
|
2018-02-19 20:24:44 +08:00
|
|
|
if (forceToBeAuthenticated && !dbParams.authenticated) {
|
2018-02-17 01:21:06 +08:00
|
|
|
return next(new Error('permission denied'));
|
2016-10-04 21:40:56 +08:00
|
|
|
}
|
|
|
|
|
2018-02-19 20:24:44 +08:00
|
|
|
res.locals.userDbParams = dbParams;
|
|
|
|
res.locals.authDbParams = authDbParams;
|
|
|
|
res.locals.userLimits = userLimits;
|
2016-10-04 21:40:56 +08:00
|
|
|
|
2018-02-17 01:21:06 +08:00
|
|
|
next();
|
2016-10-04 21:40:56 +08:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = authenticatedMiddleware;
|