Skip to content

Commit

Permalink
feat: add auth directive to surveys query
Browse files Browse the repository at this point in the history
  • Loading branch information
rmanguinho committed Dec 8, 2020
1 parent 8b19fcc commit 5a30d7f
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/main/config/apollo-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import typeDefs from '@/main/graphql/type-defs'
import resolvers from '@/main/graphql/resolvers'
import schemaDirectives from '@/main/graphql/directives'

import { ApolloServer } from 'apollo-server-express'
import { Express } from 'express'
Expand Down Expand Up @@ -28,6 +29,8 @@ export default (app: Express): void => {
const server = new ApolloServer({
resolvers,
typeDefs,
schemaDirectives,
context: ({ req }) => ({ req }),
plugins: [{
requestDidStart: () => ({
willSendResponse: ({ response, errors }) => handleErrors(response, errors)
Expand Down
22 changes: 22 additions & 0 deletions src/main/graphql/directives/auth-directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { makeAuthMiddleware } from '@/main/factories'

import { SchemaDirectiveVisitor, ForbiddenError } from 'apollo-server-express'
import { GraphQLField, defaultFieldResolver } from 'graphql'

export class AuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition (field: GraphQLField<any, any>): any {
const { resolve = defaultFieldResolver } = field
field.resolve = async (parent, args, context, info) => {
const request = {
accessToken: context?.req?.headers?.['x-access-token']
}
const httpResponse = await makeAuthMiddleware().handle(request)
if (httpResponse.statusCode === 200) {
Object.assign(context?.req, httpResponse.body)
return resolve.call(this, parent, args, context, info)
} else {
throw new ForbiddenError(httpResponse.body.message)
}
}
}
}
5 changes: 5 additions & 0 deletions src/main/graphql/directives/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { AuthDirective } from './auth-directive'

export default {
auth: AuthDirective
}
2 changes: 2 additions & 0 deletions src/main/graphql/type-defs/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { gql } from 'apollo-server-express'

export default gql`
scalar DateTime
directive @auth on FIELD_DEFINITION
type Query {
_: String
Expand Down
2 changes: 1 addition & 1 deletion src/main/graphql/type-defs/survey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { gql } from 'apollo-server-express'

export default gql`
extend type Query {
surveys: [Survey!]!
surveys: [Survey!]! @auth
}
type Survey {
Expand Down

0 comments on commit 5a30d7f

Please sign in to comment.