Commit c2f3ddce by Percy Quispe Huarcaya

Initial commit

parents
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "security-ndjs-lib",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"jsonwebtoken": "^9.0.2"
},
"devDependencies": {
"jest": "^29.7.0"
}
}
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 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