diff --git a/authorization.js b/authorization.js index 7ac282ebe9c67e79d08ef7f54e8fc57b966e793b..eb8160b61128924cf88f3f0a8f7654139ebd00ae 100644 --- a/authorization.js +++ b/authorization.js @@ -9,6 +9,8 @@ const { not, } = require('graphql-shield') +const { isAdmin, isAuthenticated } = require('./src/helpers') + module.exports = { rule, inputRule, @@ -18,4 +20,6 @@ module.exports = { chain, or, not, + isAuthenticated, + isAdmin, } diff --git a/src/graphqlSchema.js b/src/graphqlSchema.js index 8219ea200422ebd3ecdfd32c242d407d3c9613d1..896b6815e6d9fa61515f4951c34d385b06b730a7 100644 --- a/src/graphqlSchema.js +++ b/src/graphqlSchema.js @@ -1,11 +1,13 @@ const config = require('config') - +const isEmpty = require('lodash/isEmpty') const { applyMiddleware } = require('graphql-middleware') const { shield } = require('graphql-shield') let schema = require('pubsweet-server/src/graphql/schema') -if (config.has('permissions')) { - schema = applyMiddleware(schema, shield(config.get('permissions'))) +const permissions = config.has('permissions') && config.get('permissions') + +if (permissions && !isEmpty(permissions)) { + schema = applyMiddleware(schema, shield(permissions)) } module.exports = schema diff --git a/src/helpers.js b/src/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..62a81da214401d7f34e073144dab0023d13b0e85 --- /dev/null +++ b/src/helpers.js @@ -0,0 +1,21 @@ +const { rule } = require('graphql-shield') + +const isAuthenticated = rule()(async (parent, args, ctx, info) => { + return !!ctx.user +}) + +const isAdmin = rule()( + async (parent, args, { user: userId, connectors: { User } }, info) => { + if (!userId) { + return false + } + + const user = await User.model.findById(userId) + return user.admin + }, +) + +module.exports = { + isAuthenticated, + isAdmin, +}