npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

gql-auth-directives

v1.0.2

Published

Guard your GraphQL API using roles & permissions schema directives.

Downloads

100

Readme


Summary

gql-auth-directives is a set of schema directives that allows a granular approach to role-based access control with GraphQL.

Features

  • Directives for roles, permissions and authentication
  • Allows access control for queries, mutations
  • Allows access control for input types
  • Provided with default handlers using JWTs

Getting Started

Prerequisites

This package requires the user to use a server that supports Apollo schema directives.

Installing

Use npm

$ npm install --save gql-auth-directives

or yarn

$ yarn add gql-auth-directives

to install the package.

Available directives

  • @hasRole(roles: ["ADMIN", "USER"])

    A user with either an admin or user role will be authorized

  • @hasPermission(permissions: ["CREATE_USERS"])
  • @isAuthenticated

Setup

Default handlers

To use the default handlers, the environment variable JWT_SECRET must be set. The variable will be used for verifying authorization headers and grab roles/permissions arrays in the token's payload.

We need to generate the auth directives and add it to the server configuration like so:

import { createAuthDirectives } from "gql-auth-directives";

const authDirectives = createAuthDirectives();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives: { ...authDirectives },
  context(ctx) {
    return { ...ctx }; // ⚠ Make sure to always pass the ctx from the server's context function
  },
});

Override handlers

The library also allows using custom functions for the provided directives.

You could override the hasPermission handler like so:

import { createAuthDirectives } from "gql-auth-directives";

const authDirectives = createAuthDirectives({
  hasPermissionHandler: (ctx, permissions) => {
    const user = getUser(ctx);
    // Do something with the user and throw an error if the user's permissions doesn't match the permissions passed
  },
});

const server = new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives: { ...authDirectives },
  context(ctx) {
    return { ...ctx };
  },
});

Schema declarations

We also need to add the directives declarations at the top of our GraphQL schema like so:

directive @isAuthenticated on FIELD | FIELD_DEFINITION | INPUT_FIELD_DEFINITION
directive @hasPermission(permissions: [String!]!) on FIELD | FIELD_DEFINITION | INPUT_FIELD_DEFINITION
directive @hasRole(roles: [String!]!) on FIELD | FIELD_DEFINITION | INPUT_FIELD_DEFINITION

[...]

If you use something like makeExecutableSchema from graphql-tools that allows schema stitching you can also add the directives declarations like so:

import { createAuthDirectives, authTypeDefs } from "gql-auth-directives";
import { makeExecutableSchema } from "graphql-tools";

const authDirectives = createAuthDirectives();

const schema = makeExecutableSchema({
  resolvers,
  typeDefs: [authTypeDefs, typeDefs],
  schemaDirectives: { ...authDirectives },
});

const server = new ApolloServer({
  schema,
  context(ctx) {
    return { ...ctx };
  },
});

Usage

We can now use our directives inside our GraphQL schema:

input CreatePostInput {
  name: String!
  description: String!
  published: Boolean @hasPermission(permissions: ["PUBLISH_POST"])
}

type Mutation {
  createPost(data: CreatePostInput!): Post! @hasRole(roles: ["AUTHOR"])
}

type Query {
  me: User! @isAuthenticated
}

ℹ Notice that you can also use the directives for inputs. If an unauthorized user tries to fill the published field it will throw an error and never reach the resolver.

License

MIT