-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (73 loc) · 1.96 KB
/
index.js
File metadata and controls
76 lines (73 loc) · 1.96 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
'use strict';
const HydraExpressPlugin = require('hydra-express-plugin');
const jwtAuth = require('jwt-simple-auth');
/**
* @name JWTAuthPlugin
* @summary HydraExpressPlugin for JWT auth
* @extends HydraExpressPlugin
*/
class JWTAuthPlugin extends HydraExpressPlugin {
constructor() {
super('jwt-auth');
}
/**
* @override
*/
setHydraExpress(hydraExpress) {
super.setHydraExpress(hydraExpress);
hydraExpress.validateJwtToken = () => this.getMiddleware();
hydraExpress.getJwtAuth = () => jwtAuth;
}
/**
* @override
*/
setConfig(serviceConfig) {
super.setConfig(serviceConfig);
jwtAuth.loadCerts(null, serviceConfig.jwtPublicCert);
}
/**
* @override
*/
onServiceReady() { /*noop*/ }
/**
* @name getMiddleware
* @summary Express middleware to validate a JWT sent via the req.authorization header
* @return {function} Middleware function
*/
getMiddleware() {
const ServerResponse = this.hydraExpress.getHydra().getServerResponseHelper();
return (req, res, next) => {
let authHeader = req.headers.authorization;
if (!authHeader) {
this.hydraExpress.sendResponse(ServerResponse.HTTP_UNAUTHORIZED, res, {
result: {
reason: 'Invalid token'
}
});
} else {
let token = authHeader.split(' ')[1];
if (token) {
return jwtAuth.verifyToken(token)
.then((decoded) => {
req.authToken = decoded;
next();
})
.catch((err) => {
this.hydraExpress.sendResponse(ServerResponse.HTTP_UNAUTHORIZED, res, {
result: {
reason: err.message
}
});
});
} else {
this.hydraExpress.sendResponse(ServerResponse.HTTP_UNAUTHORIZED, res, {
result: {
reason: 'Invalid token'
}
});
}
}
};
}
}
module.exports = JWTAuthPlugin;