From 779c072ac783c7b78187cff6c3226e072e50cd27 Mon Sep 17 00:00:00 2001 From: baldo Date: Thu, 28 Jul 2022 13:56:47 +0200 Subject: [PATCH] Add typeguard for node data passed in requests. --- server/resources/nodeResource.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/server/resources/nodeResource.ts b/server/resources/nodeResource.ts index afb754a..7b0cee6 100644 --- a/server/resources/nodeResource.ts +++ b/server/resources/nodeResource.ts @@ -10,9 +10,13 @@ import {Request, Response} from "express"; import { CreateOrUpdateNode, DomainSpecificNodeResponse, + isCreateOrUpdateNode, isNodeSortField, + isString, isToken, + isUndefined, JSONObject, + JSONValue, MAC, NodeResponse, NodeStateData, @@ -25,19 +29,27 @@ import { const nodeFields = ['hostname', 'key', 'email', 'nickname', 'mac', 'coords', 'monitoring']; -// TODO: Rename -function getNormalizedNodeData(reqData: any): CreateOrUpdateNode { +function getNormalizedNodeData(reqData: JSONObject): CreateOrUpdateNode { const node: { [key: string]: any } = {}; for (const field of nodeFields) { - let value = normalizeString(reqData[field]); - if (field === 'mac') { - value = normalizeMac(value as MAC); + let value: JSONValue | undefined = reqData[field]; + if (isString(value)) { + value = normalizeString(value); + if (field === 'mac') { + value = normalizeMac(value as MAC); + } + } + + if (!isUndefined(value)) { + node[field] = value; } - node[field] = value; } - // TODO: Add typeguard before cast. - return node as CreateOrUpdateNode; + if (isCreateOrUpdateNode(node)) { + return node; + } + + throw {data: "Invalid node data.", type: ErrorTypes.badRequest}; } const isValidNode = forConstraints(Constraints.node, false);