forked from Jobcool/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticate.js
More file actions
63 lines (57 loc) · 1.78 KB
/
authenticate.js
File metadata and controls
63 lines (57 loc) · 1.78 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
54
55
56
57
58
59
60
61
62
63
const fromEvent = require('graphcool-lib').fromEvent
const bcryptjs = require('bcryptjs')
const userQuery = `
query UserQuery($email: String!) {
User(email: $email){
id
password
}
}`
const getGraphcoolUser = (api, email) => {
return api.request(userQuery, { email })
.then(userQueryResult => {
if (userQueryResult.error) {
return Promise.reject(userQueryResult.error)
} else {
return userQueryResult.User
}
})
}
module.exports = event => {
if (!event.context.graphcool.pat) {
console.log('Please provide a valid root token!')
return { error: 'Email Authentication not configured correctly.'}
}
// Retrieve payload from event
const email = event.data.email
const password = event.data.password
// Create Graphcool API (based on https://github.com/graphcool/graphql-request)
const graphcool = fromEvent(event)
const api = graphcool.api('simple/v1')
return getGraphcoolUser(api, email)
.then(graphcoolUser => {
if (!graphcoolUser) {
return Promise.reject('Invalid Credentials') //returning same generic error so user can't find out what emails are registered.
} else {
return bcryptjs.compare(password, graphcoolUser.password)
.then(passwordCorrect => {
if (passwordCorrect) {
return graphcoolUser.id
} else {
return Promise.reject('Invalid Credentials')
}
})
}
})
.then(graphcoolUserId => {
return graphcool.generateAuthToken(graphcoolUserId, 'User')
})
.then(token => {
return { data: { token } }
})
.catch(error => {
// Log error, but don't expose to caller
console.log(`Error: ${JSON.stringify(error)}`)
return { error: `An unexpected error occured` }
})
}