Commit 98b26cf6 by Percy Quispe Huarcaya

feat: Adding token creator and a parser

parent c2f3ddce
const jwt = require('jsonwebtoken');
const { getDefaultPath } = require('./util/osutils')
require('dotenv').config({path: getDefaultPath('global') + "/.env"});
const apiKey = process.env.API_KEY;
createJWT = (id, subject, ...time) => {
return createToken(id, "oliverpqh@gmail.com", subject, time);
}
createToken = (id, issuer, subject, ...time) => {
const ttlMillis = time[0] || process.env.VIGENCIA_TOKEN || 3600000 ; // Time in ms (1 hour default)
const now = Date.now();
const signingKey = Buffer.from(apiKey, 'base64');
// JWT payload (claims)
const payload = {
id: id, // JWT ID
issuedAt: Math.floor(now / 1000), // Issued at (in seconds)
subject: subject, // Subject (the user or object the token represents)
issuer: issuer // Issuer (who issued the token)
};
// Set expiration if provided
const options = {
algorithm: 'HS512'
};
if (ttlMillis >= 0) {
const exp = Math.floor((now + ttlMillis) / 1000); // Expiration time in seconds
options.expiresIn = exp;
}
// Create and sign the JWT with the given payload and secret
const token = jwt.sign(payload, signingKey, options);
return token; // Return the signed JWT
}
parseJWT = (token, ...id) => {
try {
// Verify and decode the token using token and private key
const decoded = jwt.verify(token, Buffer.from(apiKey, 'base64'), {
algorithms: ['HS512'] // Ensure it matches the algorithm used when creating the token
});
/* // if one day we want to validate the id
if(id[0]){
if(decoded.payload.id !== id[0]){
throw "EL ID NO ES VALIDO";
}
}
*/
return decoded; // This will return the token's claims (payload)
} catch (err) {
console.error('Invalid token:', err.message);
throw err;
}
}
module.exports = {
createJWT,
parseJWT
};
\ No newline at end of file
const jwt = require('jsonwebtoken');
const secretKey = process.env.JWT_SECRET || 'your-secret-key'; // Always use environment variables for secrets
const TokenService = {
// Function to create a token
createToken: (payload) => {
return jwt.sign(payload, secretKey, { expiresIn: '1h' });
},
// Function to validate a token
validateToken: (token) => {
try {
return jwt.verify(token, secretKey);
} catch (err) {
throw new Error('Invalid token');
}
},
// Function to decode token without verifying
decodeToken: (token) => {
return jwt.decode(token);
}
};
module.exports = TokenService;
const os = require('os');
const fs = require('fs');
const path = require('path');
const DEFAULT_UNIX = '/opt/dotenv/';
// Helper function to detect the operating system
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
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
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}`);
}
};
// Export the functions for use in other files
module.exports = {
getOperatingSystemType,
getDefaultPath,
};
const {createJWT, parseJWT} = require('../src/token');
describe('Token', () => {
test('should generate and validate a token sending duration time', () => {
//id, issuer, subject
const id = 'trismegistro';
const subject = {"usuarioId": 395};
const unixTime = 3600000; // 1 hour validity
const token = createJWT(id, subject, unixTime);
const test = parseJWT(token);
const payload = test.subject;
expect(payload.usuarioId).toBe(395);
});
test('should generate and validate a token without sending duration time', () => {
//id, issuer, subject
const id = 'trismegistro';
const subject = {"usuarioId": 395};
const token = createJWT(id, subject);
const test = parseJWT(token);
const payload = test.subject;
expect(payload.usuarioId).toBe(395);
});
test('should throw an error for an invalid token', () => {
expect(() => parseJWT('invalidToken')).toThrow('jwt malformed');
});
});
const TokenService = require('../src/tokenService');
describe('TokenService', () => {
test('should generate and validate a token', () => {
const payload = { userId: 123 };
const token = TokenService.createToken(payload);
const decoded = TokenService.validateToken(token);
expect(decoded.userId).toBe(123);
});
test('should throw an error for an invalid token', () => {
expect(() => TokenService.validateToken('invalidToken')).toThrow('Invalid token');
});
});
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