cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
80 lines (79 loc) • 2.63 kB
JavaScript
/// <reference types="cypress" />
import _ from "lodash";
export const C8yPactAuthObjectKeys = [
"userAlias",
"user",
"type",
];
/**
* Checks if the given object is a C8yAuthOptions.
*
* @param obj The object to check.
* @param options Options to check for additional properties.
* @returns True if the object is a C8yAuthOptions, false otherwise.
*/
export function isAuthOptions(obj) {
return _.isObjectLike(obj) && "user" in obj && "password" in obj;
}
export function toPactAuthObject(obj) {
return _.pick(obj, C8yPactAuthObjectKeys);
}
export function isPactAuthObject(obj) {
return (_.isObjectLike(obj) &&
"user" in obj &&
("userAlias" in obj || "type" in obj) &&
Object.keys(obj).every((key) => C8yPactAuthObjectKeys.includes(key)));
}
export function normalizeAuthHeaders(headers) {
// required to fix inconsistencies between c8yclient and interceptions
// using lowercase and uppercase. fix here.
const xsrfTokenHeader = Object.keys(headers || {}).find((key) => key.toLowerCase() === "x-xsrf-token");
const authorizationHeader = Object.keys(headers || {}).find((key) => key.toLowerCase() === "authorization");
if (xsrfTokenHeader && xsrfTokenHeader !== "X-XSRF-TOKEN") {
headers["X-XSRF-TOKEN"] = headers[xsrfTokenHeader];
delete headers[xsrfTokenHeader];
}
if (authorizationHeader && authorizationHeader !== "Authorization") {
headers["Authorization"] = headers[authorizationHeader];
delete headers[authorizationHeader];
}
return headers;
}
export function getAuthOptionsFromBasicAuthHeader(authHeader) {
if (!authHeader ||
!_.isString(authHeader) ||
!authHeader.startsWith("Basic ")) {
return undefined;
}
const base64Credentials = authHeader.slice("Basic ".length);
const credentials = decodeBase64(base64Credentials);
const components = credentials.split(":");
if (!components || components.length < 2) {
return undefined;
}
return { user: components[0], password: components.slice(1).join(":") };
}
export function encodeBase64(str) {
if (!str)
return "";
let encoded;
if (typeof Buffer !== "undefined") {
encoded = Buffer.from(str).toString("base64");
}
else {
encoded = btoa(str);
}
return encoded;
}
export function decodeBase64(base64) {
if (!base64)
return "";
let decoded;
if (typeof Buffer !== "undefined") {
decoded = Buffer.from(base64, "base64").toString("utf-8");
}
else {
decoded = atob(base64);
}
return decoded;
}