Created
March 5, 2020 15:42
-
-
Save bogoslavskiy/d79d37b150520428ed963cd322176a6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SchemaDirectiveVisitor } from 'graphql-tools'; | |
import { gql, AuthenticationError } from 'apollo-server'; | |
import { GraphQLField, defaultFieldResolver } from 'graphql'; | |
import AccessTokenModel from '../models/AccessTokenModel'; | |
import { ResolverContext } from '../types'; | |
class AuthDirective extends SchemaDirectiveVisitor { | |
visitFieldDefinition(field: GraphQLField<any, any>) { | |
const { resolve = defaultFieldResolver } = field; | |
field.resolve = async function (...args) { | |
const context = args[2] as ResolverContext; | |
if (!context.token) { | |
throw new AuthenticationError("User authorization failed: no token passed."); | |
} | |
const token = await AccessTokenModel.findOne({ | |
token: context.headers.token | |
}); | |
if (!token) { | |
throw new AuthenticationError("Access denied"); | |
} | |
args[2] = { | |
...context, | |
user_id: token.user_id, | |
token | |
}; | |
return resolve.apply(this, args); | |
}; | |
field.description = | |
(field.description ? field.description + '\n ' : '') + | |
'`require authorization`'; | |
} | |
} | |
export default { | |
declaration: gql` | |
directive @auth on FIELD_DEFINITION | |
`, | |
directive: AuthDirective | |
}; | |
/* | |
Usage: | |
type MessagesMutation { | |
send(input: MessageSendInput!): Message! @auth | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment