-
Notifications
You must be signed in to change notification settings - Fork 0
/
snap4city-authentication-tunnel.js
181 lines (170 loc) · 9.79 KB
/
snap4city-authentication-tunnel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/* NODE-RED-CONTRIB-SNAP4CITY-TUNNEL
Copyright (C) 2018 DISIT Lab http://www.disit.org - University of Florence
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
module.exports = function (RED) {
function Snap4cityAuthenticationTunnel(config) {
RED.nodes.createNode(this, config);
var node = this;
node.name = config.name;
node.domain = config.domain;
node.domainLight = config.domain.replace("https://", "").replace("http://", "").replace("/", "");
node.isMainAccount = config.ismainaccount;
var s4cUtility = require("./snap4city-utility.js");
const logger = s4cUtility.getLogger(RED, node);
node.s4cAuth = this;
this.setNewOwnership = function (accessToken, uid) {
var os = require('os');
var homedir = os.homedir() + "/";
var fs = require('fs');
logger.info("Try to set new ownership on " + node.domain);
if (!fs.existsSync(__dirname + "/../node-red-contrib-snap4city-developer/config/ownership") && !fs.existsSync(__dirname + "/../node-red-contrib-snap4city-user/config/ownership") && !fs.existsSync(__dirname + "/../../../.snap4cityConfig/ownership") && !fs.existsSync(homedir + ".snap4cityConfig/ownership")) {
var ifaces = os.networkInterfaces();
var url = s4cUtility.settingUrl(RED,node, "ownershipUrl", "https://www.snap4city.org", "/ownership-api/v1/") + "register/";
var params = "?accessToken=" + accessToken;
var iplocal = null;
Object.keys(ifaces).forEach(function (ifname) {
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (iface.address.indexOf("192.168") != -1) {
iplocal = iface.address;
return;
}
});
});
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
logger.info(encodeURI(url));
xmlHttp.open("POST", encodeURI(url + params), false);
xmlHttp.setRequestHeader("Content-Type", "application/json");
var message = {
elementId: uid,
elementType: "AppID",
elementName: new Date().toJSON().slice(0, 16),
elementUrl: "http://" + iplocal + ":" + RED.settings.uiPort,
elementDetails: {
edgegateway_type: os.platform() + "_" + os.type() + "_" + os.release()
}
};
xmlHttp.send(JSON.stringify(message));
if (xmlHttp.responseText != "") {
try {
response = JSON.parse(xmlHttp.responseText)
logger.info("ResponseText: " + xmlHttp.responseText + " status: " + xmlHttp.status);
if (typeof response.error == "undefined") {
if (fs.existsSync(__dirname + "/../node-red-contrib-snap4city-user")) {
if (!fs.existsSync(__dirname + "/../node-red-contrib-snap4city-user/config")) {
fs.mkdirSync(__dirname + "/../node-red-contrib-snap4city-user/config");
}
fs.writeFileSync(__dirname + "/../node-red-contrib-snap4city-user/config/ownership", "");
}
if (fs.existsSync(__dirname + "/../node-red-contrib-snap4city-developer")) {
if (!fs.existsSync(__dirname + "/../node-red-contrib-snap4city-developer/config")) {
fs.mkdirSync(__dirname + "/../node-red-contrib-snap4city-developer/config");
}
fs.writeFileSync(__dirname + "/../node-red-contrib-snap4city-developer/config/ownership", "");
}
if (fs.existsSync(homedir + ".snap4cityConfig")) {
if (!fs.existsSync(homedir + ".snap4cityConfig")) {
fs.mkdirSync(homedir + ".snap4cityConfig");
}
fs.writeFileSync(homedir + ".snap4cityConfig/ownership_" + node.domainLight, "");
}
}
} catch (e) {}
}
} else {
if (fs.existsSync(__dirname + "/../node-red-contrib-snap4city-user/config/ownership_" + node.domainLight) || fs.existsSync(__dirname + "/../node-red-contrib-snap4city-developer/config/ownership_" + node.domainLight)) {
if (!fs.existsSync(homedir + ".snap4cityConfig")) {
fs.mkdirSync(homedir + ".snap4cityConfig");
}
fs.writeFileSync(homedir + ".snap4cityConfig/ownership_" + node.domainLight, "");
}
}
}
this.retrieveCurrentUser = function () {
return node.credentials.user.toLowerCase();
}
this.refreshTokenGetAccessToken = function (uid) {
var s4cUtility = require("./snap4city-utility.js");
const logger = s4cUtility.getLogger(RED, node);
var url = s4cUtility.settingUrl(RED,node, "keycloakBaseUri", "https://www.snap4city.org", "/auth/realms/master/") + "protocol/openid-connect/token/";
logger.info(url);
var params = "";
var expiresTimestamp = node.credentials.expiresTimestamp;
var refreshToken = node.credentials.refreshToken;
if (typeof refreshToken == "undefined" || typeof expiresTimestamp == "undefined" || new Date().getTime() > expiresTimestamp) {
params = "client_id=" + (RED.settings.keycloakClientid ? RED.settings.keycloakClientid : "nodered-iotedge") + "&grant_type=password&username=" + node.credentials.user + "&password=" + encodeURIComponent(node.credentials.password);
} else {
params = "client_id=" + (RED.settings.keycloakClientid ? RED.settings.keycloakClientid : "nodered-iotedge") + "&grant_type=refresh_token&scope=openid profile&refresh_token=" + refreshToken;
}
var response = "";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
logger.info("Refresh token");
logger.silly("Refresh token from:" + encodeURI(url) + " with parameters: " + params);
xmlHttp.open("POST", encodeURI(url), false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(params);
//logger.info(xmlHttp.responseText);
if (xmlHttp.responseText != "") {
try {
response = JSON.parse(xmlHttp.responseText);
if (response.access_token != null && uid != null) {
if (typeof expiresTimestamp == "undefined") {
if (node.isMainAccount) {
this.setNewOwnership(response.access_token, uid);
}
}
node.credentials.accessToken = response.access_token;
}
if (response.refresh_token != null) {
node.credentials.refreshToken = response.refresh_token;
}
if (response.refresh_expires_in != null) {
node.credentials.expiresTimestamp = (new Date().getTime()) + response.refresh_expires_in * 1000;
}
} catch (e) {
logger.error("Problem Parsing this data: " + xmlHttp.responseText);
}
if (response != "") {
if (response.access_token != null) {
return response.access_token;
} else {
return "";
}
}
}
return response;
}
}
RED.httpAdmin.post("/retrieveAccessTokenAuthentication/", RED.auth.needsPermission('snap4city-authentication-tunnel.read'), function (req, res) {
var s4cUtility = require("./snap4city-utility.js");
res.json({
"accessToken": s4cUtility.retrieveAccessToken(RED, RED.nodes.getNode(req.body.nodeId), req.body.authenticationNodeId, null),
"username": s4cUtility.retrieveCurrentUser(RED, RED.nodes.getNode(req.body.nodeId), req.body.authenticationNodeId),
"appId": s4cUtility.retrieveAppID(RED),
});
});
RED.nodes.registerType("snap4city-authentication-tunnel", Snap4cityAuthenticationTunnel, {
credentials: {
user: {
type: "text"
},
password: {
type: "password"
}
}
});
}