-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathapollo-auth.js
83 lines (74 loc) · 2.12 KB
/
apollo-auth.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
80
81
82
83
// @flow
// Run: ./node_modules/.bin/babel-node ./articles/graphql/auth/apollo-auth.js
import { ApolloServer, AuthenticationError } from 'apollo-server'; // v2.1
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
import jwt from 'jsonwebtoken';
const JWT_SECRET_KEY = 'qwerty ;)';
const users = [{ id: 1, roles: ['ADMIN', 'USER'] }, { id: 2, roles: ['USER'] }];
// Получаем объект пользователя из запроса
async function getUserFromReq(req: any) {
const token = req?.cookies?.token || req?.headers?.authorization;
if (token) {
const payload = jwt.verify(token, JWT_SECRET_KEY);
if (payload) {
const user = users.find(u => u.id === payload?.sub);
if (user) return user;
}
}
return null;
}
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: (source, args, context) => {
return `Hello, ${context.hasRole('ADMIN') ? 'ADMIN' : 'NON-ADMIN'} from ip ${
context.req.ip
}`;
},
},
},
}),
});
const server = new ApolloServer({
schema,
context: async ({ req }) => {
let user;
try {
user = await getUserFromReq(req);
} catch (e) {
throw new AuthenticationError('You provide incorrect token!');
}
const hasRole = role => {
if (user && Array.isArray(user.roles)) return user.roles.includes(role);
return false;
};
return { req, user, hasRole };
},
playground: {
tabs: [
{
endpoint: 'http://localhost:5000/',
query: `
# FOR DEMO PURPOSES
# You may try
# 1) Delete HTTP HEADERS at all (open them from bottom panel)
# 2) Change token (add some symbols to it) for getting an error
# 3) Or try admin token:
# { "Authorization": "${jwt.sign({ sub: 1 }, JWT_SECRET_KEY)}" }
query {
hello
}
`,
headers: {
Authorization: jwt.sign({ sub: 2 }, JWT_SECRET_KEY),
},
},
],
},
});
server.listen({ port: 5000, endpoint: '/' }).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});