-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
219 lines (181 loc) · 5.41 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
const express = require('express')
const scrape_members = require('./scrape.js')
const sendy_sync = require('./sendy')
const fs = require('fs')
const fsAsync = require('fs').promises
const { DateTime } = require('luxon')
// authentication
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const session = require('express-session')
// some secrets
const readJSON = file => JSON.parse(fs.readFileSync(file))
const config = readJSON('./instance/config.json')
const secrets = readJSON('./instance/secret.json')
/* --- API SUB-APPLICATION --- */
const api_app = express()
const cachefile = config.cachefile
const port = config.port
const orgID = config.orgID
const groupID = config.groupID
const apikey = secrets.apikey
const apiAuthenticationMiddleware = (req, res, next) => {
const expected_header = `Bearer ${apikey}`
if (!req.headers.authorization || req.headers.authorization !== expected_header) {
res
.status(401)
.send({
status: 'authentication failure',
success: false
})
} else {
next()
}
}
api_app.use(apiAuthenticationMiddleware)
const writeScrape = async () => {
const members = await scrape_members({
orgID,
groupID,
auth: {
email: secrets.email,
password: secrets.password
}
})
const out = {
members: members,
date: new Date().toISOString()
}
await fsAsync.writeFile(
cachefile,
JSON.stringify(out)
)
return out
}
const readScrape = async () => JSON.parse(await fsAsync.readFile(cachefile))
api_app.get('/members', async (req, res) => {
try {
res.json({ success: true, ...(await readScrape())})
} catch(e) {
res.json({ success: false, status:e.toString()})
}
})
api_app.get('/refresh', async (req, res) => {
try{
res.json({ success: true, ...(await writeScrape())})
} catch(e) {
res.json({ success: false, status:e.toString()})
}
})
api_app.get('/sendy_sync', async (req, res) => {
try {
const subscribed = await sendy_sync((await readScrape()).members, secrets.sendy)
res.json({ success: true })
} catch (e) {
res.json({ success: false, status: 'An error occurred.' })
}
})
/* --- FRONTEND --- */
const app = express()
app.set('view engine', 'ejs')
app.use('/static', express.static('static'))
app.use(session({ secret: 'anything', resave: false, saveUninitialized: false }));
// google auth plumbing
app.use(passport.initialize())
app.use(passport.session());
passport.use(
new GoogleStrategy({
clientID: secrets.google.client_id,
clientSecret: secrets.google.client_secret,
callbackURL: secrets.google.callback
},
(access_token, refresh_token, profile, cb) => {
// simplify profile response
let lensed = profile => ({
id: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
email_verified: profile.emails[0].verified,
photo: profile.photos[0]?.value
})
cb(null, lensed(profile))
})
)
// serialize the profile directly into the session (d i r t y)
passport.serializeUser((user, done) => done(null, JSON.stringify(user)))
passport.deserializeUser((user, done) => done(null, JSON.parse(user)))
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', {failureRedirect: '/auth/failed'}),
(req, res) => {
// successful authentication
res.redirect('/dashboard')
}
)
app.get('/auth/failed', (req, res) => {
res.send('auth failed!')
})
app.get('/auth/logout', (req, res) => {
req.logout()
res.redirect('/')
})
const login_guard = (req, res, next) => {
if (!req.user) {
res.redirect('/')
} else {
next()
}
}
// homepage
app.get('/', (req, res) => {
res.render('index')
})
// dashboard
app.get('/dashboard',
login_guard,
async (req, res) => {
const latest = await readScrape()
const makecsv = members => {
const data = members.map(
m => `${m.name.first},${m.name.last},${m.student},s${m.student}@ed.ac.uk,${m.joined},${m.expires}`
).join('\n')
return `First,Last,StudentNo,Email,Joined,Expires\n` + data
}
res.render('dash', {
latest,
csv: makecsv(latest.members),
render_time: new Date().toISOString(),
sendy: {
url: secrets.sendy.sendy_url,
list: secrets.sendy.target_list
},
apikey: apikey,
user: req.user
})
}
)
app.get('/dashboard/rescrape',
login_guard,
(req, res) => {
res.render('rescrape', {
apikey,
user: req.user
})
}
)
app.get('/dashboard/sendy_sync',
login_guard,
(req, res) => {
res.render('sendy_sync', {
apikey,
user: req.user
})
}
)
// mount the api application
app.use('/api', api_app)
console.log('getting initial scrape...')
//const dummy = async () => {} // useful for debugging
writeScrape()
.then(() => app.listen(port, () => console.log(`EUSA members api listening on port ${port}!`)))