2019-01-22 17:29:44 +03:00
|
|
|
const jose = require('node-jose');
|
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
|
|
|
|
module.exports = function ({
|
|
|
|
privateKey,
|
|
|
|
publicKey,
|
|
|
|
issuer
|
|
|
|
}) {
|
|
|
|
const keyStore = jose.JWK.createKeyStore();
|
|
|
|
const keyStoreReady = keyStore.add(privateKey, 'pem');
|
|
|
|
|
2019-02-25 19:03:27 +03:00
|
|
|
function encodeToken({sub, aud = issuer, plans, exp}) {
|
2019-01-22 17:29:44 +03:00
|
|
|
return keyStoreReady.then(jwk => jwt.sign({
|
|
|
|
sub,
|
2019-02-25 19:03:27 +03:00
|
|
|
exp,
|
2019-02-07 12:41:39 +03:00
|
|
|
plans,
|
2019-01-22 17:29:44 +03:00
|
|
|
kid: jwk.kid
|
|
|
|
}, privateKey, {
|
|
|
|
algorithm: 'RS512',
|
|
|
|
audience: aud,
|
|
|
|
issuer
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
function decodeToken(token) {
|
|
|
|
return keyStoreReady.then(jwk => jwt.verify(token, publicKey, {
|
|
|
|
algorithm: 'RS512',
|
|
|
|
kid: jwk.kid,
|
|
|
|
issuer
|
|
|
|
})).then(() => jwt.decode(token));
|
|
|
|
}
|
|
|
|
|
|
|
|
function getPublicKeys() {
|
|
|
|
return keyStoreReady.then(() => {
|
|
|
|
keyStore.toJSON();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
encodeToken,
|
|
|
|
decodeToken,
|
|
|
|
getPublicKeys
|
|
|
|
};
|
|
|
|
};
|