-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhello-server-protected.js
More file actions
100 lines (75 loc) · 2.22 KB
/
hello-server-protected.js
File metadata and controls
100 lines (75 loc) · 2.22 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
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
const debug = require('debug')('hello-server')
const dotenv = require('dotenv').config()
const { expressjwt: jwt } = require('express-jwt')
const express = require('express')
const cors = require('cors')
const api = express()
api.use(cors())
///////////////////
// LOAD ENV VARS
///////////////////
if (dotenv.error) {
throw new Error('LOAD ENV VARS: ' + dotenv.error)
}
if (! "APPROOV_BASE64_SECRET" in dotenv.parsed) {
throw new Error("LOAD ENV VARS: Failed to load APPROOV_BASE64_SECRET. Check it's set in the .env file")
}
const APPROOV_SECRET = Buffer.from(dotenv.parsed.APPROOV_BASE64_SECRET, 'base64')
//////////////////////
// LOGGING CALLBACK
//////////////////////
const logRequest = (req, res, next) => {
debug('<<< ' + req.method + ' ' + req.originalUrl)
req.on('end', () => {
debug('>>> ' + res.statusCode + ' ' + req.method + ' ' + req.originalUrl)
})
next()
}
///////////////////////
// APPROOV CALLBACKS
///////////////////////
// Callback that performs the Approov token check using the express-jwt library
const verifyApproovToken = jwt({
secret: APPROOV_SECRET,
requestProperty: 'approovTokenDecoded',
getToken: function fromApproovTokenHeader(req, res) {
return req.get('Approov-Token')
},
algorithms: ['HS256']
})
// Callback to handle the errors occurred while checking the Approov token.
const approovTokenErrorHandler = (err, req, res, next) => {
// When has an error, it means the header `Approov-Token` is empty, missing or
// have failed validation of signature, expire time or is malformed.
// @see verifyApproovToken()
if (err.name === 'UnauthorizedError') {
debug("---> Approov token error -> " + err)
res.status(401)
res.json({})
return
}
next()
}
////////////////
// MIDDLEWARE
////////////////
api.use(logRequest)
// Middleware to handle the validation of the Approov token.
api.use(verifyApproovToken)
api.use(approovTokenErrorHandler)
////////////////
// ENDPOINTS
////////////////
// simple 'hello world' endpoint.
api.get('/', function (req, res, next) {
res.json({
message: "Hello, World!",
})
})
////////////
// SERVER
////////////
// Create and run the HTTP server
api.listen(8002, function () {
debug("Server listening on %s", "localhost")
})