-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtoken-auth.js
79 lines (68 loc) · 2.19 KB
/
token-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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const jwt = require('jsonwebtoken');
const passport = require("passport");
const passportJWT = require("passport-jwt");
const nameGenerator = require('project-name-generator');
const ApiToken = require("./model/api-token");
const config = require("./config");
const jwtOptions = {
jwtFromRequest: passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.JWT_SECRET,
ignoreExpiration: true
};
function createToken(name) {
return ApiToken.exists({name: name})
.then((tokenExists) => {
if (tokenExists === false) {
// create new token
const token = jwt.sign({name: name}, jwtOptions.secretOrKey);
return ApiToken.Model.create({
name: name,
token: token
})
}
})
}
function init() {
// create default token
if (config.DEFAULT_TOKEN_NAME != null)
createToken(config.DEFAULT_TOKEN_NAME);
// create strategy for validating tokens
const strategy = new passportJWT.Strategy(jwtOptions, function (jwt_payload, next) {
ApiToken.exists({name: jwt_payload.name})
.then((tokenExists) => {
if (tokenExists)
next(null, jwt_payload);
else
next(null, false);
})
.catch((err) => {
console.log(err);
next(null, false);
})
});
passport.use(strategy);
return passport;
}
function tokenRequestHandler(req, res, next) {
const tokenName = req.body.name || nameGenerator().dashed;
createToken(tokenName)
.then((tokenObj) => {
if (tokenObj == null)
res.status(409).send(`Token with name ${tokenName} already exists`);
else
res.json({
name: tokenName,
token: tokenObj.token
});
})
.catch((error) => {
next(error)
});
}
middleware = passport.authenticate('jwt', {session: false});
module.exports = {
init: init,
middleware: middleware,
createToken: createToken,
tokenRequestHandler: tokenRequestHandler
};