import { ValidateRoleOptions } from "../typings"; /** * Validates the role contained within a token against the allowed role(s) provided * @param options Options for validating the role */ export const validateRole = (options: ValidateRoleOptions) => { const { roles, scheme, serviceAuthScheme, data, service } = options; if ( (roles === "user" || roles === "admin" || roles === "agent") && scheme !== "Bearer" ) throw new Error("Invalid auth scheme provided"); if (roles === "service" && scheme !== serviceAuthScheme) throw new Error("Invalid auth scheme provided"); if (Array.isArray(roles) && !roles.includes(data.role)) throw new Error("You do not have permission to call this endpoint"); if (typeof roles === "string" && roles !== "*" && roles !== data.role) throw new Error("You do not have permission to call this endpoint"); if (scheme === serviceAuthScheme) { if (service === "*") return; if (Array.isArray(service) && !service.includes(data.service)) throw new Error( `The service ${data.service} does not have permission to call this endpoint` ); if (typeof service === "string" && service !== data.service) throw new Error( `The service ${data.service} does not have permission to call this endpoint` ); return; } };