-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
185 lines (168 loc) · 4.72 KB
/
server.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
require('dotenv').config()
const express = require('express')
const app = express()
const axios = require('axios')
const path = require('path')
const crypto = require('crypto')
const { execSync } = require('child_process')
const bodyParser = require('body-parser')
const createMail = require('./createmail')
const urlcrypt = require('url-crypt')(
'~{ry*I)44==yU/]9<7DPk!Hj"R#:-/Z7(hTBnlRS=4CXF'
)
const sgMail = require('@sendgrid/mail')
const {
glitch,
slack,
webhookURL,
token,
selfEmail,
codes
} = require('./constants')
app.use(bodyParser.json())
sgMail.setApiKey(process.env.SG_TOKEN)
// Auto-update Glitch with GitHub
app.post('/git', (req, res) => {
const hmac = crypto.createHmac('sha1', glitch)
const sig = `sha1=${hmac.update(JSON.stringify(req.body)).digest('hex')}`
if (
req.headers['x-github-event'] === 'push' &&
crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(req.headers['x-hub-signature'])
)
) {
res.sendStatus(200)
const commands = [
'git fetch origin master',
'git reset --hard origin/master',
'git pull origin master --force',
'npm i',
'refresh'
]
for (const cmd of commands) {
try {
const o = execSync(cmd)
console.log(o.toString())
} catch (e) {
console.log(e)
}
}
console.log('> [GIT] Updated with origin/master')
} else {
console.log('webhook signature incorrect!')
return res.sendStatus(403)
}
})
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/views/index.html'))
})
// Send the mail to the given email
app.get('/sendmail/:username/:id', (req, res, next) => {
const { username, id } = req.params
const base64 = urlcrypt.cryptObj({
email: id,
username: username
})
// Invite to Slack
const slackUrl = `https://slack.com/api/users.admin.invite?token=${slack}&email=${id}`
axios.post(slackUrl)
// Post invitation message on Slack
const time = Math.round(new Date().getTime() / 1000)
const message = `${username} got invited to Flutter Club organization on GitHub and Slack`
const options = {
text: 'Welcome to Flutter Club',
attachments: [
{
color: '#36a64f',
title: 'Invitation from Flutter Club',
title_link: 'https://github.com/orgs/FlutterClub/people',
text: message,
footer: 'Slack API',
ts: time
}
]
}
const sendMessage = () => {
return new Promise((resolve, reject) => {
axios
.post(webhookURL, JSON.stringify(options))
.then(response => {
return resolve('SUCCESS: Sent slack webhook', response.data)
})
.catch(error => {
return reject(new Error('FAILED: Sent slack webhook', error))
})
})
}
const loop = async () => {
for (let i = 0; i < 3; i++) {
console.log('retrying sending message ', i)
try {
const res = await sendMessage()
console.log(res)
break
} catch (err) {
console.log(err)
}
}
}
loop()
const verificationurl = `https://${req.get('host')}/verify/${base64}`
const msg = {
from: selfEmail,
bcc: selfEmail,
to: id,
subject: 'Invitation to join Flutter Club Team',
html: createMail.createMail(username, verificationurl)
}
sgMail.send(msg)
})
// Verify the email id through the link, and add as member
app.get('/verify/:base64', (request, response, next) => {
const encryptedData = request.params.base64
try {
const data = urlcrypt.decryptObj(encryptedData)
addMember(data)
.then(status => {
response.status(status)
response.redirect('https://github.com/orgs/FlutterClub/teams')
})
.catch(err => {
console.log(err)
response.status(400).send('Error occured. Please try again later.')
response.end()
})
} catch (e) {
response.status(400).send('Invalid Link.')
}
})
// Add the member as per their email id
const addMember = data => {
const { email, username } = data
const regex = /^20\d{7}@thapar?edu$/; // eslint-disable-line
const promise = new Promise((resolve, reject) => {
let pref = 'outsiders'
if (regex.test(email)) {
pref = parseInt(email.substring(0, 4)) + 4
console.log('Thaparian')
}
console.log(pref)
const url = `https://api.github.com/teams/${codes[pref]}/memberships/${username}?access_token=${token}`
console.log(url)
axios
.put(url)
.then(res => {
console.log(res.data.url)
resolve(200)
})
.catch(error => {
reject(error)
})
})
return promise
}
const listener = app.listen(3000 || process.env.PORT, () => {
console.log(`Your app is listening on port ${listener.address().port}`)
})