Skip to content

Instantly share code, notes, and snippets.

@claustres
Last active August 3, 2017 16:50
Show Gist options
  • Save claustres/d10f7cbb7c17513e8ebc0ec996e0338f to your computer and use it in GitHub Desktop.
Save claustres/d10f7cbb7c17513e8ebc0ec996e0338f to your computer and use it in GitHub Desktop.
Dynamic authorization service
import _ from 'lodash'
import sift from 'sift'
// Util function to look for a given resource in a scope
function findResource (scope, query) {
let results = sift(query, scope)
return results.length > 0 ? results[0] : null
}
const service = {
create (data, params) {
// The scope identify the type of resources
let scopeName = data.scope
// Then retrieve the right scope on the subject
let scope = _.get(params.subject, scopeName, [])
// Then the target resource
let resource = findResource(scope, { _id: params.resource._id.toString() })
// On first authorisation create the resource in scope
if (!resource) {
resource = {
name: params.resource.name,
_id: params.resource._id.toString()
}
scope.push(resource)
}
// Now we have to set permissions on the given subject's scope
resource.permissions = data.permissions
// Update scope on user
_.set(subject, scopeName, scope)
return app.service('users').patch(subject._id, { [scopeName]: scope })
.then(subject => {
debug('Authorisation ' + data.permissions + ' set for subject ' + params.subject._id + ' on resource ' + params.resource._id + ' with scope ' + scopeName)
})
},
remove (id, params) {
let query = params.query
// The scope identify the type of resources
let scopeName = query.scope
// Then retrieve the right scope on the subject
let scope = _.get(subject, scopeName, [])
// Then the target resource
scope.filter(sift({ _id: id }))
// Update scope on user
_.set(subject, scopeName, scope)
return app.service('users').patch(subject._id, { [scopeName]: scope })
.then(subject => {
debug('Authorisation unset for subject ' + subject._id + ' on resource ' + id + ' with scope ' + scopeName)
})
}
}
app.use('authorisations', service)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment