0.1.1 • Published 7 years ago

graphql-factory-passport v0.1.1

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

graphql-factory-passport

Passport.js plugin for GraphQL Factory

About

This plugin allows the use of passport.js standard strategies for auth to "tagged" graphql operations using the graphql-factory framework. This plugin was written as a companion plugin to graphql-factory-acl which provides authorization to graphql operations.

Example

import * as graphql from 'graphql'
import GraphQLFactory from 'graphql-factory'
import PassportPlugin from 'graphql-factory-passport'
import passport from 'passport'

// passport local strategy
import localStrategy from './localStrategy'

// add the strategy with a name that will be referenced
// in the _factoryPassport tag
passport.use('local', localStrategy)

const definition = {
  schemas: {
    Auth: {
      query: {
        fields: {
          basicAuth: {
            type: 'String',
            args: {
              username: { type: 'String', nullable: false },
              password: { type: 'String', nullable: false }
            },
            resolve (source, args, context, info) {
              // the user object is passed as the source
              // on successful authentication
              return source.username
            },
            // tag the field with _factoryPassport who's
            // value is the strategy name
            _factoryPassport: 'local'
          }
        }
      }
    }
  }
}

const factory = GraphQLFactory(graphql)
const lib = factory.make(definition, {
  plugin: [ new PassportPlugin(passport) ]
})

lib.Auth(`
  query Authenticate {
    basicAuth (
      username: "john",
      password: "p@ncakes!"
    )
  }
`)
.then(result => {
  // process query result
})

Passport setup

Passport should be setup the same way it is with express except that passport.initialize() should not be called. Additionally, strategies need to be named in order for the plugin to apply them.

Tagging

For graphql operations that require passport authentication simply add _factoryPassport key/tag to the operation's field with the strategy name as its value (see example above).

User object

The user object is made available in the source field of the resolver function

Notes

Some passport options like redirect are ignored by this plugin because they do not make sense in the context of a graphql request.

Integration

As previously stated this plugin can be used along with graphql-factory-acl to provide authN and authZ. The workflow there would be to create a query that uses graphql-factory-passport to authenticate a user account and return a jsonwebtoken which can then be used on operations protected by graphql-factory-acl by injecting the jsonwebtoken into the rootValue.jwt property of the request.