Commit 3b8e9e3b by Percy Quispe Huarcaya

feat: Adding token creator and a parser

parent a08c2422
This source diff could not be displayed because it is too large. You can view the blob instead.
import os from 'os';
import fs from 'fs';
import path from 'path';
const DEFAULT_UNIX = '/opt/dotenv/';
// Helper function to detect the operating system
export const getOperatingSystemType = () => {
const platform = os.platform();
switch (platform) {
case 'darwin':
return 'MacOS';
case 'win32':
return 'Windows';
case 'linux':
return 'Linux';
default:
throw new Error(`Unsupported platform: ${platform}`);
}
};
// Helper function for Windows-specific path check
export const findWindowsPath = (projectName) => {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
for (const letter of alphabet) {
const winPath = `${letter}:/dotenv/${projectName}`;
if (fs.existsSync(winPath)) {
return winPath;
}
}
return null; // No valid path found
};
// Main function to get the default project path
export const getDefaultPath = (projectName, ...customPath) => {
const detectedOs = getOperatingSystemType();
if (!projectName) {
throw new Error('Project name is required.');
}
switch (detectedOs) {
case 'MacOS':
case 'Linux': {
const basePath = customPath[0] ? customPath[0] : DEFAULT_UNIX;
return path.join(basePath, projectName);
}
case 'Windows': {
if (customPath[0]) {
return path.join(customPath[0], projectName);
}
else {
const windowsPath = findWindowsPath(projectName);
if (!windowsPath) {
throw new Error('No valid Windows drive found for the path.');
}
return windowsPath;
}
}
default:
throw new Error(`Unsupported OS: ${detectedOs}`);
}
};
import jwt from 'jsonwebtoken';
import { getDefaultPath } from './osutils';
import dotenv from 'dotenv';
// Cargar las variables de entorno desde el archivo .env
dotenv.config({ path: getDefaultPath('global') + '/.env' });
const apiKey = process.env.API_KEY;
const tokenAlgorithm = process.env.TOKEN_ALGORITHM;
export const createJWT = (id, subject, ...time) => {
return createToken(id, "oliverpqh@gmail.com", subject, ...time);
};
export const createToken = (id, issuer, subject, ...time) => {
const ttlMillis = time[0] || Number(process.env.VIGENCIA_TOKEN) || 3600000; // Default to 1 hour
const now = Date.now();
if (!apiKey) {
throw new Error('API_KEY is required but not defined in environment variables.');
}
const signingKey = Buffer.from(apiKey, 'base64');
// JWT payload
const payload = {
id: id,
issuedAt: Math.floor(now / 1000),
subject: subject,
issuer: issuer
};
const options = {
algorithm: tokenAlgorithm,
expiresIn: ttlMillis >= 0 ? Math.floor((now + ttlMillis) / 1000) : undefined
};
// Create and sign the JWT
const token = jwt.sign(payload, signingKey, options);
return token;
};
export const parseJWT = (token, ...id) => {
try {
// Ensure apiKey is defined
if (!apiKey) {
throw new Error('API_KEY is required but not defined in environment variables.');
}
const decoded = jwt.verify(token, Buffer.from(apiKey, 'base64'), {
algorithms: [tokenAlgorithm]
});
console.log("parseJWT--------------------");
console.log(decoded);
return decoded;
}
catch (err) {
throw err;
}
};
......@@ -36,7 +36,6 @@ export const createToken = (id: string, issuer: string, subject: object, ...time
// Create and sign the JWT
const token = jwt.sign(payload, signingKey, options);
return token;
};
......@@ -51,8 +50,6 @@ export const parseJWT = (token: string, ...id: string[]) => {
const decoded = jwt.verify(token, Buffer.from(apiKey, 'base64'), {
algorithms: [tokenAlgorithm]
});
console.log("parseJWT--------------------")
console.log(decoded);
return decoded;
} catch (err) {
throw err;
......
......@@ -12,7 +12,7 @@ describe('Token', () => {
const test = parseJWT(token);
console.log("------------------------>");
console.log(test);
console.log(token);
const payload = test.sub;
expect(payload).not.toBeNull();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment