This repository has been archived by the owner on Aug 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.js
117 lines (97 loc) · 3.36 KB
/
jwt.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
const debug = require('debug')('loopback:jwt');
const expressJwt = require('express-jwt');
const Promise = require('bluebird');
const loopbackUser = require('./loopbackUser');
const extend = require('xtend');
const Profile = require('./profile');
const assert = require('assert');
const ManagementClient = require('auth0').ManagementClient;
class LoopbackJwt extends loopbackUser {
constructor(options) {
super(options);
assert(options, 'Options must be defined');
assert(options.secretKey, 'Options.secretKey must be defined');
assert(options.password, 'Options.password must be defined');
this.options = {
secretKey: '',
credentialsRequired: false,
algorithms: ['RS256', 'HS256'],
beforeCreate: null,
};
this.userMap = {};
this.options = extend(this.options, options);
this.jwtCheck = expressJwt({
algorithms: this.options.algorithms,
secret: this.options.secretKey,
credentialsRequired: false,
getToken: options.getToken,
});
this.management = new ManagementClient({
token: this.options.managementConfig.token,
domain: this.options.domain,
});
}
parseTokenFromQueryString(req, res, next) {
const accessToken = req.query.access_token;
if (accessToken) {
delete req.query.access_token;
req.headers.authorization = 'Bearer ' + accessToken;
debug(
'parseTokenFromQueryString',
'found token in query string. attached to headers'
);
}
next();
};
getUserInformation(req, res, next) {
if (!req.user) {
debug('no current user context found.');
return next();
}
let that = this;
this.management.users.get({
id: req.user.sub,
}, function (err, user) {
req.user = new Profile(user, that.options.userModel);
next();
});
}
mapUser(req, res, next) {
if (!req.user) {
debug('no current user context found.');
return next();
}
this.user = req.user;
debug('attempting to map user [%s]', this.user.email);
const token = this.userMap[this.user.email];
if (!token) {
this.loginUser()
.then(token => {
debug('mapped existing user [%s]', token.id);
this.userMap[this.user.email] = token;
req.accessToken = token;
next();
})
.catch((e) => {
debug('login error', e);
this.createUser(req)
.then(token => {
this.userMap[this.user.email] = token;
req.accessToken = token;
next();
})
.catch(e => {
debug('Error while creating error', e);
next();
});
});
} else {
debug('found existing token [%s]', token.id);
req.accessToken = token;
next();
}
}
}
module.exports = (options) => {
return new LoopbackJwt(options);
};