Commit 3c8a0e00 authored by A. Koch's avatar A. Koch
Browse files

refactored, now using generic api module

parent e071eb35
This diff is collapsed.
...@@ -37,32 +37,20 @@ ...@@ -37,32 +37,20 @@
}, },
"dependencies": { "dependencies": {
"@polka/send-type": "^0.4.0", "@polka/send-type": "^0.4.0",
"acl": "^0.4.11",
"axios": "^0.18.0", "axios": "^0.18.0",
"body-parser": "^1.18.3",
"config": "^1.30.0",
"cors": "^2.8.4",
"express-jwt": "^5.3.1",
"jwks-rsa": "^1.2.1",
"luxon": "^1.3.3", "luxon": "^1.3.3",
"mbjs-data-models": "0.0.8", "mbjs-data-models": "0.0.8",
"mbjs-media": "0.0.12", "mbjs-generic-api": "0.0.5",
"mbjs-media": "0.0.13",
"mbjs-persistence": "^0.2.0", "mbjs-persistence": "^0.2.0",
"mbjs-utils": "0.0.5", "mbjs-utils": "0.0.5",
"memcached": "^2.2.2", "memcached": "^2.2.2",
"mongodb": "^3.1.0", "mongodb": "^3.1.0",
"morgan": "^1.9.0",
"multer": "^1.3.1", "multer": "^1.3.1",
"mz": "^2.7.0", "mz": "^2.7.0",
"nedb": "^1.8.0", "nedb": "^1.8.0",
"polka": "^0.4.0",
"primus": "^7.2.2",
"rimraf": "^2.6.2", "rimraf": "^2.6.2",
"serve-favicon": "^2.5.0",
"serve-static": "^1.13.2",
"tiny-emitter": "^2.0.2", "tiny-emitter": "^2.0.2",
"uws": "^10.148.0",
"winston": "^2.4.2",
"yauzl": "^2.10.0", "yauzl": "^2.10.0",
"yazl": "^2.4.3" "yazl": "^2.4.3"
} }
......
const
Acl = require('acl'),
config = require('config'),
Backend = Acl.mongodbBackend,
MongoClient = require('mongodb').MongoClient,
send = require('@polka/send-type')
const setupACL = async function (app) {
const cfg = config.get('acl.mongodb')
cfg.logger = console
const db = await new Promise((resolve, reject) => {
MongoClient.connect(cfg.url, function (err, client) {
if (err) return reject(err)
cfg.logger.info(`ACL connected at ${cfg.url}/${cfg.dbName}`)
const db = client.db(cfg.dbName)
resolve(db)
})
})
const acl = new Acl(new Backend(db))
/**
* Manage permissions
*/
app.get('/acl/:role/:resource', (req, res, next) => {
acl.allowedPermissions(req.params.role, req.params.resource, (err, result) => {
if (err) next(err)
else if (result) send(res, 200, result)
else send(res, 404)
})
})
app.put('/acl/:role/:resource', (req, res, next) => {
acl.allow(req.params.role, req.params.resource, req.body, err => {
if (err) next(err)
else send(res, 200)
})
})
/**
* Manage roles
*/
app.get('/acl/:userId/roles', (req, res, next) => {
acl.userRoles(req.params.userId, (err, result) => {
if (err) next(err)
else send(res, 200, result)
})
})
app.post('/acl/:userId/roles', (req, res, next) => {
acl.addUserRoles(req.params.userId, req.body, err => {
if (err) next(err)
else send(res, 200)
})
})
app.delete('/acl/:userId/roles', (req, res, next) => {
acl.removeUserRoles(req.params.userId, req.body, err => {
if (err) next(err)
else send(res, 200)
})
})
return acl
}
module.exports = setupACL
{ {
"api": { "api": {
"uriBase": "https://app.motionbank.org",
"apiHost": "http://localhost:3030" "apiHost": "http://localhost:3030"
}, },
"http": { "http": {
...@@ -24,9 +25,26 @@ ...@@ -24,9 +25,26 @@
"dbName": "motionbank-api-sys-dev" "dbName": "motionbank-api-sys-dev"
} }
}, },
"metadata": {
"memcachedURL": null,
"lifetime": 86400
},
"auth": { "auth": {
"jwks": {
"cache": true,
"rateLimit": true,
"jwksRequestsPerMinute": 5,
"jwksUri": "https://motionbank.eu.auth0.com/.well-known/jwks.json"
},
"jwt": { "jwt": {
"audience": "http://localhost:3030" "audience": "http://localhost:3030",
"issuer": "https://motionbank.eu.auth0.com/",
"algorithms": ["RS256"],
"credentialsRequired": false
} }
},
"apiKeys": {
"youtube": null,
"vimeo": null
} }
} }
const const GenericAPI = require('mbjs-generic-api')
config = require('config'),
path = require('path'),
http = require('http'),
polka = require('polka'),
Primus = require('primus'),
morgan = require('morgan'),
cors = require('cors')({ origin: true }),
send = require('@polka/send-type'),
jwt = require('express-jwt'),
favicon = require('serve-favicon'),
jwks = require('jwks-rsa'),
{ json } = require('body-parser'),
{ ObjectUtil } = require('mbjs-utils')
const setup = async function () { const setup = async function () {
/** const api = new GenericAPI()
* HTTP server await api.setup()
*/
const
host = config.get('http.host'),
port = config.get('http.port'),
server = http.createServer()
/**
* Logger
*/
const winston = require('winston')
winston.level = process.env.NODE_ENV === 'production' ? 'error' : 'info'
winston.level = process.env.LOG_LEVEL || winston.level
/**
* Set up WebSockets (Primus)
*/
const primus = new Primus(server, { transformer: 'uws' })
primus.on('connection', spark => {
winston.log('debug', `Spark ${spark.id} connected with address ${spark.address}`)
})
primus.on('disconnection', spark => {
winston.log('debug', `Spark ${spark.id} disconnected with address ${spark.address}`)
})
/**
* Setup API server (Polka)
*/
const
app = polka({
server,
onError (err, req, res, next) {
send(res, err.status || 500, { code: err.code })
}
})
app.use(favicon(path.join(__dirname, '..', 'assets', 'favicon.ico')))
const jwtCheck = jwt(ObjectUtil.merge({
secret: jwks.expressJwtSecret(config.get('auth.jwks'))
}, config.get('auth.jwt')))
app.use(cors, jwtCheck, json(), morgan(process.env.NODE_ENV === 'production' ? 'common' : 'dev'))
/**
* Add proxy
*/
const proxy = require('./middleware/proxy')
proxy(app)
/**
* Set up ACL
*/
const
setupACL = require('./auth/acl'),
acl = await setupACL(app)
/**
* Middleware
*/
const addUserUUID = require('./middleware/user')
addUserUUID(app)
/** /**
* Configure Profiles * Configure Profiles
*/ */
const const
Profiles = require('./profiles'), Profiles = require('./lib/profiles'),
profiles = new Profiles(app) profiles = new Profiles(api._app)
profiles.on('message', message => winston.debug(message)) // profiles.on('message', message => api._logger.debug(message))
const addAuthor = require('./middleware/author') const addAuthor = require('./middleware/author')
addAuthor(app, profiles) addAuthor(api._app, profiles)
/** /**
* Configure resources * Configure resources
*/ */
const const
models = require('mbjs-data-models'), models = require('mbjs-data-models'),
Service = require('./service') Service = require('./lib/service')
const annotations = new Service('annotations', app, models.Annotation, winston, acl) const annotations = new Service('annotations', api._app, models.Annotation, api._logger, api._acl)
annotations.on('message', message => primus.write(message)) // annotations.on('message', message => api._sockets.write(message))
const maps = new Service('maps', app, models.Map, winston, acl) const maps = new Service('maps', api._app, models.Map, api._logger, api._acl)
maps.on('message', message => primus.write(message)) // maps.on('message', message => api._sockets.write(message))
const documents = new Service('documents', app, models.Document, winston, acl) // const documents = new Service('documents', api._app, models.Document, api._logger, api._acl)
documents.on('message', message => primus.write(message)) // documents.on('message', message => api._sockets.write(message))
/** /**
* Configure metadata * Configure metadata
*/ */
const const
Metadata = require('./metadata'), Metadata = require('./lib/metadata'),
metadata = new Metadata(app, annotations) metadata = new Metadata(api._app, annotations)
metadata.on('message', message => primus.write(message)) // metadata.on('message', message => api._sockets.write(message))
/** /**
* Configure sessions * Configure sessions
*/ */
const const
Sessions = require('./sessions'), Sessions = require('./lib/sessions'),
sessions = new Sessions(app, maps, annotations) sessions = new Sessions(api._app, maps, annotations)
sessions.on('message', message => primus.write(message)) // sessions.on('message', message => api._logger.write(message))
/** /**
* Configure archives * Configure archives
*/ */
const archives = require('./archives') const archives = require('./lib/archives')
archives.setupArchives(app, maps, annotations) archives.setupArchives(api._app, maps, annotations)
/** await api.start()
* Start server
*/
return app.listen(port, host).then(() => winston.info(`API started on ${host}:${port}`))
} }
setup().catch(err => { setup().catch(err => {
......
const
axios = require('axios'),
send = require('@polka/send-type')
module.exports = function (app) {
app.use('/proxy', async (req, res, next) => {
const result = await axios.get(req.query.url)
send(res, 200, result.data, { 'Content-Type': result.headers['content-type'] })
})
}
const { ObjectUtil } = require('mbjs-utils')
const setup = async function (app) {
app.use(async (req, res, next) => {
if (req.user) {
req.user.uuid = ObjectUtil.uuid5(req.user.sub)
}
next()
})
}
module.exports = setup
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment