Ghost/ghost/magic-link/lib/JWTTokenProvider.js
Fabien O'Carroll 97ceb13d42 Moved JWTTokenProvider to lib and exported from index
no-issue

This brings the module in line with our current package standards.
2020-09-18 13:20:12 +01:00

51 lines
986 B
JavaScript

const jwt = require('jsonwebtoken');
/**
* @typedef {import('jsonwebtoken').Secret} Secret
* @typedef {string} JSONWebToken
*/
/**
* @typedef {Object<string, any>} Data
*/
module.exports = class JWTTokenProvider {
/**
* @param {Secret} secret
*/
constructor(secret) {
this.secret = secret;
}
/**
* @param {Data} data
* @returns {Promise<JSONWebToken>}
*/
async create(data) {
const token = jwt.sign(data, this.secret, {
algorithm: 'HS256',
expiresIn: '10m'
});
return token;
}
/**
* @param {JSONWebToken} token
* @returns {Promise<Data>}
*/
async validate(token) {
/** @type any */
const claims = jwt.verify(token, this.secret, {
algorithms: ['HS256'],
maxAge: '10m'
});
if (!claims || typeof claims === 'string') {
throw new Error();
}
return claims;
}
};