From dd47b368908bc5d5cdb80264dcaa226b941cb0ac Mon Sep 17 00:00:00 2001 From: Christoph Lienhard Date: Tue, 30 Mar 2021 15:44:04 +0200 Subject: [PATCH] Refactor: Improve typing in jwt.ts --- redaktions-app/src/jwt/jwt.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/redaktions-app/src/jwt/jwt.ts b/redaktions-app/src/jwt/jwt.ts index 7dd7c9d..1912e54 100644 --- a/redaktions-app/src/jwt/jwt.ts +++ b/redaktions-app/src/jwt/jwt.ts @@ -1,5 +1,6 @@ import { client } from "../backend/helper"; +type Claim = "role" | "person_row_id" | "exp" | "iat" | "aud" | "iss"; export type UserRole = | "candymat_editor" | "candymat_candidate" @@ -14,20 +15,25 @@ export interface JwtPayload { iss: "postgraphile"; } -const claims = ["role", "person_row_id", "exp", "iat", "aud", "iss"]; -const userRoles = ["candymat_editor", "candymat_candidate", "candymat_person"]; +const CLAIMS: Claim[] = ["role", "person_row_id", "exp", "iat", "aud", "iss"]; +const USER_ROLES: UserRole[] = [ + "candymat_editor", + "candymat_candidate", + "candymat_person", +]; export const getRawJsonWebToken = (): string | null => { return localStorage.getItem("token"); }; -export const isJwtPayloadValid = (jwtPayload: JwtPayload): boolean => { +export const isJwtPayloadValid = (jwtPayload: unknown): boolean => { + const jwt = Object(jwtPayload); return ( - claims.every((claim) => Object.keys(jwtPayload).includes(claim)) && - userRoles.includes(jwtPayload.role) && - typeof jwtPayload.person_row_id === "number" && - typeof jwtPayload.exp === "number" && - typeof jwtPayload.iat === "number" + CLAIMS.every((claim) => Object.keys(jwt).includes(claim)) && + USER_ROLES.includes(jwt.role) && + typeof jwt.person_row_id === "number" && + typeof jwt.exp === "number" && + typeof jwt.iat === "number" ); };