@intrasoft/auth-core
Version:
A robust and customizable authentication package for Node.js applications, providing JWT-based authentication and token management
76 lines (73 loc) • 2.05 kB
JavaScript
// src/tokens.ts
import * as jwt from "jsonwebtoken";
// src/config.ts
function validateConfig(config) {
if (!config.secretKey) {
throw new Error("Missing secretKey in configuration");
}
if (isNaN(config.accessLifetime)) {
throw new Error("Missing or invalid accessLifetime in configuration");
}
if (config.accessLifetime && isNaN(config.refreshLifetime)) {
throw new Error("Invalid refreshLifetime in configuration");
}
}
var CACHED_CONFIG = void 0;
function getConfig() {
if (CACHED_CONFIG) return CACHED_CONFIG;
const config = {
secretKey: process.env.INTRASOFT_SECRET_KEY,
accessLifetime: parseInt(process.env.INTRASOFT_ACCESS_TOKEN_LIFETIME),
refreshLifetime: parseInt(process.env.INTRASOFT_REFRESH_TOKEN_LIFETIME)
};
validateConfig(config);
CACHED_CONFIG = config;
return config;
}
// src/tokens.ts
async function createToken(payload) {
const validTypes = ["object"];
if (!payload || !validTypes.includes(typeof payload)) {
throw new Error("Invalid payload type");
}
const config = getConfig();
const _payload = new Object({ payload });
return generateTokens(_payload, false, config);
}
async function refreshToken(refreshToken2) {
try {
const config = getConfig();
const verifiedToken = jwt.verify(
refreshToken2,
config.secretKey
);
return generateTokens(verifiedToken.payload, true, config);
} catch (error) {
throw new Error("Invalid refresh token");
}
}
async function decodeJwt(token) {
const config = getConfig();
const payload = jwt.verify(token, config.secretKey);
return payload;
}
function generateTokens(payload, _r, config) {
const _payload = new Object({ _r, payload });
const access = jwt.sign(_payload, config.secretKey, {
expiresIn: config.accessLifetime
});
const token = {
access
};
if (config.refreshLifetime) {
token.refresh = jwt.sign(_payload, config.secretKey, {
expiresIn: config.refreshLifetime
});
}
return token;
}
export {
createToken,
decodeJwt,
refreshToken
};