-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
60 lines (48 loc) · 1.59 KB
/
Copy pathindex.js
File metadata and controls
60 lines (48 loc) · 1.59 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
require('./load-env.js')
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const { parse } = require('node:url')
const { getCognitoTokensFromCodeUrlQuery, isAuthorized } = require('./utils/cognito.js')
const WebServer = require('./WebServer.js')
const webServer = new WebServer()
const serveLandingPage = (req, res) => {
const landingPage = readFileSync(join(__dirname, 'index.html'), 'utf8')
res
.writeHead(200, {
'Content-Length': Buffer.byteLength(landingPage),
'Content-Type': 'text/html',
})
.end(landingPage)
}
webServer
.initialize()
.addRoute('GET', '/', async (req, res) => {
const url = parse(req.url, process.env.HOST)
const { accessToken } = url.query
if (!(await isAuthorized(accessToken))) {
const message = 'Unauthorized'
return res.writeHead(404, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(message)
}).end(message)
}
serveLandingPage(req, res)
})
.addRoute('GET', '/cognito', async (req, res) => {
try {
const { access_token } = await getCognitoTokensFromCodeUrlQuery(req, res)
res.statusCode = 301
res.setHeader('Location', `/?accessToken=${access_token}`)
res.end()
} catch (error) {
if (error.message === 'Invalid JWT tokens') {
return res.writeHead(404, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(error.message)
}).end(error.message)
}
console.error(error)
res.writeHead(500).end()
}
})
.listen(80)