This repository has been archived by the owner on Jan 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (67 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require('express');
const {
ApolloServer,
gql,
SchemaDirectiveVisitor,
ApolloError,
} = require('apollo-server-express');
const { introspectToken } = require('./mocks');
const { defaultFieldResolver } = require("graphql");
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
directive @auth( scope: String ) on FIELD_DEFINITION
type User {
_id: ID!
name: String! @auth(scope: "user:read:*")
age: Int! @auth(scope: "user:read:*")
}
type Query {
Users: [User]
}
`;
class AuthDirective extends SchemaDirectiveVisitor {
// https://www.apollographql.com/docs/apollo-server/schema/creating-directives/#uppercasing-strings
visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field;
const { scope } = this.args
field.resolve = async function (...args) {
const context = args[2];
if (!context || !context.headers || !context.headers.authorization) {
throw new ApolloError('Unauthorized', 'UNAUTHORIZED')
}
const token = context.headers.authorization;
const accessToken = token.replace('Bearer ', '');
const inspectedInfo = introspectToken(accessToken)
if (!inspectedInfo || !inspectedInfo.active || inspectToken.scope !== scope) {
throw new ApolloError('Unauthorized', 'UNAUTHORIZED')
}
const result = await resolve.apply(this, args);
return result;
};
}
}
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
Users: () => [{
_id: 'first user id',
name: 'Truong Ma Phi',
age: 25,
}]
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
auth: AuthDirective,
},
context: (integrationContext) => ({
headers: integrationContext.req.headers
}),
});
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);