2021-01-18 16:55:40 +03:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2021-05-20 17:17:12 +03:00
|
|
|
async encodeIdentityToken({sub}) {
|
|
|
|
const jwk = await this._keyStoreReady;
|
|
|
|
return jwt.sign({
|
2021-01-18 16:55:40 +03:00
|
|
|
sub,
|
|
|
|
kid: jwk.kid
|
|
|
|
}, this._privateKey, {
|
2022-05-23 13:45:08 +03:00
|
|
|
keyid: jwk.kid,
|
2021-01-18 16:55:40 +03:00
|
|
|
algorithm: 'RS512',
|
|
|
|
audience: this._issuer,
|
|
|
|
expiresIn: '10m',
|
|
|
|
issuer: this._issuer
|
2021-05-20 17:17:12 +03:00
|
|
|
});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-05-20 17:17:12 +03:00
|
|
|
/**
|
|
|
|
* @param {string} token
|
2021-09-17 12:25:57 +03:00
|
|
|
* @returns {Promise<jwt.JwtPayload>}
|
2021-05-20 17:17:12 +03:00
|
|
|
*/
|
|
|
|
async decodeToken(token) {
|
|
|
|
await this._keyStoreReady;
|
|
|
|
|
2021-09-17 12:25:57 +03:00
|
|
|
const result = jwt.verify(token, this._publicKey, {
|
2021-05-20 17:17:12 +03:00
|
|
|
algorithms: ['RS512'],
|
2021-01-18 16:55:40 +03:00
|
|
|
issuer: this._issuer
|
2021-05-20 17:17:12 +03:00
|
|
|
});
|
2021-09-17 12:25:57 +03:00
|
|
|
|
|
|
|
if (typeof result === 'string') {
|
|
|
|
return {sub: result};
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-05-20 17:17:12 +03:00
|
|
|
async getPublicKeys() {
|
|
|
|
await this._keyStoreReady;
|
|
|
|
return this._keyStore.toJSON();
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
2021-05-20 17:17:12 +03:00
|
|
|
};
|