How to use the graphql-shield.shield function in graphql-shield

To help you get started, we’ve selected a few graphql-shield examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Gomah / prisma-serverless / src / permissions / index.ts View on Github external
async (parent, args, context: Ctx): Promise => {
      const userId = await getUserId(context);
      return !!userId;
    }
  ),

  isAdmin: rule({ cache: 'strict' })(
    async (parent, args, context: Ctx): Promise => {
      const userId = await getUserId(context);
      const user: User = await context.prisma.user({ id: userId });
      return user.role === 'ADMIN';
    }
  ),
};

export const permissions = shield({
  Query: {
    // Global
    '*': rules.isAdmin,
    profile: rules.isUser,
  },
  Mutation: {
    '*': rules.isAdmin,
    login: allow,
    signup: allow,
  },
});
github rsnay / wadayano / server / src / index.js View on Github external
endpoint: config.PRISMA_ENDPOINT,
	secret: config.PRISMA_SECRET,
	debug: true,
});

// Set up our graphql server
const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  resolverValidationOptions :{
    requireResolversForResolveType: false
  },
  // Since the shield catches errors and masks as unauthorized,
  // commenting this next line out is very helpful for debugging.
  // Just make *certain* that it is uncommented before committing/pushing.
  middlewares: [shield(Permissions)],
  context: req => ({
    ...req,
    // Allow this server's mutations and queries to access prisma server
    db
  }),
});

// Nginx proxy_passes to this server, and we want to trust its forwarded https headers, so that oauth signatures match
server.express.enable('trust proxy');

// Handle LTI launch requests
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({ extended: false })
server.post('/lti', urlencodedParser, (req, res) => handleLaunch(config, db, req, res));
server.post('/lti/:action/:objectId', urlencodedParser, (req, res) => handleLaunch(config, db, req, res));
github maticzav / graphql-shield / examples / simple / src / index.js View on Github external
Query: {
      hello: (_, { name }) => `Hello ${name || 'World'}`,
      secret: (_, { agent }) => `Hello agent ${agent}`,
   },
}

const permissions = {
   Query: {
      hello: () => true,
      secret: (_, { code }) => code === 'donttellanyone'
   }
}

const server = new GraphQLServer({
   typeDefs,
   resolvers: shield(resolvers, permissions, { debug: true })
})

server.start(() => console.log('Server is running on http://localhost:4000'))
github waitandseeagency / graphql-sword / src / permissions.ts View on Github external
export const validatePermissions = (
  schema: GraphQLSchema,
  permissions: IPermission[],
  options: IOptions,
) => {
  return shield(
    extractPermissions(
      permissions,
      extractOperationsName(schema),
      options,
    ),
    {
      debug: options.debug,
      allowExternalErrors: true,
    },
  )
}
github webiny / webiny-js / packages / api-security / src / plugins / security.js View on Github external
plugins.byType("graphql-schema").forEach(plugin => {
                    let { security } = plugin;
                    if (!security) {
                        return true;
                    }

                    if (typeof security === "function") {
                        security = security();
                    }

                    security.shield &&
                        middleware.push(
                            shield(security.shield, {
                                allowExternalErrors: true
                            })
                        );
                });
github WhatTheFar / modularizing-graphql-boilerplate / src / permissions.ts View on Github external
import { mergeResolvers } from '@src/resolvers';
import { shield } from 'graphql-shield';
import { fileLoader } from 'merge-graphql-schemas';
import { join } from 'path';

const permissionsArray = fileLoader(join(__dirname, './**/*.permissions.*')) as any[];

const mergedPermissions = mergeResolvers(permissionsArray);
export const permissions = shield(mergedPermissions);
github arkhn / pyrog / server-v2 / src / permissions / index.ts View on Github external
const rules = {
  isAuthenticatedUser: rule()((_, __, ctx: Context) => {
    const userId = getUserId(ctx)
    return Boolean(userId)
  }),
  isAdmin: rule()(async (_, __, ctx: Context) => {
    const userId = getUserId(ctx)
    const user = await ctx.photon.users.findOne({
      where: { id: userId },
    })
    return Boolean(user && user.role == 'ADMIN')
  }),
}

export const permissions = shield({
  Query: {
    me: rules.isAuthenticatedUser,
    sources: rules.isAuthenticatedUser,
    source: rules.isAuthenticatedUser,
    resource: rules.isAuthenticatedUser,
    attribute: rules.isAuthenticatedUser,
  },
  Mutation: {
    createSource: rules.isAdmin,
  },
})
github prisma / prisma-examples / typescript / graphql-auth / src / permissions / index.ts View on Github external
return Boolean(userId)
  }),
  isPostOwner: rule()(async (parent, { id }, context) => {
    const userId = getUserId(context)
    const author = await context.photon.posts
      .findOne({
        where: {
          id,
        },
      })
      .author()
    return userId === author.id
  }),
}

export const permissions = shield({
  Query: {
    me: rules.isAuthenticatedUser,
    filterPosts: rules.isAuthenticatedUser,
    post: rules.isAuthenticatedUser,
  },
  Mutation: {
    createDraft: rules.isAuthenticatedUser,
    deletePost: rules.isPostOwner,
    publish: rules.isPostOwner,
  },
})
github revskill10 / next-template / packages / server / create-graphql-server.js View on Github external
introspectSchema, 
  makeRemoteExecutableSchema,
} = require('graphql-tools')

const {canViewReport} = require('./policies')

const urlMap = {
  'reportingService': {
    uri: process.env.REPORTING_SERVICE_GRAPHQL_URL,
    subUri: process.env.REPORTING_SERVICE_SUBSCRIPTION_URL,
    headers: {
      "X-Hasura-Access-Key": process.env.HASURA_ACCESS_KEY,
      "Content-Type": "application/json",
    },
    prefix: 'reporting',
    permissions: shield({
      'query_root': {
        v_all_lesson_class: rule()(canViewReport),
      },      
      'subscription_root': {
        v_all_lesson_class: rule()(canViewReport),
      },
    })
  },
  'userService': {
    uri: process.env.USER_SERVICE_GRAPHQL_URL,
    subUri: process.env.USER_SERVICE_SUBSCRIPTION_URL,
    headers: {
      "X-Hasura-Access-Key": process.env.HASURA_ACCESS_KEY,
      "Content-Type": "application/json",
    },
    prefix: null,
github este / este / server / api / permissions / index.js View on Github external
createWeb: isAuthenticated,
    deleteWeb: and(isAuthenticated, isWebCreator(args => args.input.id)),
    setTheme: isAuthenticated,
    setPageTitle: and(isAuthenticated, isPageCreator(args => args.input.id)),
    setWebName: and(isAuthenticated, isWebCreator(args => args.input.id)),
    setPageElement: and(isAuthenticated, isPageCreator(args => args.input.id)),
    deletePage: and(isAuthenticated, isPageCreator(args => args.input.id)),
  },
  Query: {
    me: allow,
    page: and(isAuthenticated, isPageCreator(args => args.id)),
    web: and(isAuthenticated, isWebCreator(args => args.id)),
  },
};

const permissions = shield(rules);

export default permissions;

graphql-shield

GraphQL Server permissions as another layer of abstraction!

MIT
Latest version published 2 years ago

Package Health Score

72 / 100
Full package analysis

Similar packages