forked from ShragaUser/spike-auth-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
32 lines (25 loc) · 1.21 KB
/
index.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
const fs = require("fs");
const getPassportAuthMiddleware = require("./passport");
const config = require("./config")();
const getSpikeAuthMiddleWare = (options) => {
const { audience, pathToPublicKey, allowedScopes, useBearerToken } = { ...config, ...options };
if (!(pathToPublicKey && audience && allowedScopes)) {
throw new Error('must provide pathToPublicKey && audience && allowedScopes to auth middleware');
}
const getPublicKey = function () {
if (this.key)
return this.key;
this.key = fs.readFileSync(pathToPublicKey);
return this.key;
};
const verifyAudience = (aud) => aud === audience;
const verifyScopes = (scopes) => scopes.some(scope => allowedScopes.includes(scope));
const getAndVerifiyAudienceFromJWT = jwt => jwt && jwt.aud && verifyAudience(jwt.aud);
const getAndVerifiyScopesFromJWT = jwt => jwt && jwt.scope && verifyScopes(jwt.scope);
const verify = (jwt, done) => {
const verified = getAndVerifiyAudienceFromJWT(jwt) && getAndVerifiyScopesFromJWT(jwt);
done(null, verified);
};
return getPassportAuthMiddleware(getPublicKey(), useBearerToken, verify);
};
module.exports = { getSpikeAuthMiddleWare };