switch to middleware validation

This commit is contained in:
Hendrik Schutter 2025-01-06 20:07:55 +01:00
parent 2c94b7fb7e
commit dca88c26a4
4 changed files with 51 additions and 40 deletions

View File

@ -15,9 +15,10 @@ def send_post_request(uri, data, token):
"Content-Type": "application/json",
}
try:
requests.post(uri, json=data, timeout=1, headers=headers)
response = requests.post(uri, json=data, timeout=1, headers=headers)
print("Return code: " + str(response.status_code))
except requests.exceptions.RequestException as e:
pass
print(e)
def main():
parser = argparse.ArgumentParser(

View File

@ -7,6 +7,8 @@ import { LpTtnEndDeviceUplinksService } from "../services/lpTtnEndDeviceUplinksS
import { TtnGatewayReceptionService } from "../services/ttnGatewayReceptionService";
import { WifiScanService } from "../services/wifiScanService";
import { ttnMessageValidator } from "../validation/ttn/ttnMessageValidation";
import { authenticateHeader } from "../middleware/authentificationMiddleware";
import { StatusCodes } from "http-status-codes";
const lpTtnEndDeviceUplinksService = container.resolve(
LpTtnEndDeviceUplinksService
@ -20,44 +22,10 @@ const locationService = container.resolve(LocationService);
const router = express.Router();
const validateBearerToken = (authorizationHeader: string | undefined): boolean => {
if (!authorizationHeader) {
console.log("Authorization header is missing!");
return false;
}
const token = authorizationHeader.split(' ')[1]; // Extract token after 'Bearer'
if (!token) {
console.log("Bearer token is missing!");
return false;
}
if (token !== process.env.WEBHOOK_TOKEN) {
console.log("Bearer token is incorrect!");
return false;
}
return true;
};
router.post(
"/webhook",
validateData(ttnMessageValidator),
[authenticateHeader, validateData(ttnMessageValidator)],
async (req: Request, res: Response) => {
try {
const authorizationHeader = req.headers['authorization'];
if (!validateBearerToken(authorizationHeader as string)) {
res.status(401).json({ error: "Authentication failed" });
return;
}
//console.log("Bearer token is correct!");
} catch (error) {
console.error("Error during authentication:", error);
res.status(401).json({ error: "Authentication failed" });
}
try {
const message = req.body as TtnMessage;
@ -137,10 +105,10 @@ router.post(
});
};
createDatabaseEntries().then();
res.status(200);
res.status(StatusCodes.OK).send();
} catch (error) {
console.log(error);
res.status(500).json({ error: "Error creating uplink" });
res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ error: "Error creating uplink" });
}
}
);

View File

@ -0,0 +1,42 @@
import { NextFunction, Request, Response } from "express";
import { StatusCodes } from "http-status-codes";
const validateBearerToken = (authorizationHeader: string | undefined): boolean => {
if (!authorizationHeader) {
console.log("Authorization header is missing!");
return false;
}
const token = authorizationHeader.split(' ')[1]; // Extract token after 'Bearer'
if (!token) {
console.log("Bearer token is missing!");
return false;
}
if (token !== process.env.WEBHOOK_TOKEN) {
console.log("Bearer token is incorrect!");
return false;
}
return true;
};
export function authenticateHeader(req: Request, res: Response, next: NextFunction) {
try {
const authorizationHeader = req.headers['authorization'];
if (!validateBearerToken(authorizationHeader as string)) {
res.status(StatusCodes.UNAUTHORIZED).json({ error: "Authentication failed" });
return;
}
console.log("Bearer token is correct!");
next();
} catch (error) {
res.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json({ error: "Internal Server Error" });
}
};

View File

@ -22,4 +22,4 @@ export function validateData(schema: z.ZodObject<any, any>) {
}
}
};
}
}