UNPKG

domotz-remote-pawn

Version:

Domotz Agent

93 lines (75 loc) 3.25 kB
/** This file is part of Domotz Agent. * Copyright (C) 2016 Domotz Ltd * * Domotz Agent is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Domotz Agent is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>. **/ /** * * Created by Tommaso Latini <tommaso@domotz.com> on 16/07/15. */ var factory = function (random, url, web, hostInfo, configuration, userRequest) { const AGENT_RESET_TIMEOUT = 60000; const AGENT_CREATE_TIMEOUT = 180000; var mainAgentProperties = ['display_name', 'id', 'licence_id', 'status', 'versions', 'timezone', 'location', 'country_code']; function create(userId, displayName, agentContext) { var method = 'POST'; var resource = 'user/' + userId + '/agent'; var body = { display_name: displayName, context: agentContext, mac_address: hostInfo.getMAC() }; console.debug("User %s creates a new agent %s", userId, displayName); return userRequest.sendWithPromise(resource, method, body, web.extractLocation, null, {timeout: AGENT_CREATE_TIMEOUT}); } function update(userId, agentId, agentUsername) { var method = 'PUT'; var resource = 'user/' + userId + '/agent/' + agentId + '/credentials'; var newPassword = random.getRandomBytes(64, 'hex'); var body = { password: newPassword }; console.debug("User %s re-configures a broken agent %s with name: %s", userId, agentId, agentUsername); /** * When the API is stable. The callback of this method should be * extractLocation() [as in create method] when the engine will start * return location in HTTP headers like for POST requests. **/ return userRequest.sendWithPromise(resource, method, body, function(response) { var appApiEndpoint = response.headers['x-api-endpoint']; return 'https://' + agentUsername + ':' + newPassword + '@' + url.parse(appApiEndpoint).host + '/hub-api/v1/agent/' + agentId; }); } function get() { var data = {}; mainAgentProperties.forEach(function (val) { data[val] = configuration[val]; }); return data; } function destroy(userId, licenceId) { var resource = 'user/' + userId + '/licence/' + licenceId; console.debug("User %s asks for licence %s reset", userId, licenceId); return userRequest.sendWithPromise(resource, 'PUT', {agent_id: null}, null, null, {timeout: AGENT_RESET_TIMEOUT}); } return { create: create, get: get, update: update, delete: destroy }; }; module.exports.factory = factory;