-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathauth.js
62 lines (49 loc) · 1.33 KB
/
auth.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
var jwt = require('jsonwebtoken');
var config = require('./configurations/config');
var authAPI = function(req, res, next){
// check header or url parameters or post parameters for token
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.jwtSecret, function(err, decoded) {
if (err) {
return res.status(403).json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'Not Authenticated'
});
}
};
var authSocket = function(socket, next){
var { token } = socket.handshake.query;
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.jwtSecret, function(err, decoded) {
if (err) {
return next(err);
} else {
// set user to decoded token
// for use throughout app
socket.user = decoded;
next(null);
}
});
} else {
// if there is no token
// return an error
return next('Not Authenticated')
}
};
module.exports.authAPI = authAPI;
module.exports.authSocket = authSocket;