-
Notifications
You must be signed in to change notification settings - Fork 13
/
overrideSchema.js
129 lines (116 loc) · 3.25 KB
/
overrideSchema.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
const { gql } = require('apollo-server-lambda')
const cookie = require('cookie')
const faunadb = require('faunadb')
const q = faunadb.query
const overrideTypeDefs = gql`
input LoginInput {
email: String!
password: String!
}
type Mutation {
login(data: LoginInput): String! @resolver(name: "login")
}
`
const createOverrideResolvers = (remoteExecutableSchema) => ({
Mutation: {
login: async (root, args, context, info) => {
console.log('*** OVERRIDE mutation login')
// short circuit if cookie exists
if (context.event.headers.cookie) {
const parsedCookie = cookie.parse(context.event.headers.cookie)
const cookieSecret = parsedCookie['fauna-token']
const userClient = new faunadb.Client({
secret: cookieSecret
})
const alreadyLoggedIn = await userClient
.query(q.Get(q.CurrentIdentity()))
.then((response) => {
if (!response.message) {
if (args.data && args.data.email && args.data.email) {
// TODO trying to log in as someone else besides cookie holder.
// should probably log them out first!
return response.data.email === args.data.email
} else {
// did not provide credentials so just use the cookie values
return true
}
}
return false
})
.catch((e) => {
console.log('error: bad cookie secret')
console.trace(e)
return false
})
if (alreadyLoggedIn) {
return true
} else {
// kill the cookie
context.setCookies.push({
name: 'fauna-token',
value: '',
options: {
httpOnly: true,
expires: new Date()
}
})
}
return false
}
if (!args.data || !args.data.email || !args.data.email) return false
const result = await info.mergeInfo
.delegateToSchema({
schema: remoteExecutableSchema,
operation: 'mutation',
fieldName: 'login',
args,
context,
info
})
.catch(console.trace)
if (result) {
context.setCookies.push({
name: 'fauna-token',
value: result,
options: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production'
}
})
return true
}
return false
},
logout: async (root, args, context, info) => {
console.log('*** OVERRIDE mutation logout')
// short circuit if NO cookie exists
if (!context.event.headers.cookie) {
return true
}
await info.mergeInfo
.delegateToSchema({
schema: remoteExecutableSchema,
operation: 'mutation',
fieldName: 'logout',
args,
context,
info
})
.catch(console.trace)
// kill the cookie
context.setCookies.push({
name: 'fauna-token',
value: '',
options: {
httpOnly: true,
expires: new Date()
}
})
return true
}
}
})
module.exports = {
overrideTypeDefs,
createOverrideResolvers
}