UNPKG

@c8y/client

Version:

Client application programming interface to access the Cumulocity IoT-Platform REST services.

70 lines 2.27 kB
import { btoa } from '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. */ export 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 = 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 = Object.assign({ 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; } } } //# sourceMappingURL=BasicAuth.js.map