-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
218 lines (189 loc) · 6.02 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
import ViteExpress from 'vite-express'
import { createLightship } from 'lightship'
import express from 'express'
import { getReasonPhrase } from 'http-status-codes'
import proxy from 'express-http-proxy'
import dotenv from 'dotenv'
import cache from 'memory-cache'
import bodyParser from 'body-parser'
if (!process.env.DAPLA_TEAM_API_URL) {
dotenv.config({ path: './.env.local' })
}
const app = express()
const PORT = process.env.PORT || 3000
const DAPLA_TEAM_API_URL = process.env.DAPLA_TEAM_API_URL || 'https://dapla-team-api.intern.test.ssb.no'
app.use(
'/klass',
proxy('https://data.ssb.no/api/klass/v1', {
proxyReqPathResolver: (req) => {
return '/api/klass/v1' + req.url
},
userResDecorator: function (proxyRes, proxyResData, userReq, userRes) {
console.log('Response Status:', proxyRes.statusCode)
console.log('Response Headers:', proxyRes.headers)
console.log('User Request Headers:', userReq.headers)
if (userRes.body) {
console.log('User Response:', userRes.body)
}
return proxyResData
},
})
)
app.post('/log', bodyParser.text({ type: '*/*' }), (req, res) => {
console.log(req.body)
res.send('Ok')
})
app.use(
'/api',
proxy(DAPLA_TEAM_API_URL, {
proxyReqBodyDecorator: function (bodyContent) {
console.log(`Request Body: ${bodyContent}`)
return bodyContent
},
proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
const headers = srcReq.headers
delete headers['authorization']
console.log(`Request Headers:`, headers)
if (srcReq.body) {
console.log(`Request Body:`, srcReq.body)
}
return proxyReqOpts
},
proxyReqPathResolver: function (req) {
const newPath = req.originalUrl.replace(/^\/api/, '')
console.log(`Forwarding to: ${DAPLA_TEAM_API_URL}${newPath}`)
return newPath
},
userResDecorator: function (proxyRes, proxyResData) {
console.log(`Response Status: ${proxyRes.statusCode}`)
console.log(`Response Headers:`, proxyRes.headers)
return proxyResData
},
proxyErrorHandler: function (err, res) {
console.error('Proxy Error:', err)
res.status(500).send('Proxy Error')
},
})
)
app.use(express.json())
// DO NOT REMOVE, NECCESSARY FOR FRONTEND
app.get('/localApi/photo/:principalName', async (req, res, next) => {
const accessToken = req.headers.authorization.split(' ')[1]
const principalName = req.params.principalName
const userPhotoUrl = `${DAPLA_TEAM_API_URL}/users/${principalName}/photo`
try {
const photoData = await fetchPhoto(accessToken, userPhotoUrl, 'could not fetch photo')
return res.send({ photo: photoData })
} catch (error) {
next(error)
}
})
app.get('/localApi/users', async (req, res) => {
const cacheKey = 'usersForSearch'
const cachedData = cache.get(cacheKey)
const token = req.headers.authorization
const usersUrl = new URL(`${DAPLA_TEAM_API_URL}/users`)
const selects = ['display_name', 'principal_name', 'section_name']
usersUrl.searchParams.append('select', selects.join(','))
if (cachedData) {
res.json(cachedData)
} else {
try {
const response = await fetch(usersUrl.toString(), {
method: 'GET',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: token,
},
})
if (!response.ok) {
const err = await response.text()
res.status(response.status).send(err)
} else {
const data = await response.json()
cache.put(cacheKey, data, 3600000)
res.status(response.status).send(data)
}
} catch (error) {
console.log(error)
res.status(500).send('Internal Server Error')
}
}
})
async function fetchPhoto(accessToken, url, fallbackErrorMessage) {
const response = await fetch(url, getFetchOptions(accessToken))
if (!response.ok) {
throw new Error(fallbackErrorMessage)
}
const arrayBuffer = await response.arrayBuffer()
const photoBuffer = Buffer.from(arrayBuffer)
return photoBuffer.toString('base64')
}
//TODO: Remove me once DELETE with proxy is fixed
app.delete('/localApi/groups/:groupUniformName/:userPrincipalName', async (req, res) => {
const token = req.headers.authorization
const groupUniformName = req.params.groupUniformName
const userPrincipalName = req.params.userPrincipalName
const groupsUrl = `${DAPLA_TEAM_API_URL}/groups/${groupUniformName}/users`
try {
const response = await fetch(groupsUrl, {
method: 'DELETE',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: token,
},
body: JSON.stringify({
users: [userPrincipalName],
}),
})
if (!response.ok) {
const err = await response.text()
res.status(response.status).send(err)
} else {
const data = await response.json()
res.status(response.status).send(data)
}
} catch (error) {
console.log(error)
res.status(500).send('Internal Server Error')
}
})
app.get('/localApi/fetch-token', (req, res) => {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer')) {
return res.status(401).json({ message: 'No token provided' })
}
const token = req.headers.authorization.split('Bearer ')[1]
res.json({ token })
})
function getFetchOptions(token) {
return {
method: 'GET',
headers: {
accept: '*/*',
Authorization: `Bearer ${token}`,
},
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500
return res.status(statusCode).json({
success: false,
error: {
code: getReasonPhrase(statusCode),
message: err.message,
},
})
})
const lightship = await createLightship()
ViteExpress.listen(app, PORT, () => {
lightship.signalReady()
console.log(`Server is listening on port ${PORT} ... ${process.env.NODE_ENV}`)
}).on('error', () => {
lightship.shutdown()
})
lightship.registerShutdownHandler(async () => {
console.log('Server is shutting down...')
})