@c8y/client
Version:
Client application programming interface to access the Cumulocity IoT-Platform REST services.
278 lines • 12 kB
JavaScript
import { __awaiter } from "tslib";
import { BearerAuth, CookieAuth, NodeJSCookieAuth } from './core/index.js';
import { Realtime } from './realtime/index.js';
import { FetchClient, BasicAuth, AlarmService, ApplicationService, AuditService, DeviceRegistrationBulkService, DeviceRegistrationService, EventService, InventoryBinaryService, InventoryRoleService, InventoryService, MeasurementService, OperationBulkService, OperationService, SystemOptionsService, TenantOptionsService, TenantSecurityOptionsService, TenantLoginOptionsService, TenantService, UserGroupService, UserRoleService, UserService, IdentityService, SmartGroupsService, SmartRulesService } from './services.js';
export class Client {
/**
* Authenticates the given user. Determines the tenant by itself via a call to tenant/currentTenant.
*
* **Example**
* ```typescript
*
* let client: Client;
* (async () => {
* client = await Client.authenticate({
* user: 'testuser',
* password: 'password1337!'
* }, 'https://acme.cumulocity.com');
*
* //you have access to the client api now
* const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });
* })();
* ```
*/
static authenticate(credentials, baseUrl) {
return __awaiter(this, void 0, void 0, function* () {
const auth = new BasicAuth(credentials);
const clientCore = new FetchClient(auth, baseUrl);
const tenantName = yield this.getCurrentTenant(clientCore);
const client = new Client(auth, baseUrl);
client.core.tenant = tenantName;
return client;
});
}
/**
* Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.
* Login call goes to `/tenant/oauth/token` and the retrieved token will be added in the `Authorization` header to subsequent requests.
*
* **Example**
* ```typescript
*
* let client: Client;
* (async () => {
* client = await Client.authenticateViaOAuthInternal({
* user: 'testuser',
* password: 'password1337!'
* }, 'https://acme.cumulocity.com');
*
* //you have access to the client api now
* const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });
* })();
* ```
*/
static authenticateViaOAuthInternal(credentials, baseUrl) {
return __awaiter(this, void 0, void 0, function* () {
const token = yield this.loginViaOAuthInternal(credentials, true, baseUrl);
const auth = new BearerAuth(token);
const clientCore = new FetchClient(auth, baseUrl);
const tenantName = credentials.tenant || (yield this.getCurrentTenant(clientCore));
const client = new Client(auth, baseUrl);
client.core.tenant = tenantName;
return client;
});
}
/**
* Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.
* Login call goes to `/tenant/oauth` and the retrieved token will be attached as a Cookie in browser environments to subsequent requests (using 'CookieAuth').
* In none browser environments (e.g. nodejs) the retrieved token will be added in the `Authorization` header to subsequent requests (using 'NodeJSCookieAuth').
*
* **Example**
* ```typescript
*
* let client: Client;
* (async () => {
* client = await Client.authenticateViaOAuthInternalCookie({
* user: 'testuser',
* password: 'password1337!'
* }, 'https://acme.cumulocity.com');
*
* //you have access to the client api now
* const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });
* })();
* ```
*/
static authenticateViaOAuthInternalCookie(credentials, baseUrl) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.loginViaOAuthInternal(credentials, false, baseUrl);
let auth;
if (typeof document === 'undefined') {
auth = new NodeJSCookieAuth(response);
}
else {
auth = new CookieAuth();
}
const clientCore = new FetchClient(auth, baseUrl);
const tenantName = credentials.tenant || (yield this.getCurrentTenant(clientCore));
const client = new Client(auth, baseUrl);
client.core.tenant = tenantName;
return client;
});
}
/**
* Allows to use http to register a device on the platform.
*
* **Deprecated** Please use MQTT to bootstrap a device.
*/
static deviceBootstrap(options) {
return __awaiter(this, void 0, void 0, function* () {
const { deviceId, timeout, baseUrl, basicAuthToken } = options;
let { expire } = options;
if (timeout && !expire) {
expire = Date.now() + timeout;
}
const clientCore = new FetchClient(undefined, baseUrl);
const deviceRegistration = new DeviceRegistrationService(clientCore);
let client;
try {
const { data } = yield deviceRegistration.bootstrap(deviceId, { basicAuthToken });
const { username, password, tenantId } = data;
const auth = new BasicAuth({ user: username, tenant: tenantId, password });
client = new Client(auth, baseUrl);
client.core.tenant = tenantId;
}
catch (error) {
const retry = (!expire || Date.now() < expire) && error.res.status === 404;
if (retry) {
return Client.deviceBootstrap(Object.assign({ expire }, options));
}
else {
throw error;
}
}
return client;
});
}
/**
* Retrieves microservice credentials for the subscribed tenants
* using provided bootstrap credentials
*
* **Example**
* ```typescript
*
* (async () => {
* const subscriptions = await Client.getMicroserviceSubscriptions({
* tenant: process.env.C8Y_BOOTSTRAP_TENANT,
* user: process.env.C8Y_BOOTSTRAP_USER,
* password: process.env.C8Y_BOOTSTRAP_PASSWORD
* }, process.env.C8Y_BASEURL);
*
* const clients = subscriptions.map(subscription => new Client(new BasicAuth(subscription), process.env.C8Y_BASEURL));
* // you have access to the client api now
* const promiseArray = clients.map(client => client.options.tenant.detail({
* category: process.env.APPLICATION_KEY,
* key: 'someSetting'
* }));
* })();
* ```
*/
static getMicroserviceSubscriptions(bootstrapCredentials_1, baseUrl_1) {
return __awaiter(this, arguments, void 0, function* (bootstrapCredentials, baseUrl, fetchOptions = {}) {
const microserviceSubscriptionsEndpoint = '/application/currentApplication/subscriptions';
const clientCore = new FetchClient(new BasicAuth(bootstrapCredentials), baseUrl);
const res = yield clientCore.fetch(microserviceSubscriptionsEndpoint, fetchOptions);
const { users } = yield res.json();
return users.map(({ tenant, name, password }) => {
return {
tenant,
user: name,
password
};
});
});
}
static loginViaOAuthInternal(credentials_1) {
return __awaiter(this, arguments, void 0, function* (credentials, bearerAuth = true, baseUrl) {
const auth = new BasicAuth(credentials);
const clientCore = new FetchClient(auth, baseUrl);
let url = '/tenant/oauth';
if (bearerAuth) {
url += `/token`;
}
if (credentials.tenant) {
url += `?tenant_id=${credentials.tenant}`;
}
const params = new URLSearchParams({
grant_type: 'PASSWORD',
username: credentials.user,
password: credentials.password,
tfa_code: credentials.tfa
});
const res = yield clientCore.fetch(url, {
method: 'POST',
body: params.toString(),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
});
if (res.status !== 200) {
throw { res };
}
if (bearerAuth) {
const body = yield res.json();
return body['access_token'];
}
return res;
});
}
static getCurrentTenant(fetchClient) {
return __awaiter(this, void 0, void 0, function* () {
const tenantService = new TenantService(fetchClient);
const { data: tenant } = yield tenantService.current();
return tenant.name;
});
}
/**
* Initializes a new Client, which allows to request data from the API. Differently
* to Client.authenticate([...]) it needs a tenant given and does not verify if the
* login is correct.
*
* **Example**
* ```typescript
*
* const auth = new BasicAuth({
* user: 'youruser',
* password: 'yourpassword',
* tenant: 'acme'
* }); // use CookieAuth() if your platform uses oauth (only in browser!)
*
* const baseUrl = 'https://acme.cumulocity.com';
* const client = new Client(auth, baseUrl);
* (async () => {
* const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });
* })();
* ```
*
* @param auth The Authentication strategy to use (e.g. new BasicAuth())
* @param baseUrl The URL to request (optional in browser, mandatory in node)
*/
constructor(auth, baseUrl) {
const client = new FetchClient(auth, baseUrl);
this.realtime = new Realtime(client);
this.alarm = new AlarmService(client, this.realtime);
this.application = new ApplicationService(client, this.realtime);
this.audit = new AuditService(client);
this.core = client;
this.deviceRegistration = new DeviceRegistrationService(client);
this.deviceRegistrationBulk = new DeviceRegistrationBulkService(client);
this.event = new EventService(client, this.realtime);
this.inventory = new InventoryService(client, this.realtime);
this.inventoryBinary = new InventoryBinaryService(client);
this.inventoryRole = new InventoryRoleService(client);
this.measurement = new MeasurementService(client, this.realtime);
this.operation = new OperationService(client);
this.operationBulk = new OperationBulkService(client);
this.options = {
security: new TenantSecurityOptionsService(client),
system: new SystemOptionsService(client),
login: new TenantLoginOptionsService(client),
tenant: new TenantOptionsService(client)
};
this.role = new InventoryRoleService(client);
this.tenant = new TenantService(client);
this.user = new UserService(client);
this.userGroup = new UserGroupService(client);
this.userRole = new UserRoleService(client);
this.identity = new IdentityService(client);
this.smartGroups = new SmartGroupsService(client);
this.smartRules = new SmartRulesService(client);
}
/**
* Allows to change the current Authentication
* @param auth The new Authentication information.
*/
setAuth(auth) {
this.core.setAuth(auth);
this.realtime.disconnect();
}
}
//# sourceMappingURL=Client.js.map