forked from TheCacophonyProject/cacophony-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
passportConfig.js
79 lines (73 loc) · 1.81 KB
/
passportConfig.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
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var AnonymousStrategy = require('passport-anonymous');
var models = require('./models');
var config = require('./config/config');
module.exports = function(passport) {
passport.use(new AnonymousStrategy());
var opts = {
jwtFromRequest: getJWT,
secretOrKey: config.server.passportSecret,
};
function getJWT(request) {
if (request.query.jwt)
return ExtractJwt.fromUrlQueryParameter('jwt')(request);
else
return ExtractJwt.fromAuthHeader()(request);
}
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
if (!jwt_payload._type) {
return done("No 'type' field in JWT.", false);
}
switch (jwt_payload._type) {
case 'user':
validateUser(jwt_payload, done);
break;
case 'device':
validateDevice(jwt_payload, done);
break;
case 'fileDownload':
validateFileDownload(jwt_payload, done);
break;
default:
return done("Unknown field type: " + jwt_payload._type, false);
}
}));
};
function validateUser(jwt_payload, done) {
models.User.findOne({
where: {
id: jwt_payload.id
}
})
.then(function(user) {
if (user) {
done(null, user);
} else {
done(null, false);
}
})
.catch(function(err) {
return done(err, false);
});
}
function validateDevice(jwt_payload, done) {
models.Device.findOne({
where: {
id: jwt_payload.id
}
})
.then(function(device) {
if (device) {
done(null, device);
} else {
done(null, false);
}
})
.catch(function(err) {
return done(err, false);
});
}
function validateFileDownload(jwt_payload, done) {
done(null, jwt_payload);
}