forked from ifavo/ah-jwtauth-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
jwtauth_middleware.js
83 lines (67 loc) · 2.63 KB
/
jwtauth_middleware.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
var jsonwebtoken = require('jsonwebtoken');
module.exports = {
initialize: function(api, next) {
var jwtMiddleware = {
name: 'jwt token validator',
global: true,
preProcessor: function(data, next) {
// is it required to have a valid token to access an action?
var tokenRequired = false;
if (data.actionTemplate.authenticate && api.config.jwtauth.enabled[data.connection.type]) {
tokenRequired = true;
}
// get request data from the required sources
var token = '';
var req = {
headers: data.params.httpHeaders || (data.connection.rawConnection.req ? data.connection.rawConnection.req.headers : undefined) || data.connection.mockHeaders || {},
uri: data.connection.rawConnection.req ? data.connection.rawConnection.req.uri : {}
};
var authHeader = req.headers.authorization || req.headers.Authorization || false;
// extract token from http headers
if (authHeader) {
var parts = authHeader.split(' ');
if (parts.length != 2 || parts[0].toLowerCase() !== 'token') {
// return error if token was required and missing
if ( tokenRequired ) {
return next({
code: 500,
message: 'Invalid Authorization Header'
});
}
else {
return next();
}
}
token = parts[1];
}
// if GET parameter for tokens is allowed, use it
if (!token && api.config.jwtauth.enableGet && req.uri.query && req.uri.query.token) {
token = req.uri.query.token;
}
// return error if token was missing but marked as required
if (tokenRequired && !token) {
return next({
code: 500,
message: 'Authorization Header Not Set'
});
}
// process token and save in connection
else if (token) {
api.jwtauth.processToken(token, function(tokenData) {
data.connection._jwtToken = token;
data.connection._jwtTokenData = tokenData;
next();
}, next);
}
else {
return next();
}
},
stop: function(api, next) {
next();
}
}
api.actions.addMiddleware(jwtMiddleware);
next();
}
};