@c8y/client
Version:
Client application programming interface to access the Cumulocity IoT-Platform REST services.
77 lines • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicAuth = void 0;
const b2a_1 = require("b2a");
// this is var and not const to please typedoc https://github.com/TypeStrong/typedoc/issues/691
// eslint-disable-next-line no-var
var secrets = new WeakMap();
/**
* Allows to use Basic-Auth for Authorization to the
* Cumulocity API.
*/
class BasicAuth {
/**
* Authenticates the given user against the given tenant.
* @param name
* @param password
* @param tenant
*/
constructor(credentials) {
this.updateCredentials(credentials);
}
updateCredentials({ tenant, user, password, token, tfa } = {}) {
const secret = secrets.get(this) || {};
if (user && tenant) {
user = `${tenant}/${user}`;
}
user = user || this.user;
password = password || secret.password;
if (!token && user && password) {
token = (0, b2a_1.btoa)(`${user}:${password}`);
}
if (user) {
this.user = user;
}
token = token || secret.token;
tfa = tfa || secret.tfa;
secrets.set(this, { tfa, token, password });
return token;
}
getFetchOptions(options) {
const secret = secrets.get(this);
const { token, tfa } = secret;
const xsrfToken = this.getCookieValue('XSRF-TOKEN');
const headers = {
Authorization: `Basic ${token || ''}`,
...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : undefined)
};
if (tfa) {
headers.tfatoken = tfa;
}
options.headers = Object.assign(headers, options.headers);
return options;
}
getCometdHandshake(config = {}) {
const secret = secrets.get(this);
const { token, tfa } = secret;
const KEY = 'com.cumulocity.authn';
const ext = (config.ext = config.ext || {});
ext[KEY] = Object.assign(ext[KEY] || {}, { token, tfa });
return config;
}
logout() {
delete this.user;
secrets.set(this, {});
}
getCookieValue(name) {
try {
const value = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
return value ? value.pop() : undefined;
}
catch (ex) {
return undefined;
}
}
}
exports.BasicAuth = BasicAuth;
//# sourceMappingURL=BasicAuth.js.map