From 4c9a868d6b2e2bc68da5c1c6a0d1ab5e02cd57a4 Mon Sep 17 00:00:00 2001 From: Martin Berka Date: Thu, 29 Jun 2023 07:33:05 +0200 Subject: [PATCH] =?UTF-8?q?Za=C4=8Di=C5=A1t=C4=9Bn=C3=AD=20pou=C5=BEit?= =?UTF-8?q?=C3=AD=20remote-user=20hlavi=C4=8Dky?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/src/auth.ts | 5 ++++- server/src/index.ts | 23 ++++++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/server/src/auth.ts b/server/src/auth.ts index 85c837b..4dcf0f0 100644 --- a/server/src/auth.ts +++ b/server/src/auth.ts @@ -6,13 +6,16 @@ import jwt from 'jsonwebtoken'; * @param login přihlašovací jméno uživatele * @returns JWT token */ -export function generateToken(login: string): string { +export function generateToken(login?: string): string { if (!process.env.JWT_SECRET) { throw Error("Není vyplněna proměnná prostředí JWT_SECRET"); } if (process.env.JWT_SECRET.length < 32) { throw Error("Proměnná prostředí JWT_SECRET musí být minimálně 32 znaků"); } + if (!login || login.trim().length === 0) { + throw Error("Nebyl předán login"); + } return jwt.sign({ login }, process.env.JWT_SECRET); } diff --git a/server/src/index.ts b/server/src/index.ts index 02db08f..a8635c7 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -38,29 +38,30 @@ const parseToken = (req: any) => { // ----------- Metody nevyžadující token -------------- -app.get("/api/whoami",(req,res)=>{ +app.get("/api/whoami", (req, res) => { res.send(req.header('remote-user')); }) app.post("/api/login", (req, res) => { - if (!req.body?.login) { + // Autentizace pomocí trusted headers + const remoteUser = req.header('remote-user'); + if (remoteUser && remoteUser.length > 0) { + res.status(200).json(generateToken(remoteUser)); + return; + } + // Klasická autentizace loginem + if (!req.body?.login || req.body.login.trim().length === 0) { throw Error("Nebyl předán login"); } - // TODO: je tohle hnusny?... bude to fungovat? lol - if (req.header('remote-user')){ - let username = req.header('remote-user') || "jmenonemahlavicku" - res.status(200).json(generateToken(username)); - } else { - // TODO zavést podmínky pro délku loginu (min i max) - res.status(200).json(generateToken(req.body.login)); - } + // TODO zavést podmínky pro délku loginu (min i max) + res.status(200).json(generateToken(req.body.login)); }); // ---------------------------------------------------- /** Middleware ověřující JWT token */ app.use((req, res, next) => { - if (req.header('remote-user')){ + if (req.header('remote-user')) { console.log("Tvuj username: %s.", req.header('remote-user')); } if (!req.headers.authorization) {