domotz-remote-pawn
Version:
Domotz Agent
73 lines (62 loc) • 3.14 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2021 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 Fausto Lelli <fausto@domotz.com> on 08/09/21.
*/
module.exports.post = function (resourceLocator, onException, onSuccess) {
var myConsole = resourceLocator.log.decorateLogs();
var activationTokenEntity = resourceLocator.entities.activationToken;
var notConfiguredAgentEntity = resourceLocator.entities.notConfiguredAgent;
return function (req, res) {
var activationToken = activationTokenEntity.getActivationToken();
if (activationToken) {
myConsole.info('(%s): %s - %s', req.method, req.url, 'activation token already exists, returning it');
return onSuccess(res, { token: activationToken });
}
myConsole.info('(%s): %s - %s', req.method, req.url, 'valid activation token not found, creating a new one');
var ip = resourceLocator.discovery.host.getIP();
var port = resourceLocator.webapp.get('port');
myConsole.info('(%s): %s - %s', req.method, req.url, 'getting authentication token from cloud...');
notConfiguredAgentEntity
.create()
.then(function () {
return notConfiguredAgentEntity.update(ip, port);
})
.then(function () {
activationTokenEntity
.create()
.then(function (body) {
var activationToken = body.token;
var tokenExpirationTime = body.expires_in_minutes * 60 * 1000;
myConsole.debug('Received new ActivationToken %s, reset potential old ActivationToken in cache', activationToken);
activationTokenEntity.clearTimeoutAndInterval();
activationTokenEntity.resetActivationTokenCache();
body.token_received_time = Date.now();
activationTokenEntity.storeActivationTokenCache(body);
activationTokenEntity.handleToken(activationToken, tokenExpirationTime);
onSuccess(res, body);
})
.catch(function (err) {
activationTokenEntity.clearTimeoutAndInterval();
myConsole.error('Error during creation/handling activationToken %s', JSON.stringify(err));
onException(res, err);
});
});
};
};