-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathauthenticate.js
More file actions
53 lines (49 loc) · 1.46 KB
/
authenticate.js
File metadata and controls
53 lines (49 loc) · 1.46 KB
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
const fromEvent = require('graphcool-lib').fromEvent
const bcrypt = require('bcrypt')
module.exports = function(event) {
const phoneNumber = event.data.phoneNumber
const deviceId = event.data.deviceId
const graphcool = fromEvent(event)
const api = graphcool.api('simple/v1')
function getGraphcoolUser(phoneNumber) {
return api.request(`
query {
User(phoneNumber: "${phoneNumber}") {
id
deviceId
}
}`)
.then((userQueryResult) => {
if (userQueryResult.error) {
return Promise.reject(userQueryResult.error)
} else {
return userQueryResult.User
}
})
}
function generateGraphcoolToken(graphcoolUserId) {
return graphcool.generateAuthToken(graphcoolUserId, 'User')
}
return getGraphcoolUser(phoneNumber)
.then((graphcoolUser) => {
if (graphcoolUser === null) {
return Promise.reject("Invalid Credentials") //returning same generic error so user can't find out what phoneNumbers are registered.
} else {
return bcrypt.compare(deviceId, graphcoolUser.deviceId)
.then((res) => {
if (res === true) {
return graphcoolUser.id
} else {
return Promise.reject("Invalid Credentials")
}
})
}
})
.then(generateGraphcoolToken)
.then((token) => {
return { data: { token } }
})
.catch((error) => {
return { error: error.toString() }
})
}