summary refs log tree commit diff
path: root/src/util/jwtUtils.js
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-06-01 01:03:40 +0200
committerRory& <root@rory.gay>2025-06-01 01:03:40 +0200
commit99220d73469210f94493ef92a9edc64ab50eb0d9 (patch)
tree765781a300db5c1e1a15afaa8bd09f48712a5313 /src/util/jwtUtils.js
parentInit test frontend (diff)
downloadnodejs-final-assignment-99220d73469210f94493ef92a9edc64ab50eb0d9.tar.xz
Add some tests
Diffstat (limited to 'src/util/jwtUtils.js')
-rw-r--r--src/util/jwtUtils.js34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/util/jwtUtils.js b/src/util/jwtUtils.js

index 115c9c5..9031631 100644 --- a/src/util/jwtUtils.js +++ b/src/util/jwtUtils.js
@@ -1,6 +1,7 @@ import {existsSync} from 'fs'; import {readFile, writeFile} from "node:fs/promises"; import {generateKeyPairSync, createHash, createPublicKey, createPrivateKey} from 'node:crypto'; +import jwt from "jsonwebtoken"; let privateKey, publicKey, fingerprint; @@ -10,6 +11,8 @@ export async function initJwt() { throw new Error('JWT secret path is not defined in environment variables, or the directory does not exist.'); } + console.log(`[JWT] Initializing JWT with secret path: ${secretPath}`); + const privateKeyPath = `${secretPath}/jwt.key`; const publicKeyPath = `${secretPath}/jwt.key.pub`; @@ -55,9 +58,40 @@ const jwtOptions = { } export async function generateJwtToken(user) { + if (!privateKey) { + throw new Error('JWT private key is not initialized. Please call initJwt() first.'); + } + + const payload = { + sub: user._id.toString(), + username: user.username, + type: user.type, + iat: Math.floor(Date.now() / 1000) + }; + return new Promise((resolve, reject) => { + jwt.sign(payload, privateKey, jwtOptions, (err, token) => { + if (err) { + console.error('[JWT] Error generating token:', err); + return reject(err); + } + resolve(token); + }); + }); } export async function validateJwtToken(token) { + if (!publicKey) { + throw new Error('JWT public key is not initialized. Please call initJwt() first.'); + } + return new Promise((resolve, reject) => { + jwt.verify(token, publicKey, jwtOptions, (err, decoded) => { + if (err) { + console.error('[JWT] Token validation failed:', err); + return reject(err); + } + resolve(decoded); + }); + }); } \ No newline at end of file