Ghost/ghost/members-api/lib/services/token/index.js
Fabien 'egg' O'Carroll e3ef01932f Refactor members-api (#231)
no-issue

This refactors the members-api module so that it is easier to test going forward,
as well as easier to understand & navigate. The Stripe API no longer contains
storage code, this is all handled via the member repository. And we have dedicated
services for webhooks, and stripe plans initialisation.
2021-01-18 13:55:40 +00:00

55 lines
1.4 KiB
JavaScript

const jose = require('node-jose');
const jwt = require('jsonwebtoken');
module.exports = class TokenService {
constructor({
privateKey,
publicKey,
issuer
}) {
this._keyStore = jose.JWK.createKeyStore();
this._keyStoreReady = this._keyStore.add(privateKey, 'pem');
this._privateKey = privateKey;
this._publicKey = publicKey;
this._issuer = issuer;
}
encodeAPIToken({sub, aud = this._issuer, plans, exp}) {
return this._keyStoreReady.then(jwk => jwt.sign({
sub,
plans,
kid: jwk.kid
}, this._privateKey, {
algorithm: 'RS512',
audience: aud,
expiresIn: exp,
issuer: this._issuer
}));
}
encodeIdentityToken({sub}) {
return this._keyStoreReady.then(jwk => jwt.sign({
sub,
kid: jwk.kid
}, this._privateKey, {
algorithm: 'RS512',
audience: this._issuer,
expiresIn: '10m',
issuer: this._issuer
}));
}
decodeToken(token) {
return this._keyStoreReady.then(jwk => jwt.verify(token, this._publicKey, {
algorithm: 'RS512',
kid: jwk.kid,
issuer: this._issuer
})).then(() => jwt.decode(token));
}
getPublicKeys() {
return this._keyStoreReady.then(() => {
this._keyStore.toJSON();
});
}
};