Refactor: Improve typing in jwt.ts

This commit is contained in:
Christoph Lienhard 2021-03-30 15:44:04 +02:00
parent ee263f52b1
commit dd47b36890
Signed by: christoph.lienhard
GPG key ID: 6B98870DDC270884

View file

@ -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"
);
};