-
Notifications
You must be signed in to change notification settings - Fork 0
/
signup.js
76 lines (70 loc) · 2.01 KB
/
signup.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
const fromEvent = require('graphcool-lib').fromEvent
const bcrypt = require('bcryptjs')
const validator = require('validator')
function getGraphcoolUser(api, email) {
return api.request(`
query {
User(email: "${email}") {
id
}
}`)
.then((userQueryResult) => {
if (userQueryResult.error) {
return Promise.reject(userQueryResult.error)
} else {
return userQueryResult.User
}
})
}
function createGraphcoolUser(api, email, passwordHash, admin) {
return api.request(`
mutation {
createUser(
email: "${email}",
password: "${passwordHash}",
role: ${admin ? 'ADMIN' : 'CUSTOMER'}
) {
id
}
}`)
.then((userMutationResult) => {
return userMutationResult.createUser.id
})
}
module.exports = function(event) {
if (!event.context.graphcool.pat) {
console.log('Please provide a valid root token!')
return { error: 'Email Signup not configured correctly.'}
}
const email = event.data.email
const password = event.data.password
const admin = event.data.admin || false
const graphcool = fromEvent(event)
const api = graphcool.api('simple/v1')
const SALT_ROUNDS = 10
const salt = bcrypt.genSaltSync(SALT_ROUNDS)
if (validator.isEmail(email)) {
return getGraphcoolUser(api, email)
.then(graphcoolUser => {
if (graphcoolUser === null) {
return bcrypt.hash(password, salt)
.then(hash => createGraphcoolUser(api, email, hash, admin))
} else {
return Promise.reject("Email already in use")
}
})
.then(graphcoolUserId => {
return graphcool.generateAuthToken(graphcoolUserId, 'User')
.then(token => {
return { data: {id: graphcoolUserId, token}}
})
})
.catch((error) => {
console.log(error)
// don't expose error message to client!
return { error: 'An unexpected error occured.' }
})
} else {
return { error: "Not a valid email" }
}
}