-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.js
253 lines (201 loc) · 5.87 KB
/
utils.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"use strict";
var debug = require('debug')('app:utils:' + process.pid),
path = require('path'),
util = require('util'),
redis = require("redis"),
client = redis.createClient('6379', process.env.CONTAINER),
_ = require("lodash"),
config = require("./config.json"),
jsonwebtoken = require("jsonwebtoken"),
TOKEN_EXPIRATION = 60,
TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION * 60,
UnauthorizedAccessError = require(path.join(__dirname, 'errors', 'UnauthorizedAccessError.js'));
client.on('error', function (err) {
debug(err);
process.exit(1);
});
client.on('connect', function () {
debug("Redis successfully connected");
});
client.get(this.testKey, function(err,res) {
if(err){
process.exit(1);
}
else{
console.log("hey its conected")
}
});
/**
* Find the authorization headers from the headers in the request
*
* @param headers
* @returns {*}
*/
module.exports.fetch = function (headers) {
if (headers && headers.authorization) {
var authorization = headers.authorization;
var part = authorization.split(' ');
if (part.length === 2) {
var token = part[1];
return part[1];
} else {
return null;
}
} else {
return null;
}
};
/**
* Creates a new token for the user that has been logged in
*
* @param user
* @param req
* @param res
* @param next
*
* @returns {*}
*/
module.exports.create = function (user, req, res, next) {
debug("Create token");
if (_.isEmpty(user)) {
return next(new Error('User data cannot be empty.'));
}
var data = {
_id: user._id,
username: user.username,
access: user.access,
name: user.name,
email: user.email,
token: jsonwebtoken.sign({ _id: user._id }, config.secret, {
expiresInMinutes: TOKEN_EXPIRATION
})
};
var decoded = jsonwebtoken.decode(data.token);
data.token_exp = decoded.exp;
data.token_iat = decoded.iat;
debug("Token generated for user: %s, token: %s", data.username, data.token);
client.set(data.token, JSON.stringify(data), function (err, reply) {
if (err) {
return next(new Error(err));
}
if (reply) {
client.expire(data.token, TOKEN_EXPIRATION_SEC, function (err, reply) {
if (err) {
return next(new Error("Can not set the expire value for the token key"));
}
if (reply) {
req.user = data;
next(); // we have succeeded
} else {
return next(new Error('Expiration not set on redis'));
}
});
}
else {
return next(new Error('Token not set in redis'));
}
});
return data;
};
/**
* Fetch the token from redis for the given key
*
* @param id
* @param done
* @returns {*}
*/
module.exports.retrieve = function (id, done) {
debug("Calling retrieve for token: %s", id);
if (_.isNull(id)) {
return done(new Error("token_invalid"), {
"message": "Invalid token"
});
}
client.get(id, function (err, reply) {
if (err) {
return done(err, {
"message": err
});
}
if (_.isNull(reply)) {
return done(new Error("token_invalid"), {
"message": "Token doesn't exists, are you sure it hasn't expired or been revoked?"
});
} else {
var data = JSON.parse(reply);
debug("User data fetched from redis store for user: %s", data.username);
if (_.isEqual(data.token, id)) {
return done(null, data);
} else {
return done(new Error("token_doesnt_exist"), {
"message": "Token doesn't exists, login into the system so it can generate new token."
});
}
}
});
};
/**
* Verifies that the token supplied in the request is valid, by checking the redis store to see if it's stored there.
*
* @param req
* @param res
* @param next
*/
module.exports.verify = function (req, res, next) {
debug("Verifying token");
var token = exports.fetch(req.headers);
jsonwebtoken.verify(token, config.secret, function (err, decode) {
if (err) {
req.user = undefined;
return next(new UnauthorizedAccessError("invalid_token"));
}
exports.retrieve(token, function (err, data) {
if (err) {
req.user = undefined;
return next(new UnauthorizedAccessError("invalid_token", data));
}
req.user = data;
next();
});
});
};
/**
* Expires the token, so the user can no longer gain access to the system, without logging in again or requesting new token
*
* @param headers
* @returns {boolean}
*/
module.exports.expire = function (headers) {
var token = exports.fetch(headers);
debug("Expiring token: %s", token);
if (token !== null) {
client.expire(token, 0);
}
return token !== null;
};
/**
* Middleware for getting the token into the user
*
* @param req
* @param res
* @param next
*/
module.exports.middleware = function () {
var func = function (req, res, next) {
var token = exports.fetch(req.headers);
exports.retrieve(token, function (err, data) {
if (err) {
req.user = undefined;
return next(new UnauthorizedAccessError("invalid_token", data));
} else {
req.user = _.merge(req.user, data);
next();
}
});
};
func.unless = require("express-unless");
return func;
};
module.exports.TOKEN_EXPIRATION = TOKEN_EXPIRATION;
module.exports.TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION_SEC;
debug("Loaded");