This repository was archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
194 lines (181 loc) · 6.8 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
import { sign as jwtSign, verify as jwtVerify } from 'jsonwebtoken'
import express from 'express'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import morgan from 'morgan'
import ms from 'ms'
import next from 'next'
import uuidV4 from 'uuid/v4'
import fetch from 'isomorphic-fetch'
import { apiHost, currentHost, loginHost } from 'gg-common/utils/hosts'
const allowedHosts = [currentHost]
const proto = process.env.BASE_HOST.endsWith('.local') ? 'http' : 'https'
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
const JWT_LENGTH = '12h'
const JWT_COOKIE_LENGTH = (ms(JWT_LENGTH) - 30000)
app.prepare().then(() => {
const server = express()
server.disable('x-powered-by')
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({
extended: true
}))
server.use(cookieParser())
server.use(morgan('combined'))
server.get('/_youtube/oauth', (req, res) => {
if (!(req.query && req.query.code)) {
console.log('No code, redirecting to /youtube')
res.redirect('/youtube')
} else if (!(req.cookies && req.cookies.jwt)) {
console.log('Received code while not logged in', req.query.code)
res.redirect(proto + '://' + loginHost())
} else {
console.log('Handling code', req.query.code)
jwtVerify(req.cookies.jwt, 'GGUiSecret', (err, decoded) => {
if (!err && decoded.sub && decoded.sub === ('' + parseInt(decoded.sub, 10)) && decoded.iss && decoded.iss === (proto + '://' + currentHost)) {
console.log('Token verified, sending request to API')
fetch(proto + '://' + apiHost() + '/youtube/auth', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + req.cookies.jwt,
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
code: req.query.code
})
})
.then(fetchResponse => {
console.log('Response from API', fetchResponse)
res.redirect('/youtube')
})
} else {
console.log('Received code but token was invalid')
res.redirect(proto + '://' + loginHost())
}
})
}
})
server.get('/logout', (req, res) => {
if (!req.headers || !req.headers.host || allowedHosts.indexOf(req.headers.host) < 0) {
console.log('Invalid host header, redirecting to login')
res.redirect(proto + '://' + loginHost())
} else {
res.writeHead(302, {
'Cache-Control': 'no-cache, no-store, must-revalidate',
Pragma: 'no-cache',
Expires: 0,
'Set-Cookie':
'jwt=; ' +
'Domain=.' + req.headers.host + '; ' +
(proto === 'https' ? 'Secure; ' : '') +
'Expires=Thu, 01 Jan 1970 00:00:00 GMT; ' +
'Version=1',
Location: '/'
})
res.end()
}
})
server.get('/auth', (req, res) => {
if (!req.headers || !req.headers.host || allowedHosts.indexOf(req.headers.host) < 0) {
console.log('Invalid host header, redirecting to login')
res.redirect(proto + '://' + loginHost())
} else if (!(req.query && req.query.token)) {
console.log('No token, redirecting to /')
res.redirect('/')
} else {
console.log('Verifying auth token')
jwtVerify(req.query.token, 'GGAuthSecret', (err, decoded) => {
if (!err && decoded.sub && decoded.sub === ('' + parseInt(decoded.sub, 10)) && decoded.aud && decoded.aud.length > 0 && decoded.aud.indexOf(proto + '://' + currentHost) > -1) {
const uuid = uuidV4()
const issuer = proto + '://' + currentHost
const audience = [proto + '://' + apiHost()]
console.log('Valid auth token, signing UI token')
jwtSign(
{
tk: decoded.jti
},
'GGUiSecret',
{
algorithm: 'HS512',
audience,
issuer,
jwtid: uuid,
subject: decoded.sub,
expiresIn: JWT_LENGTH
},
(error, token) => {
if (error) {
console.log('JWT error: ', error)
res.status(400)
res.send('Failed to generate access token')
} else {
fetch(proto + '://' + apiHost() + '/claim', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
credentials: 'include'
})
.then(fetchResponse => {
if (fetchResponse.ok) {
res.writeHead(302, {
'Cache-Control': 'no-cache, no-store, must-revalidate',
Pragma: 'no-cache',
Expires: 0,
'Set-Cookie':
'jwt=' + encodeURIComponent(token) + '; ' +
'Domain=.' + req.headers.host + '; ' +
(proto === 'https' ? 'Secure; ' : '') +
'Expires=' + (new Date(Date.now() + JWT_COOKIE_LENGTH)).toUTCString() + '; ' +
'Version=1',
Location: '/'
})
res.end()
} else {
fetchResponse.text().then(text => {
console.log('Redirecting to login after bad response from claim: ', text)
res.redirect(proto + '://' + loginHost())
})
}
})
.catch(error => {
console.log('Redirecting to login after error fetching claim: ', error)
res.redirect(proto + '://' + loginHost())
})
}
}
)
} else {
console.log('Invalid auth token, redirecting to login')
res.redirect(proto + '://' + loginHost())
}
})
}
})
server.get('*', (req, res) => {
if (req.originalUrl.startsWith('/_next')) {
return handle(req, res)
} else if (!(req.cookies && req.cookies.jwt)) {
res.redirect(proto + '://' + loginHost())
} else {
jwtVerify(req.cookies.jwt, 'GGUiSecret', (err, decoded) => {
if (!err && decoded.sub && decoded.sub === ('' + parseInt(decoded.sub, 10)) && decoded.iss && decoded.iss === (proto + '://' + currentHost)) {
return handle(req, res)
} else {
console.log('Bad token, redirecting to login')
res.redirect(proto + '://' + loginHost())
}
})
}
})
server.listen(80, (err) => {
if (err) {
throw err
}
console.log('> Ready at http://' + process.env.HOST)
})
})