-
Notifications
You must be signed in to change notification settings - Fork 3
/
routes.js
189 lines (175 loc) · 5.96 KB
/
routes.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict'
let https = require('https')
let config = require('./config.js')
let mongoose = require('mongoose')
let querystring = require('querystring')
let User = mongoose.model('User')
let Survey = mongoose.model('Survey')
mongoose.Promise = require('bluebird')
let ajaxResponse = JSON.stringify({
'success': true,
'emailValid': true,
'githubValid': true,
'errorMessage': ''
})
module.exports = (app, logger) => {
// The main page
app.get('/', (req, res) => {
res.render('index.html', {
'title': 'Join',
'css': ['css/normalize.css', 'css/skeleton.css', 'css/style.css'],
'javascripts': ['javascripts/jquery-1.12.0.min.js', 'javascripts/index.js']
})
})
// The form API call
app.post('/join', (req, res, next) => {
// Github actions
logger.info('Request body', req.body)
let response = JSON.parse(ajaxResponse) // Get a copy
let githubUsername = req.body.githubUsername
if (githubUsername === '') {
next()
return
}
addToTeam(githubUsername, (err, statusCode) => {
if (err) {
logger.error(`Github request error: ${err}`)
response.success = false
response.githubValid = false
response.errorMessage = 'Github error'
res.status(500).json(response)
} else if (statusCode === 404) {
// Username could not be found
response.success = false
response.githubValid = false
response.errorMessage = 'Github username could not be found'
logger.info(response.errorMessage)
res.status(400).json(response)
} else if (statusCode === 200) {
logger.info('Successfully invited user to GitHub')
next() // Move to saving in Mongo
} else {
// if api sends back anything other than 200 or 404, something must be wrong with our server or Github's API
logger.error(`Github API responded with ${statusCode}`)
response.success = false
response.githubValid = false
response.errorMessage = 'Github API error'
res.status(500).json(response)
}
})
}, (req, res, next) => {
// Database actions w/ Mongoose
let response = JSON.parse(ajaxResponse) // Get a copy
let body = req.body
let userObj = {
firstName: body.firstName,
lastName: body.lastName,
studentId: body.studentId,
email: body.email,
mailchimp: !!body.mailchimp, // Convert to boolean if not already
github: body.githubUsername
}
// Search for the user email.
// Email exists? Update
// Email original? Create new using upsert
User.findOneAndUpdate({email: userObj.email}, userObj, {upsert: true, new: true}).exec().then((user) => {
if (!user.submittedSurvey) {
return new Survey({
'experience': body.experience,
'interests': body.interests,
'more-interests': body['more-interests'],
'projects': body.projects,
'more-projects': body['more-projects'],
'events': body.events,
'more-events': body['more-events']
}).save().then((survey) => {
user.description = survey
user.submittedSurvey = true
return user.save()
})
} else {
logger.info('Updated existing user in MongoDB')
}
}).then((user) => {
// Successful save
logger.info('Successfully saved user in MongoDB')
next() // Move to addToSlack
}, (err) => {
// Most likely validation error
logger.error(`MongoDB: ${err.name}: ${err.message}`)
response.success = false
response.errorMessage = Object.keys(err.errors).map((key) => err.errors[key].message).join(' ')
res.status(400).json(response)
})
}, (req, res, next) => {
// Slack actions
let response = JSON.parse(ajaxResponse) // Get a copy
addToSlack(req.body.email, (err, statusCode, invited) => {
response.slackSuccess = !err && statusCode === 200
response.slackInvited = invited
res.status(statusCode).json(response)
})
})
let addToTeam = (githubUsername, cb) => {
// sends and invite to the passed username to join the "developer" team
// (error, statusCode) is passed to callback function
let options = {
hostname: 'api.github.com',
// Make sure that GITHUB_API_KEY is set before running server
path: `/teams/1679886/memberships/${githubUsername}?access_token=${config.github.apiKey}`,
method: 'PUT',
headers: {
'User-Agent': config.github.userAgent
}
}
let ghReq = https.request(options, (ghRes) => {
cb(null, ghRes.statusCode)
})
ghReq.on('error', (e) => {
cb(e, 500)
})
ghReq.end()
}
let addToSlack = (email, cb) => {
// sends an invite to join the dvcoders slack channel
// (error, statusCode, invited) is passed to the callback, but note that
// slack sends a 200 even if the user has already been invited.
// also note this api endpoint is "undocumented" and subject to change
let data = querystring.stringify({
email: email,
token: config.slack.token,
set_active: true
})
let options = {
hostname: 'dvcoders.slack.com',
path: '/api/users.admin.invite',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
}
let req = https.request(options, (res) => {
let body = ''
res.setEncoding('utf8')
res.on('data', (d) => {
body += d
})
res.on('end', () => {
let resBody = JSON.parse(body)
logger.info('Slack response:', res.statusCode, resBody)
if (res.statusCode === 200 && !resBody.ok && (resBody.error === 'already_invited' || resBody.error === 'already_in_team')) {
cb(null, 200, true)
} else {
cb(null, res.statusCode, false)
}
})
})
req.on('error', (err) => {
logger.error(`Slack request error: ${err}`)
cb(err, 500, false)
})
req.write(data)
req.end()
}
}