const express = require("express"); const jsonwebtoken = require("jsonwebtoken"); function logMeIn(host, port) { const secretKey = process.env.JWT_SECRET_KEY; const app = express(); app.use(express.json()); app.get("/", (req, res) => { res.status(200).send({ message: "Hello World!" }); }); app.post("/login", (req, res) => { const login = req.body.username; const passwd = req.body.password; if (login !== "xavier.login" || passwd != "1234") { res.status(401).send({ error: "Invalid username or password" }); } else { const jwt = jsonwebtoken.sign(req.body, secretKey); res.status(200).send({ jwt: jwt }); } }); app.get("/secret", (req, res) => { if (req.headers == null || req.headers == undefined) { res.status(401).send({ error: "Unauthorized" }); return; } try { const decoded = jsonwebtoken.verify( req.headers.authorization.split(" ")[1], secretKey, ); if ( decoded.username !== "xavier.login" || decoded.password !== "1234" ) { res.status(401).send({ error: "Unauthorized" }); } res.status(200).send({ message: "Access granted" }); } catch { res.status(401).send({ error: "Unauthorized" }); } }); return app.listen(port, () => { console.log("Server running at http://" + host + ":" + port + "/"); }); } module.exports = { logMeIn, }; //logMeIn("127.0.0.1", 3000);