diff --git a/application/src/main/data/json/system/widget_bundles/control_widgets.json b/application/src/main/data/json/system/widget_bundles/control_widgets.json index 4756b149c3..1de1bae6f1 100644 --- a/application/src/main/data/json/system/widget_bundles/control_widgets.json +++ b/application/src/main/data/json/system/widget_bundles/control_widgets.json @@ -18,8 +18,8 @@ "resources": [], "templateHtml": "
", "templateCss": ".cmd .cursor.blink {\n -webkit-animation-name: terminal-underline;\n -moz-animation-name: terminal-underline;\n -ms-animation-name: terminal-underline;\n animation-name: terminal-underline;\n}\n.terminal .inverted, .cmd .inverted {\n border-bottom-color: #aaa;\n}\n\n", - "controllerScript": "var requestTimeout = 500;\nvar multiParams = false;\nvar useRowStyleFunction = false;\nvar styleObj = {};\n\nself.onInit = function() {\n var subscription = self.ctx.defaultSubscription;\n var rpcEnabled = subscription.rpcEnabled;\n var deviceName = 'Simulated';\n var prompt;\n if (subscription.targetDeviceName && subscription.targetDeviceName.length) {\n deviceName = subscription.targetDeviceName;\n }\n if (self.ctx.settings.requestTimeout) {\n requestTimeout = self.ctx.settings.requestTimeout;\n }\n if (self.ctx.settings.multiParams) {\n multiParams = self.ctx.settings.multiParams;\n }\n if (self.ctx.settings.useRowStyleFunction && self.ctx.settings.rowStyleFunction) {\n try {\n var style = self.ctx.settings.rowStyleFunction;\n styleObj = JSON.parse(style);\n if ((typeof styleObj !== \"object\")) {\n styleObj = null;\n throw new URIError(`${style === null ? 'null' : typeof style} instead of style object`);\n }\n else if (typeof styleObj === \"object\" && (typeof styleObj.length) === \"number\") {\n styleObj = null;\n throw new URIError('Array instead of style object');\n }\n }\n catch (e) {\n console.log(`Row style function in widget ` +\n `returns '${e}'. Please check your row style function.`); \n }\n useRowStyleFunction = self.ctx.settings.useRowStyleFunction;\n \n }\n var greetings = 'Welcome to ThingsBoard RPC debug terminal.\\n\\n';\n if (!rpcEnabled) {\n greetings += 'Target device is not set!\\n\\n';\n prompt = '';\n } else {\n greetings += 'Current target device for RPC commands: [[b;#fff;]' + deviceName + ']\\n\\n';\n greetings += 'Please type [[b;#fff;]\\'help\\'] to see usage.\\n';\n prompt = '[[b;#8bc34a;]' + deviceName +']> ';\n }\n \n var terminal = $('#device-terminal', self.ctx.$container).terminal(\n function(command) {\n if (command !== '') {\n try {\n var localCommand = command.trim();\n var requestUUID = uuidv4();\n if (localCommand === 'help') {\n printUsage(this);\n } else {\n var cmdObj = $.terminal.parse_command(localCommand);\n if (cmdObj.args) {\n if (!multiParams && cmdObj.args.length > 1) {\n this.error(\"Wrong number of arguments!\");\n this.echo(' ');\n }\n else {\n if (cmdObj.args.length) {\n var params = getMultiParams(cmdObj.args);\n }\n performRpc(this, cmdObj.name, params, requestUUID);\n }\n }\n \n }\n } catch(e) {\n this.error(new String(e));\n }\n } else {\n this.echo('');\n }\n }, {\n greetings: greetings,\n prompt: prompt,\n enabled: rpcEnabled\n });\n \n if (styleObj && styleObj !== null) {\n terminal.css(styleObj);\n }\n \n if (!rpcEnabled) {\n terminal.error('No RPC target detected!').pause();\n }\n}\n\n\nfunction printUsage(terminal) {\n var commandsListText = '\\n[[b;#fff;]Usage:]\\n';\n commandsListText += ' [params body]]\\n\\n';\n commandsListText += '[[b;#fff;]Example 1 (multiParams===false):]\\n'; \n commandsListText += ' myRemoteMethod1 myText\\n\\n'; \n commandsListText += '[[b;#fff;]Example 2 (multiParams===false):]\\n'; \n commandsListText += ' myOtherRemoteMethod \"{\\\\\"key1\\\\\":2,\\\\\"key2\\\\\":\\\\\"myVal\\\\\"}\"\\n\\n'; \n commandsListText += '[[b;#fff;]Example 3 (multiParams===true)]\\n'; \n commandsListText += ' [params body] = \"all the string after the method, including spaces\"]\\n';\n commandsListText += ' myOtherRemoteMethod \"{\\\\\"key1\\\\\": \"battery level\", \\\\\"key2\\\\\": \\\\\"myVal\\\\\"}\"\\n'; \n terminal.echo(new String(commandsListText));\n}\n\nfunction performRpc(terminal, method, params, requestUUID) {\n terminal.pause();\n self.ctx.controlApi.sendTwoWayCommand(method, params, requestTimeout, requestUUID).subscribe(\n function success(responseBody) {\n terminal.echo(JSON.stringify(responseBody));\n terminal.echo(' ');\n terminal.resume();\n },\n function fail() {\n var errorText = self.ctx.defaultSubscription.rpcErrorText;\n terminal.error(errorText);\n terminal.echo(' ');\n terminal.resume();\n }\n );\n}\n\nfunction getMultiParams(cmdObj) {\n var params = \"\";\n cmdObj.forEach((element) => {\n try {\n params += \" \" + JSON.strigify(JSON.parse(element));\n } catch (e) {\n params += \" \" + element;\n }\n })\n return params.trim();\n}\n\n\nfunction uuidv4() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n \nself.onDestroy = function() {\n}", - "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"requestTimeout\": {\n \"title\": \"RPC request timeout (ms)\",\n \"type\": \"number\",\n \"default\": 500\n },\n \"multiParams\": {\n \"title\": \"RPC params All line\",\n \"type\": \"boolean\",\n \"default\": false\n },\n \"useRowStyleFunction\": {\n \"title\": \"Use row style function\",\n \"type\": \"boolean\",\n \"default\": false\n },\n \"rowStyleFunction\": {\n \"title\": \"Row style function: f(entity, ctx)\",\n \"type\": \"string\",\n \"default\": \"\"\n }\n },\n \"required\": [\"requestTimeout\"]\n },\n \"form\": [\n \"requestTimeout\",\n \"multiParams\",\n \"useRowStyleFunction\",\n {\n \"key\": \"rowStyleFunction\",\n \"type\": \"javascript\",\n \"condition\": \"model.useRowStyleFunction === true\"\n }\n ]\n}", + "controllerScript": "var requestTimeout = 500;\n\nself.onInit = function() {\n var subscription = self.ctx.defaultSubscription;\n var rpcEnabled = subscription.rpcEnabled;\n var deviceName = 'Simulated';\n var prompt;\n if (subscription.targetDeviceName && subscription.targetDeviceName.length) {\n deviceName = subscription.targetDeviceName;\n }\n if (self.ctx.settings.requestTimeout) {\n requestTimeout = self.ctx.settings.requestTimeout;\n }\n var greetings = 'Welcome to ThingsBoard RPC debug terminal.\\n\\n';\n if (!rpcEnabled) {\n greetings += 'Target device is not set!\\n\\n';\n prompt = '';\n } else {\n greetings += 'Current target device for RPC commands: [[b;#fff;]' + deviceName + ']\\n\\n';\n greetings += 'Please type [[b;#fff;]\\'help\\'] to see usage.\\n';\n prompt = '[[b;#8bc34a;]' + deviceName +']> ';\n }\n \n var terminal = $('#device-terminal', self.ctx.$container).terminal(\n function(command) {\n if (command !== '') {\n try {\n var localCommand = command.trim();\n var requestUUID = uuidv4();\n if (localCommand === 'help') {\n printUsage(this);\n } else {\n var spaceIndex = localCommand.indexOf(' ');\n if (spaceIndex === -1 && !localCommand.length) {\n this.error(\"Wrong number of arguments!\");\n this.echo(' ');\n } else {\n var params;\n if (spaceIndex === -1) {\n spaceIndex = localCommand.length;\n }\n var name = localCommand.substr(0, spaceIndex);\n var args = localCommand.substr(spaceIndex + 1);\n if (args.length) {\n try {\n params = JSON.parse(args);\n } catch (e) {\n params = args;\n }\n }\n performRpc(this, name, params, requestUUID);\n }\n }\n } catch(e) {\n this.error(new String(e));\n }\n } else {\n this.echo('');\n }\n }, {\n greetings: greetings,\n prompt: prompt,\n enabled: rpcEnabled\n });\n \n if (!rpcEnabled) {\n terminal.error('No RPC target detected!').pause();\n }\n}\n\n\nfunction printUsage(terminal) {\n var commandsListText = '\\n[[b;#fff;]Usage:]\\n';\n commandsListText += ' [params body]]\\n\\n';\n commandsListText += '[[b;#fff;]Example 1:]\\n'; \n commandsListText += ' myRemoteMethod1 myText\\n\\n'; \n commandsListText += '[[b;#fff;]Example 2:]\\n'; \n commandsListText += ' myOtherRemoteMethod \"{\\\\\"key1\\\\\": 2, \\\\\"key2\\\\\": \\\\\"myVal\\\\\"}\"\\n'; \n terminal.echo(new String(commandsListText));\n}\n\n\nfunction performRpc(terminal, method, params, requestUUID) {\n terminal.pause();\n self.ctx.controlApi.sendTwoWayCommand(method, params, requestTimeout, requestUUID).subscribe(\n function success(responseBody) {\n terminal.echo(JSON.stringify(responseBody));\n terminal.echo(' ');\n terminal.resume();\n },\n function fail() {\n var errorText = self.ctx.defaultSubscription.rpcErrorText;\n terminal.error(errorText);\n terminal.echo(' ');\n terminal.resume();\n }\n );\n}\n\n\nfunction uuidv4() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n \nself.onDestroy = function() {\n}", + "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"requestTimeout\": {\n \"title\": \"RPC request timeout (ms)\",\n \"type\": \"number\",\n \"default\": 500\n }\n },\n \"required\": [\"requestTimeout\"]\n },\n \"form\": [\n \"requestTimeout\"\n ]\n}", "dataKeySettingsSchema": "{}\n", "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":true,\"backgroundColor\":\"#010101\",\"color\":\"rgba(255, 254, 254, 0.87)\",\"padding\":\"0px\",\"settings\":{\"parseGpioStatusFunction\":\"return body[pin] === true;\",\"gpioStatusChangeRequest\":{\"method\":\"setGpioStatus\",\"paramsBody\":\"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"},\"requestTimeout\":500,\"switchPanelBackgroundColor\":\"#b71c1c\",\"gpioStatusRequest\":{\"method\":\"getGpioStatus\",\"paramsBody\":\"{}\"},\"gpioList\":[{\"pin\":1,\"label\":\"GPIO 1\",\"row\":0,\"col\":0,\"_uniqueKey\":0},{\"pin\":2,\"label\":\"GPIO 2\",\"row\":0,\"col\":1,\"_uniqueKey\":1},{\"pin\":3,\"label\":\"GPIO 3\",\"row\":1,\"col\":0,\"_uniqueKey\":2}]},\"title\":\"RPC debug terminal\",\"dropShadow\":true,\"enableFullscreen\":true,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"useDashboardTimewindow\":true,\"showLegend\":false,\"actions\":{}}" } @@ -151,4 +151,4 @@ } } ] -} \ No newline at end of file +} diff --git a/application/src/main/data/upgrade/3.2.2/schema_update.sql b/application/src/main/data/upgrade/3.2.2/schema_update.sql index 30bc80a458..d57668de0d 100644 --- a/application/src/main/data/upgrade/3.2.2/schema_update.sql +++ b/application/src/main/data/upgrade/3.2.2/schema_update.sql @@ -136,7 +136,7 @@ CREATE TABLE IF NOT EXISTS oauth2_mobile ( oauth2_params_id uuid NOT NULL, created_time bigint NOT NULL, pkg_name varchar(255), - callback_url_scheme varchar(255), + app_secret varchar(2048), CONSTRAINT fk_mobile_oauth2_params FOREIGN KEY (oauth2_params_id) REFERENCES oauth2_params(id) ON DELETE CASCADE, CONSTRAINT oauth2_mobile_unq_key UNIQUE (oauth2_params_id, pkg_name) ); diff --git a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java index bc93253a73..26c230455b 100644 --- a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java +++ b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java @@ -39,6 +39,7 @@ import org.springframework.web.util.UriComponentsBuilder; import org.thingsboard.server.dao.oauth2.OAuth2Configuration; import org.thingsboard.server.dao.oauth2.OAuth2Service; import org.thingsboard.server.service.security.auth.oauth2.TbOAuth2ParameterNames; +import org.thingsboard.server.service.security.model.token.OAuth2AppTokenFactory; import org.thingsboard.server.utils.MiscUtils; import javax.servlet.http.HttpServletRequest; @@ -69,6 +70,9 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza @Autowired private OAuth2Service oAuth2Service; + @Autowired + private OAuth2AppTokenFactory oAuth2AppTokenFactory; + @Autowired(required = false) private OAuth2Configuration oauth2Configuration; @@ -78,7 +82,8 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza String registrationId = this.resolveRegistrationId(request); String redirectUriAction = getAction(request, "login"); String appPackage = getAppPackage(request); - return resolve(request, registrationId, redirectUriAction, appPackage); + String appToken = getAppToken(request); + return resolve(request, registrationId, redirectUriAction, appPackage, appToken); } @Override @@ -88,7 +93,8 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza } String redirectUriAction = getAction(request, "authorize"); String appPackage = getAppPackage(request); - return resolve(request, registrationId, redirectUriAction, appPackage); + String appToken = getAppToken(request); + return resolve(request, registrationId, redirectUriAction, appPackage, appToken); } private String getAction(HttpServletRequest request, String defaultAction) { @@ -103,8 +109,12 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza return request.getParameter("pkg"); } + private String getAppToken(HttpServletRequest request) { + return request.getParameter("appToken"); + } + @SuppressWarnings("deprecation") - private OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId, String redirectUriAction, String appPackage) { + private OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId, String redirectUriAction, String appPackage, String appToken) { if (registrationId == null) { return null; } @@ -117,10 +127,14 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza Map attributes = new HashMap<>(); attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()); if (!StringUtils.isEmpty(appPackage)) { - String callbackUrlScheme = this.oAuth2Service.findCallbackUrlScheme(UUID.fromString(registrationId), appPackage); - if (StringUtils.isEmpty(callbackUrlScheme)) { - throw new IllegalArgumentException("Invalid package: " + appPackage + ". No package info found for Client Registration."); + if (StringUtils.isEmpty(appToken)) { + throw new IllegalArgumentException("Invalid application token."); } else { + String appSecret = this.oAuth2Service.findAppSecret(UUID.fromString(registrationId), appPackage); + if (StringUtils.isEmpty(appSecret)) { + throw new IllegalArgumentException("Invalid package: " + appPackage + ". No application secret found for Client Registration with given application package."); + } + String callbackUrlScheme = this.oAuth2AppTokenFactory.validateTokenAndGetCallbackUrlScheme(appPackage, appToken, appSecret); attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, callbackUrlScheme); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java b/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java index 9e6d393b30..d94d26fc87 100644 --- a/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java +++ b/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java @@ -17,7 +17,6 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; -import org.eclipse.leshan.core.SecurityMode; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -45,14 +44,11 @@ import java.util.Map; public class Lwm2mController extends BaseController { @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") - @RequestMapping(value = "/lwm2m/deviceProfile/bootstrap/{securityMode}/{bootstrapServerIs}", method = RequestMethod.GET) + @RequestMapping(value = "/lwm2m/deviceProfile/bootstrap/{isBootstrapServer}", method = RequestMethod.GET) @ResponseBody - public ServerSecurityConfig getLwm2mBootstrapSecurityInfo(@PathVariable("securityMode") String strSecurityMode, - @PathVariable("bootstrapServerIs") boolean bootstrapServer) throws ThingsboardException { - checkNotNull(strSecurityMode); + public ServerSecurityConfig getLwm2mBootstrapSecurityInfo(@PathVariable("isBootstrapServer") boolean bootstrapServer) throws ThingsboardException { try { - SecurityMode securityMode = SecurityMode.valueOf(strSecurityMode); - return lwM2MServerSecurityInfoRepository.getServerSecurityInfo(securityMode, bootstrapServer); + return lwM2MServerSecurityInfoRepository.getServerSecurityInfo(bootstrapServer); } catch (Exception e) { throw handleException(e); } diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServerSecurityInfoRepository.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServerSecurityInfoRepository.java index 06190cdf70..78f849667f 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServerSecurityInfoRepository.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServerSecurityInfoRepository.java @@ -18,7 +18,6 @@ package org.thingsboard.server.service.lwm2m; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.eclipse.leshan.core.SecurityMode; import org.eclipse.leshan.core.util.Hex; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; @@ -50,40 +49,20 @@ public class LwM2MServerSecurityInfoRepository { private final LwM2MTransportServerConfig serverConfig; private final LwM2MTransportBootstrapConfig bootstrapConfig; - /** - * @param securityMode - * @param bootstrapServer - * @return ServerSecurityConfig more value is default: Important - port, host, publicKey - */ - public ServerSecurityConfig getServerSecurityInfo(SecurityMode securityMode, boolean bootstrapServer) { - ServerSecurityConfig result = getServerSecurityConfig(bootstrapServer ? bootstrapConfig : serverConfig, securityMode); + public ServerSecurityConfig getServerSecurityInfo(boolean bootstrapServer) { + ServerSecurityConfig result = getServerSecurityConfig(bootstrapServer ? bootstrapConfig : serverConfig); result.setBootstrapServerIs(bootstrapServer); return result; } - private ServerSecurityConfig getServerSecurityConfig(LwM2MSecureServerConfig serverConfig, SecurityMode securityMode) { + private ServerSecurityConfig getServerSecurityConfig(LwM2MSecureServerConfig serverConfig) { ServerSecurityConfig bsServ = new ServerSecurityConfig(); bsServ.setServerId(serverConfig.getId()); - switch (securityMode) { - case NO_SEC: - bsServ.setHost(serverConfig.getHost()); - bsServ.setPort(serverConfig.getPort()); - bsServ.setServerPublicKey(""); - break; - case PSK: - bsServ.setHost(serverConfig.getSecureHost()); - bsServ.setPort(serverConfig.getSecurePort()); - bsServ.setServerPublicKey(""); - break; - case RPK: - case X509: - bsServ.setHost(serverConfig.getSecureHost()); - bsServ.setPort(serverConfig.getSecurePort()); - bsServ.setServerPublicKey(getPublicKey(serverConfig.getCertificateAlias(), this.serverConfig.getPublicX(), this.serverConfig.getPublicY())); - break; - default: - break; - } + bsServ.setHost(serverConfig.getHost()); + bsServ.setPort(serverConfig.getPort()); + bsServ.setSecurityHost(serverConfig.getSecureHost()); + bsServ.setSecurityPort(serverConfig.getSecurePort()); + bsServ.setServerPublicKey(getPublicKey(serverConfig.getCertificateAlias(), this.serverConfig.getPublicX(), this.serverConfig.getPublicY())); return bsServ; } diff --git a/application/src/main/java/org/thingsboard/server/service/security/model/token/OAuth2AppTokenFactory.java b/application/src/main/java/org/thingsboard/server/service/security/model/token/OAuth2AppTokenFactory.java new file mode 100644 index 0000000000..fba1598a7f --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/security/model/token/OAuth2AppTokenFactory.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2016-2021 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.security.model.token; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureException; +import io.jsonwebtoken.UnsupportedJwtException; +import io.micrometer.core.instrument.util.StringUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +@Component +@Slf4j +public class OAuth2AppTokenFactory { + + private static final String CALLBACK_URL_SCHEME = "callbackUrlScheme"; + + private static final long MAX_EXPIRATION_TIME_DIFF_MS = TimeUnit.MINUTES.toMillis(5); + + public String validateTokenAndGetCallbackUrlScheme(String appPackage, String appToken, String appSecret) { + Jws jwsClaims; + try { + jwsClaims = Jwts.parser().setSigningKey(appSecret).parseClaimsJws(appToken); + } + catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { + throw new IllegalArgumentException("Invalid Application token: ", ex); + } catch (ExpiredJwtException expiredEx) { + throw new IllegalArgumentException("Application token expired", expiredEx); + } + Claims claims = jwsClaims.getBody(); + Date expiration = claims.getExpiration(); + if (expiration == null) { + throw new IllegalArgumentException("Application token must have expiration date"); + } + long timeDiff = expiration.getTime() - System.currentTimeMillis(); + if (timeDiff > MAX_EXPIRATION_TIME_DIFF_MS) { + throw new IllegalArgumentException("Application token expiration time can't be longer than 5 minutes"); + } + if (!claims.getIssuer().equals(appPackage)) { + throw new IllegalArgumentException("Application token issuer doesn't match application package"); + } + String callbackUrlScheme = claims.get(CALLBACK_URL_SCHEME, String.class); + if (StringUtils.isEmpty(callbackUrlScheme)) { + throw new IllegalArgumentException("Application token doesn't have callbackUrlScheme"); + } + return callbackUrlScheme; + } + +} diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Service.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Service.java index 0e9a36c05e..9764137cf2 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Service.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Service.java @@ -42,5 +42,5 @@ public interface OAuth2Service { List findAllRegistrations(); - String findCallbackUrlScheme(UUID registrationId, String pkgName); + String findAppSecret(UUID registrationId, String pkgName); } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/lwm2m/ServerSecurityConfig.java b/common/data/src/main/java/org/thingsboard/server/common/data/lwm2m/ServerSecurityConfig.java index 8777e08066..8220702ec8 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/lwm2m/ServerSecurityConfig.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/lwm2m/ServerSecurityConfig.java @@ -20,7 +20,9 @@ import lombok.Data; @Data public class ServerSecurityConfig { String host; + String securityHost; Integer port; + Integer securityPort; String serverPublicKey; boolean bootstrapServerIs = true; Integer clientHoldOffTime = 1; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2Mobile.java b/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2Mobile.java index b3249a1ed5..53a6d41e5c 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2Mobile.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2Mobile.java @@ -31,12 +31,12 @@ public class OAuth2Mobile extends BaseData { private OAuth2ParamsId oauth2ParamsId; private String pkgName; - private String callbackUrlScheme; + private String appSecret; public OAuth2Mobile(OAuth2Mobile mobile) { super(mobile); this.oauth2ParamsId = mobile.oauth2ParamsId; this.pkgName = mobile.pkgName; - this.callbackUrlScheme = mobile.callbackUrlScheme; + this.appSecret = mobile.appSecret; } } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2MobileInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2MobileInfo.java index 18fbd49dcd..c04a1a9fd1 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2MobileInfo.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/oauth2/OAuth2MobileInfo.java @@ -30,5 +30,5 @@ import lombok.ToString; @Builder public class OAuth2MobileInfo { private String pkgName; - private String callbackUrlScheme; + private String appSecret; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java b/dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java index 32b5afc9aa..87cee53991 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java @@ -418,7 +418,7 @@ public class ModelConstants { public static final String OAUTH2_MOBILE_COLUMN_FAMILY_NAME = "oauth2_mobile"; public static final String OAUTH2_PARAMS_ID_PROPERTY = "oauth2_params_id"; public static final String OAUTH2_PKG_NAME_PROPERTY = "pkg_name"; - public static final String OAUTH2_CALLBACK_URL_SCHEME_PROPERTY = "callback_url_scheme"; + public static final String OAUTH2_APP_SECRET_PROPERTY = "app_secret"; public static final String OAUTH2_CLIENT_REGISTRATION_INFO_COLUMN_FAMILY_NAME = "oauth2_client_registration_info"; public static final String OAUTH2_CLIENT_REGISTRATION_COLUMN_FAMILY_NAME = "oauth2_client_registration"; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/OAuth2MobileEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/OAuth2MobileEntity.java index 403f7af958..a6517011b0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/OAuth2MobileEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/OAuth2MobileEntity.java @@ -40,8 +40,8 @@ public class OAuth2MobileEntity extends BaseSqlEntity { @Column(name = ModelConstants.OAUTH2_PKG_NAME_PROPERTY) private String pkgName; - @Column(name = ModelConstants.OAUTH2_CALLBACK_URL_SCHEME_PROPERTY) - private String callbackUrlScheme; + @Column(name = ModelConstants.OAUTH2_APP_SECRET_PROPERTY) + private String appSecret; public OAuth2MobileEntity() { super(); @@ -56,7 +56,7 @@ public class OAuth2MobileEntity extends BaseSqlEntity { this.oauth2ParamsId = mobile.getOauth2ParamsId().getId(); } this.pkgName = mobile.getPkgName(); - this.callbackUrlScheme = mobile.getCallbackUrlScheme(); + this.appSecret = mobile.getAppSecret(); } @Override @@ -66,7 +66,7 @@ public class OAuth2MobileEntity extends BaseSqlEntity { mobile.setCreatedTime(createdTime); mobile.setOauth2ParamsId(new OAuth2ParamsId(oauth2ParamsId)); mobile.setPkgName(pkgName); - mobile.setCallbackUrlScheme(callbackUrlScheme); + mobile.setAppSecret(appSecret); return mobile; } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2RegistrationDao.java b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2RegistrationDao.java index de80334577..87f0d56460 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2RegistrationDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2RegistrationDao.java @@ -29,6 +29,6 @@ public interface OAuth2RegistrationDao extends Dao { List findByOAuth2ParamsId(UUID oauth2ParamsId); - String findCallbackUrlScheme(UUID id, String pkgName); + String findAppSecret(UUID id, String pkgName); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2ServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2ServiceImpl.java index 6c2126a005..83a134ea36 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2ServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2ServiceImpl.java @@ -21,7 +21,23 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.thingsboard.server.common.data.BaseData; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.oauth2.*; +import org.thingsboard.server.common.data.oauth2.MapperType; +import org.thingsboard.server.common.data.oauth2.OAuth2BasicMapperConfig; +import org.thingsboard.server.common.data.oauth2.OAuth2ClientInfo; +import org.thingsboard.server.common.data.oauth2.OAuth2CustomMapperConfig; +import org.thingsboard.server.common.data.oauth2.OAuth2Domain; +import org.thingsboard.server.common.data.oauth2.OAuth2DomainInfo; +import org.thingsboard.server.common.data.oauth2.OAuth2Info; +import org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig; +import org.thingsboard.server.common.data.oauth2.OAuth2Mobile; +import org.thingsboard.server.common.data.oauth2.OAuth2MobileInfo; +import org.thingsboard.server.common.data.oauth2.OAuth2Params; +import org.thingsboard.server.common.data.oauth2.OAuth2ParamsInfo; +import org.thingsboard.server.common.data.oauth2.OAuth2Registration; +import org.thingsboard.server.common.data.oauth2.OAuth2RegistrationInfo; +import org.thingsboard.server.common.data.oauth2.PlatformType; +import org.thingsboard.server.common.data.oauth2.SchemeType; +import org.thingsboard.server.common.data.oauth2.TenantNameStrategyType; import org.thingsboard.server.common.data.oauth2.deprecated.ClientRegistrationDto; import org.thingsboard.server.common.data.oauth2.deprecated.DomainInfo; import org.thingsboard.server.common.data.oauth2.deprecated.ExtendedOAuth2ClientRegistrationInfo; @@ -36,7 +52,11 @@ import org.thingsboard.server.dao.oauth2.deprecated.OAuth2ClientRegistrationDao; import org.thingsboard.server.dao.oauth2.deprecated.OAuth2ClientRegistrationInfoDao; import javax.transaction.Transactional; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -164,11 +184,11 @@ public class OAuth2ServiceImpl extends AbstractEntityService implements OAuth2Se } @Override - public String findCallbackUrlScheme(UUID id, String pkgName) { - log.trace("Executing findCallbackUrlScheme [{}][{}]", id, pkgName); + public String findAppSecret(UUID id, String pkgName) { + log.trace("Executing findAppSecret [{}][{}]", id, pkgName); validateId(id, INCORRECT_CLIENT_REGISTRATION_ID + id); validateString(pkgName, "Incorrect package name"); - return oauth2RegistrationDao.findCallbackUrlScheme(id, pkgName); + return oauth2RegistrationDao.findAppSecret(id, pkgName); } @@ -323,8 +343,11 @@ public class OAuth2ServiceImpl extends AbstractEntityService implements OAuth2Se if (StringUtils.isEmpty(mobileInfo.getPkgName())) { throw new DataValidationException("Package should be specified!"); } - if (StringUtils.isEmpty(mobileInfo.getCallbackUrlScheme())) { - throw new DataValidationException("Callback URL scheme should be specified!"); + if (StringUtils.isEmpty(mobileInfo.getAppSecret())) { + throw new DataValidationException("Application secret should be specified!"); + } + if (mobileInfo.getAppSecret().length() < 16) { + throw new DataValidationException("Application secret should be at least 16 characters!"); } } oauth2Params.getMobileInfos().stream() diff --git a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Utils.java b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Utils.java index 896c619c82..c34875d014 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Utils.java +++ b/dao/src/main/java/org/thingsboard/server/dao/oauth2/OAuth2Utils.java @@ -148,7 +148,7 @@ public class OAuth2Utils { public static OAuth2MobileInfo toOAuth2MobileInfo(OAuth2Mobile mobile) { return OAuth2MobileInfo.builder() .pkgName(mobile.getPkgName()) - .callbackUrlScheme(mobile.getCallbackUrlScheme()) + .appSecret(mobile.getAppSecret()) .build(); } @@ -191,7 +191,7 @@ public class OAuth2Utils { OAuth2Mobile mobile = new OAuth2Mobile(); mobile.setOauth2ParamsId(oauth2ParamsId); mobile.setPkgName(mobileInfo.getPkgName()); - mobile.setCallbackUrlScheme(mobileInfo.getCallbackUrlScheme()); + mobile.setAppSecret(mobileInfo.getAppSecret()); return mobile; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/oauth2/JpaOAuth2RegistrationDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/oauth2/JpaOAuth2RegistrationDao.java index 0b09f7ddea..ef35371b6e 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/oauth2/JpaOAuth2RegistrationDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/oauth2/JpaOAuth2RegistrationDao.java @@ -57,8 +57,8 @@ public class JpaOAuth2RegistrationDao extends JpaAbstractDao findByOauth2ParamsId(UUID oauth2ParamsId); - @Query("SELECT mobile.callbackUrlScheme " + + @Query("SELECT mobile.appSecret " + "FROM OAuth2MobileEntity mobile " + "LEFT JOIN OAuth2RegistrationEntity reg on mobile.oauth2ParamsId = reg.oauth2ParamsId " + "WHERE reg.id = :registrationId " + "AND mobile.pkgName = :pkgName") - String findCallbackUrlScheme(@Param("registrationId") UUID id, - @Param("pkgName") String pkgName); + String findAppSecret(@Param("registrationId") UUID id, + @Param("pkgName") String pkgName); } diff --git a/dao/src/main/resources/sql/schema-entities-hsql.sql b/dao/src/main/resources/sql/schema-entities-hsql.sql index ad3a023a41..16522becde 100644 --- a/dao/src/main/resources/sql/schema-entities-hsql.sql +++ b/dao/src/main/resources/sql/schema-entities-hsql.sql @@ -431,7 +431,7 @@ CREATE TABLE IF NOT EXISTS oauth2_mobile ( oauth2_params_id uuid NOT NULL, created_time bigint NOT NULL, pkg_name varchar(255), - callback_url_scheme varchar(255), + app_secret varchar(2048), CONSTRAINT fk_mobile_oauth2_params FOREIGN KEY (oauth2_params_id) REFERENCES oauth2_params(id) ON DELETE CASCADE, CONSTRAINT oauth2_mobile_unq_key UNIQUE (oauth2_params_id, pkg_name) ); diff --git a/dao/src/main/resources/sql/schema-entities.sql b/dao/src/main/resources/sql/schema-entities.sql index 890d639a01..88386a11dd 100644 --- a/dao/src/main/resources/sql/schema-entities.sql +++ b/dao/src/main/resources/sql/schema-entities.sql @@ -468,7 +468,7 @@ CREATE TABLE IF NOT EXISTS oauth2_mobile ( oauth2_params_id uuid NOT NULL, created_time bigint NOT NULL, pkg_name varchar(255), - callback_url_scheme varchar(255), + app_secret varchar(2048), CONSTRAINT fk_mobile_oauth2_params FOREIGN KEY (oauth2_params_id) REFERENCES oauth2_params(id) ON DELETE CASCADE, CONSTRAINT oauth2_mobile_unq_key UNIQUE (oauth2_params_id, pkg_name) ); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseOAuth2ServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseOAuth2ServiceTest.java index ae2ff054ec..4077bb2176 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseOAuth2ServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseOAuth2ServiceTest.java @@ -15,8 +15,8 @@ */ package org.thingsboard.server.dao.service; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -487,7 +487,7 @@ public class BaseOAuth2ServiceTest extends AbstractServiceTest { } @Test - public void testFindCallbackUrlScheme() { + public void testFindAppSecret() { OAuth2Info oAuth2Info = new OAuth2Info(true, Lists.newArrayList( OAuth2ParamsInfo.builder() .domainInfos(Lists.newArrayList( @@ -496,8 +496,8 @@ public class BaseOAuth2ServiceTest extends AbstractServiceTest { OAuth2DomainInfo.builder().name("third-domain").scheme(SchemeType.HTTPS).build() )) .mobileInfos(Lists.newArrayList( - OAuth2MobileInfo.builder().pkgName("com.test.pkg1").callbackUrlScheme("testPkg1Callback").build(), - OAuth2MobileInfo.builder().pkgName("com.test.pkg2").callbackUrlScheme("testPkg2Callback").build() + validMobileInfo("com.test.pkg1", "testPkg1AppSecret"), + validMobileInfo("com.test.pkg2", "testPkg2AppSecret") )) .clientRegistrations(Lists.newArrayList( validRegistrationInfo(), @@ -527,14 +527,14 @@ public class BaseOAuth2ServiceTest extends AbstractServiceTest { for (OAuth2ClientInfo clientInfo : firstDomainHttpClients) { String[] segments = clientInfo.getUrl().split("/"); String registrationId = segments[segments.length-1]; - String callbackUrlScheme = oAuth2Service.findCallbackUrlScheme(UUID.fromString(registrationId), "com.test.pkg1"); - Assert.assertNotNull(callbackUrlScheme); - Assert.assertEquals("testPkg1Callback", callbackUrlScheme); - callbackUrlScheme = oAuth2Service.findCallbackUrlScheme(UUID.fromString(registrationId), "com.test.pkg2"); - Assert.assertNotNull(callbackUrlScheme); - Assert.assertEquals("testPkg2Callback", callbackUrlScheme); - callbackUrlScheme = oAuth2Service.findCallbackUrlScheme(UUID.fromString(registrationId), "com.test.pkg3"); - Assert.assertNull(callbackUrlScheme); + String appSecret = oAuth2Service.findAppSecret(UUID.fromString(registrationId), "com.test.pkg1"); + Assert.assertNotNull(appSecret); + Assert.assertEquals("testPkg1AppSecret", appSecret); + appSecret = oAuth2Service.findAppSecret(UUID.fromString(registrationId), "com.test.pkg2"); + Assert.assertNotNull(appSecret); + Assert.assertEquals("testPkg2AppSecret", appSecret); + appSecret = oAuth2Service.findAppSecret(UUID.fromString(registrationId), "com.test.pkg3"); + Assert.assertNull(appSecret); } } @@ -548,8 +548,8 @@ public class BaseOAuth2ServiceTest extends AbstractServiceTest { OAuth2DomainInfo.builder().name("third-domain").scheme(SchemeType.HTTPS).build() )) .mobileInfos(Lists.newArrayList( - OAuth2MobileInfo.builder().pkgName("com.test.pkg1").callbackUrlScheme("testPkg1Callback").build(), - OAuth2MobileInfo.builder().pkgName("com.test.pkg2").callbackUrlScheme("testPkg2Callback").build() + validMobileInfo("com.test.pkg1", "testPkg1Callback"), + validMobileInfo("com.test.pkg2", "testPkg2Callback") )) .clientRegistrations(Lists.newArrayList( validRegistrationInfo("Google", Arrays.asList(PlatformType.WEB, PlatformType.ANDROID)), @@ -651,4 +651,10 @@ public class BaseOAuth2ServiceTest extends AbstractServiceTest { ) .build(); } + + private OAuth2MobileInfo validMobileInfo(String pkgName, String appSecret) { + return OAuth2MobileInfo.builder().pkgName(pkgName) + .appSecret(appSecret != null ? appSecret : RandomStringUtils.randomAlphanumeric(24)) + .build(); + } } diff --git a/ui-ngx/src/app/core/http/device-profile.service.ts b/ui-ngx/src/app/core/http/device-profile.service.ts index 556567e47b..6107a0853e 100644 --- a/ui-ngx/src/app/core/http/device-profile.service.ts +++ b/ui-ngx/src/app/core/http/device-profile.service.ts @@ -18,20 +18,22 @@ import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { PageLink } from '@shared/models/page/page-link'; import { defaultHttpOptionsFromConfig, RequestConfig } from './http-utils'; -import { Observable, throwError } from 'rxjs'; +import { Observable, of, throwError } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { DeviceProfile, DeviceProfileInfo, DeviceTransportType } from '@shared/models/device.models'; import { isDefinedAndNotNull, isEmptyStr } from '@core/utils'; import { ObjectLwM2M, ServerSecurityConfig } from '@home/components/profile/device/lwm2m/lwm2m-profile-config.models'; import { SortOrder } from '@shared/models/page/sort-order'; import { OtaPackageService } from '@core/http/ota-package.service'; -import { mergeMap } from 'rxjs/operators'; +import { mergeMap, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class DeviceProfileService { + private lwm2mBootstrapSecurityInfoInMemoryCache = new Map(); + constructor( private http: HttpClient, private otaPackageService: OtaPackageService @@ -58,12 +60,18 @@ export class DeviceProfileService { return this.http.get>(url, defaultHttpOptionsFromConfig(config)); } - public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean, - config?: RequestConfig): Observable { - return this.http.get( - `/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`, - defaultHttpOptionsFromConfig(config) - ); + public getLwm2mBootstrapSecurityInfo(isBootstrapServer: boolean, config?: RequestConfig): Observable { + const securityConfig = this.lwm2mBootstrapSecurityInfoInMemoryCache.get(isBootstrapServer); + if (securityConfig) { + return of(securityConfig); + } else { + return this.http.get( + `/api/lwm2m/deviceProfile/bootstrap/${isBootstrapServer}`, + defaultHttpOptionsFromConfig(config) + ).pipe( + tap(serverConfig => this.lwm2mBootstrapSecurityInfoInMemoryCache.set(isBootstrapServer, serverConfig)) + ); + } } public getLwm2mObjectsPage(pageLink: PageLink, config?: RequestConfig): Observable> { diff --git a/ui-ngx/src/app/core/utils.ts b/ui-ngx/src/app/core/utils.ts index a287802ec2..aa52c55cbe 100644 --- a/ui-ngx/src/app/core/utils.ts +++ b/ui-ngx/src/app/core/utils.ts @@ -445,3 +445,14 @@ export function validateEntityId(entityId: EntityId | null): boolean { export function isMobileApp(): boolean { return isDefined((window as any).flutter_inappwebview); } + +const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +const alphanumericCharactersLength = alphanumericCharacters.length; + +export function randomAlphanumeric(length: number): string { + let result = ''; + for ( let i = 0; i < length; i++ ) { + result += alphanumericCharacters.charAt(Math.floor(Math.random() * alphanumericCharactersLength)); + } + return result; +} diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html index 711b72d615..78f08ce31a 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html @@ -28,60 +28,45 @@ {{ 'device-profile.lwm2m.server-host' | translate }} - + - {{ 'device-profile.lwm2m.server-host' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.server-host-required' | translate }} {{ 'device-profile.lwm2m.server-port' | translate }} - + - {{ 'device-profile.lwm2m.server-port' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.server-port-required' | translate }} + +
{{ 'device-profile.lwm2m.short-id' | translate }} - + - {{ 'device-profile.lwm2m.short-id' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.short-id-required' | translate }} -
-
{{ 'device-profile.lwm2m.client-hold-off-time' | translate }} - - {{ 'device-profile.lwm2m.client-hold-off-time' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.client-hold-off-time-required' | translate }} - {{ 'device-profile.lwm2m.bootstrap-server-account-timeout' | translate }} - {{ 'device-profile.lwm2m.account-after-timeout' | translate }} + - {{ 'device-profile.lwm2m.bootstrap-server-account-timeout' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.account-after-timeout-required' | translate }} - - {{ 'device-profile.lwm2m.bootstrap-server' | translate }} - -
@@ -89,32 +74,22 @@ {{ 'device-profile.lwm2m.server-public-key' | translate }} - {{serverPublicKey.value?.length || 0}}/{{lenMaxServerPublicKey}} + {{serverPublicKey.value?.length || 0}}/{{maxLengthPublicKey}} - {{ 'device-profile.lwm2m.server-public-key' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} + {{ 'device-profile.lwm2m.server-public-key-required' | translate }} - - {{ 'device-profile.lwm2m.server-public-key' | translate }} - {{ 'device-profile.lwm2m.pattern_hex_dec' | translate: { - count: 0} }} + + {{ 'device-profile.lwm2m.server-public-key-pattern' | translate }} - - {{ 'device-profile.lwm2m.server-public-key' | translate }} - {{ 'device-profile.lwm2m.pattern_hex_dec' | translate: { - count: lenMaxServerPublicKey } }} + + {{ 'device-profile.lwm2m.server-public-key-length' | translate: {count: maxLengthPublicKey } }}
diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts index 55f8db8f84..cccaed895f 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts @@ -14,26 +14,24 @@ /// limitations under the License. /// -import { Component, forwardRef, Inject, Input } from '@angular/core'; +import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { - DEFAULT_CLIENT_HOLD_OFF_TIME, - DEFAULT_ID_SERVER, DEFAULT_PORT_BOOTSTRAP_NO_SEC, DEFAULT_PORT_SERVER_NO_SEC, KEY_REGEXP_HEX_DEC, LEN_MAX_PUBLIC_KEY_RPK, LEN_MAX_PUBLIC_KEY_X509, - SECURITY_CONFIG_MODE, - SECURITY_CONFIG_MODE_NAMES, + securityConfigMode, + securityConfigModeNames, ServerSecurityConfig } from './lwm2m-profile-config.models'; -import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { WINDOW } from '@core/services/window.service'; -import { pairwise, startWith } from 'rxjs/operators'; import { DeviceProfileService } from '@core/http/device-profile.service'; +import { of, Subject } from 'rxjs'; +import { map, mergeMap, takeUntil, tap } from 'rxjs/operators'; +import { Observable } from 'rxjs/internal/Observable'; +import { deepClone } from '@core/utils'; -// @dynamic @Component({ selector: 'tb-profile-lwm2m-device-config-server', templateUrl: './lwm2m-device-config-server.component.html', @@ -46,127 +44,78 @@ import { DeviceProfileService } from '@core/http/device-profile.service'; ] }) -export class Lwm2mDeviceConfigServerComponent implements ControlValueAccessor { +export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAccessor, OnDestroy { - private requiredValue: boolean; private disabled = false; + private destroy$ = new Subject(); + + private securityDefaultConfig: ServerSecurityConfig; - valuePrev = null; serverFormGroup: FormGroup; - securityConfigLwM2MType = SECURITY_CONFIG_MODE; - securityConfigLwM2MTypes = Object.keys(SECURITY_CONFIG_MODE); - credentialTypeLwM2MNamesMap = SECURITY_CONFIG_MODE_NAMES; - lenMinServerPublicKey = 0; - lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; + securityConfigLwM2MType = securityConfigMode; + securityConfigLwM2MTypes = Object.keys(securityConfigMode); + credentialTypeLwM2MNamesMap = securityConfigModeNames; + maxLengthPublicKey = LEN_MAX_PUBLIC_KEY_RPK; currentSecurityMode = null; @Input() - bootstrapServerIs: boolean; + isBootstrapServer = false; - get required(): boolean { - return this.requiredValue; - } + private propagateChange = (v: any) => { }; - @Input() - set required(value: boolean) { - this.requiredValue = coerceBooleanProperty(value); + constructor(public fb: FormBuilder, + private deviceProfileService: DeviceProfileService) { } - constructor(public fb: FormBuilder, - private deviceProfileService: DeviceProfileService, - @Inject(WINDOW) private window: Window) { - this.serverFormGroup = this.initServerGroup(); + ngOnInit(): void { + this.serverFormGroup = this.fb.group({ + host: ['', Validators.required], + port: [this.isBootstrapServer ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC, [Validators.required, Validators.min(0)]], + securityMode: [securityConfigMode.NO_SEC], + serverPublicKey: ['', Validators.required], + clientHoldOffTime: ['', [Validators.required, Validators.min(0)]], + serverId: ['', [Validators.required, Validators.min(0)]], + bootstrapServerAccountTimeout: ['', [Validators.required, Validators.min(0)]], + }); this.serverFormGroup.get('securityMode').valueChanges.pipe( - startWith(null), - pairwise() - ).subscribe(([previousValue, currentValue]) => { - if (previousValue === null || previousValue !== currentValue) { - this.getLwm2mBootstrapSecurityInfo(currentValue); - this.updateValidate(currentValue); - this.serverFormGroup.updateValueAndValidity(); - } - + tap(securityMode => this.updateValidate(securityMode)), + mergeMap(securityMode => this.getLwm2mBootstrapSecurityInfo(securityMode)), + takeUntil(this.destroy$) + ).subscribe(serverSecurityConfig => { + this.serverFormGroup.patchValue(serverSecurityConfig, {emitEvent: false}); }); - this.serverFormGroup.valueChanges.subscribe(value => { - if (this.disabled !== undefined && !this.disabled) { - this.propagateChangeState(value); - } + this.serverFormGroup.valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe(value => { + this.propagateChangeState(value); }); } - private updateValueFields = (serverData: ServerSecurityConfig): void => { - serverData.bootstrapServerIs = this.bootstrapServerIs; - this.serverFormGroup.patchValue(serverData, {emitEvent: false}); - this.serverFormGroup.get('bootstrapServerIs').disable(); - const securityMode = this.serverFormGroup.get('securityMode').value as SECURITY_CONFIG_MODE; - this.updateValidate(securityMode); + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); } - private updateValidate = (securityMode: SECURITY_CONFIG_MODE): void => { - switch (securityMode) { - case SECURITY_CONFIG_MODE.NO_SEC: - this.setValidatorsNoSecPsk(); - break; - case SECURITY_CONFIG_MODE.PSK: - this.setValidatorsNoSecPsk(); - break; - case SECURITY_CONFIG_MODE.RPK: - this.lenMinServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; - this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; - this.setValidatorsRpkX509(); - break; - case SECURITY_CONFIG_MODE.X509: - this.lenMinServerPublicKey = 0; - this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_X509; - this.setValidatorsRpkX509(); - break; + writeValue(serverData: ServerSecurityConfig): void { + if (serverData) { + this.serverFormGroup.patchValue(serverData, {emitEvent: false}); + this.updateValidate(serverData.securityMode); } - this.serverFormGroup.updateValueAndValidity(); - } - - private setValidatorsNoSecPsk = (): void => { - this.serverFormGroup.get('serverPublicKey').setValidators([]); - } - - private setValidatorsRpkX509 = (): void => { - this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, - Validators.pattern(KEY_REGEXP_HEX_DEC), - Validators.minLength(this.lenMinServerPublicKey), - Validators.maxLength(this.lenMaxServerPublicKey)]); - } - - writeValue(value: ServerSecurityConfig): void { - if (value) { - this.updateValueFields(value); + if (!this.securityDefaultConfig){ + this.getLwm2mBootstrapSecurityInfo().subscribe(value => { + if (!serverData) { + this.serverFormGroup.patchValue(value); + } + }); } } - private propagateChange = (v: any) => {}; - registerOnChange(fn: any): void { this.propagateChange = fn; } - private propagateChangeState = (value: any): void => { - if (value !== undefined) { - if (this.valuePrev === null) { - this.valuePrev = 'init'; - } else if (this.valuePrev === 'init') { - this.valuePrev = value; - } else if (JSON.stringify(value) !== JSON.stringify(this.valuePrev)) { - this.valuePrev = value; - if (this.serverFormGroup.valid) { - this.propagateChange(value); - } else { - this.propagateChange(null); - } - } - } - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; - this.valuePrev = null; if (isDisabled) { this.serverFormGroup.disable({emitEvent: false}); } else { @@ -177,33 +126,76 @@ export class Lwm2mDeviceConfigServerComponent implements ControlValueAccessor { registerOnTouched(fn: any): void { } - private initServerGroup = (): FormGroup => { - const port = this.bootstrapServerIs ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC; - return this.fb.group({ - host: [this.window.location.hostname, this.required ? Validators.required : ''], - port: [port, this.required ? Validators.required : ''], - bootstrapServerIs: [this.bootstrapServerIs, ''], - securityMode: [this.fb.control(SECURITY_CONFIG_MODE.NO_SEC)], - serverPublicKey: ['', this.required ? Validators.required : ''], - clientHoldOffTime: [DEFAULT_CLIENT_HOLD_OFF_TIME, this.required ? Validators.required : ''], - serverId: [DEFAULT_ID_SERVER, this.required ? Validators.required : ''], - bootstrapServerAccountTimeout: ['', this.required ? Validators.required : ''], - }); + private updateValidate(securityMode: securityConfigMode): void { + switch (securityMode) { + case securityConfigMode.NO_SEC: + case securityConfigMode.PSK: + this.clearValidators(); + break; + case securityConfigMode.RPK: + this.maxLengthPublicKey = LEN_MAX_PUBLIC_KEY_RPK; + this.setValidators(LEN_MAX_PUBLIC_KEY_RPK); + break; + case securityConfigMode.X509: + this.maxLengthPublicKey = LEN_MAX_PUBLIC_KEY_X509; + this.setValidators(0); + break; + } + this.serverFormGroup.get('serverPublicKey').updateValueAndValidity({emitEvent: false}); + } + + private clearValidators(): void { + this.serverFormGroup.get('serverPublicKey').clearValidators(); + } + + private setValidators(minLengthKey: number): void { + this.serverFormGroup.get('serverPublicKey').setValidators([ + Validators.required, + Validators.pattern(KEY_REGEXP_HEX_DEC), + Validators.minLength(minLengthKey), + Validators.maxLength(this.maxLengthPublicKey) + ]); } - private getLwm2mBootstrapSecurityInfo = (mode: string): void => { - this.deviceProfileService.getLwm2mBootstrapSecurityInfo(mode, this.serverFormGroup.get('bootstrapServerIs').value).subscribe( - (serverSecurityConfig) => { - this.serverFormGroup.patchValue({ - host: serverSecurityConfig.host, - port: serverSecurityConfig.port, - serverPublicKey: serverSecurityConfig.serverPublicKey, - clientHoldOffTime: serverSecurityConfig.clientHoldOffTime, - serverId: serverSecurityConfig.serverId, - bootstrapServerAccountTimeout: serverSecurityConfig.bootstrapServerAccountTimeout - }, - {emitEvent: true}); + private propagateChangeState = (value: ServerSecurityConfig): void => { + if (value !== undefined) { + if (this.serverFormGroup.valid) { + this.propagateChange(value); + } else { + this.propagateChange(null); } + } + } + + private getLwm2mBootstrapSecurityInfo(securityMode = securityConfigMode.NO_SEC): Observable { + if (this.securityDefaultConfig) { + return of(this.processingBootstrapSecurityInfo(this.securityDefaultConfig, securityMode)); + } + return this.deviceProfileService.getLwm2mBootstrapSecurityInfo(this.isBootstrapServer).pipe( + map(securityInfo => { + this.securityDefaultConfig = securityInfo; + return this.processingBootstrapSecurityInfo(securityInfo, securityMode); + }) ); } + + private processingBootstrapSecurityInfo(securityConfig: ServerSecurityConfig, securityMode: securityConfigMode): ServerSecurityConfig { + const config = deepClone(securityConfig); + switch (securityMode) { + case securityConfigMode.PSK: + config.port = config.securityPort; + config.host = config.securityHost; + config.serverPublicKey = ''; + break; + case securityConfigMode.RPK: + case securityConfigMode.X509: + config.port = config.securityPort; + config.host = config.securityHost; + break; + case securityConfigMode.NO_SEC: + config.serverPublicKey = ''; + break; + } + return config; + } } diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html index e75aedd47c..30b78393d3 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html @@ -15,231 +15,172 @@ limitations under the License. --> -
+
-
- - -
-
- - -
-
-
-
- - -
-
- - - - -
{{ 'device-profile.lwm2m.servers' | translate | uppercase }}
-
-
- -
-
- - {{ 'device-profile.lwm2m.short-id' | translate }} - - - {{ 'device-profile.lwm2m.short-id' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - - - {{ 'device-profile.lwm2m.lifetime' | translate }} - - - {{ 'device-profile.lwm2m.lifetime' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - - - {{ 'device-profile.lwm2m.default-min-period' | translate }} - - - {{ 'device-profile.lwm2m.default-min-period' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - -
-
- - {{ 'device-profile.lwm2m.binding' | translate }} - - - {{ bindingModeTypeNamesMap.get(bindingModeType[bindingMode]) }} - - - -
-
- - {{ 'device-profile.lwm2m.notif-if-disabled' | translate }} - -
-
-
-
-
- - - - -
{{ 'device-profile.lwm2m.bootstrap-server' | translate | uppercase }}
-
-
- -
- - -
-
-
-
- - - - -
{{ 'device-profile.lwm2m.lwm2m-server' | translate | uppercase }}
-
-
- -
- - -
-
-
-
-
+ + + +
- + -
- -
- - - -
{{ 'device-profile.lwm2m.client-strategy' | translate | uppercase }}
-
-
- -
- - {{ 'device-profile.lwm2m.client-strategy-label' | translate }} - - {{ 'device-profile.lwm2m.client-strategy-connect' | translate: - {count: 1} }} - {{ 'device-profile.lwm2m.client-strategy-connect' | translate: - {count: 2} }} - - -
-
-
-
+
+ - -
{{ 'device-profile.lwm2m.ota-update-strategy' | translate | uppercase }}
-
+ {{ 'device-profile.lwm2m.servers' | translate }}
-
- - {{ 'device-profile.lwm2m.fw-update-strategy-label' | translate }} - - {{ 'device-profile.lwm2m.fw-update-strategy' | translate: - {count: 1} }} - {{ 'device-profile.lwm2m.fw-update-strategy' | translate: - {count: 2} }} - {{ 'device-profile.lwm2m.fw-update-strategy' | translate: - {count: 3} }} - +
+ + {{ 'device-profile.lwm2m.short-id' | translate }} + + + {{ 'device-profile.lwm2m.short-id' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + - - {{ 'device-profile.lwm2m.sw-update-strategy-label' | translate }} - - {{ 'device-profile.lwm2m.sw-update-strategy' | translate: - {count: 1} }} - {{ 'device-profile.lwm2m.sw-update-strategy' | translate: - {count: 2} }} - + + {{ 'device-profile.lwm2m.lifetime' | translate }} + + + {{ 'device-profile.lwm2m.lifetime' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + + + {{ 'device-profile.lwm2m.default-min-period' | translate }} + + + {{ 'device-profile.lwm2m.default-min-period' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} +
+ + {{ 'device-profile.lwm2m.binding' | translate }} + + + {{ bindingModeTypeNamesMap.get(bindingModeType[bindingMode]) }} + + + + + {{ 'device-profile.lwm2m.notif-if-disabled' | translate }} + - + - -
{{ 'device-profile.lwm2m.ota-update-recourse' | translate | uppercase }}
-
+ {{ 'device-profile.lwm2m.bootstrap-server' | translate }}
-
-
- - {{ 'device-profile.lwm2m.fw-update-recourse' | translate }} - - - {{ 'device-profile.lwm2m.fw-update-recourse' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - -
-
- - {{ 'device-profile.lwm2m.sw-update-recourse' | translate }} - - - {{ 'device-profile.lwm2m.sw-update-recourse' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - -
-
+ + +
+
+ + + {{ 'device-profile.lwm2m.lwm2m-server' | translate }} + + + +
+ + +
+
+ device-profile.lwm2m.fw-update + + {{ 'device-profile.lwm2m.fw-update-strategy' | translate }} + + {{ 'device-profile.lwm2m.fw-update-strategy-package' | translate }} + {{ 'device-profile.lwm2m.fw-update-strategy-package-uri' | translate }} + {{ 'device-profile.lwm2m.fw-update-strategy-data' | translate }} + + + + {{ 'device-profile.lwm2m.fw-update-recourse' | translate }} + + + {{ 'device-profile.lwm2m.fw-update-recourse-required' | translate }} + + +
+
+ device-profile.lwm2m.sw-update + + {{ 'device-profile.lwm2m.sw-update-strategy' | translate }} + + {{ 'device-profile.lwm2m.sw-update-strategy-package' | translate }} + {{ 'device-profile.lwm2m.sw-update-strategy-package-uri' | translate }} + + + + {{ 'device-profile.lwm2m.sw-update-recourse' | translate }} + + + {{ 'device-profile.lwm2m.sw-update-recourse-required' | translate }} + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
-
+
Lwm2mDeviceProfileTransportConfigurationComponent), @@ -100,12 +100,38 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro clientStrategy: [1, []], fwUpdateStrategy: [1, []], swUpdateStrategy: [1, []], - fwUpdateRecourse: ['', []], - swUpdateRecourse: ['', []] + fwUpdateRecourse: [{value: '', disabled: true}, []], + swUpdateRecourse: [{value: '', disabled: true}, []] }); this.lwm2mDeviceConfigFormGroup = this.fb.group({ configurationJson: [null, Validators.required] }); + this.lwm2mDeviceProfileFormGroup.get('fwUpdateStrategy').valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe((fwStrategy) => { + if (fwStrategy === 2) { + this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').enable({emitEvent: false}); + this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').patchValue(DEFAULT_FW_UPDATE_RESOURCE, {emitEvent: false}); + this.isFwUpdateStrategy = true; + } else { + this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').disable({emitEvent: false}); + this.isFwUpdateStrategy = false; + } + this.otaUpdateFwStrategyValidate(true); + }); + this.lwm2mDeviceProfileFormGroup.get('swUpdateStrategy').valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe((swStrategy) => { + if (swStrategy === 2) { + this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').enable({emitEvent: false}); + this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').patchValue(DEFAULT_SW_UPDATE_RESOURCE, {emitEvent: false}); + this.isSwUpdateStrategy = true; + } else { + this.isSwUpdateStrategy = false; + this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').disable({emitEvent: false}); + } + this.otaUpdateSwStrategyValidate(true); + }); this.lwm2mDeviceProfileFormGroup.valueChanges.pipe( takeUntil(this.destroy$) ).subscribe((value) => { @@ -176,11 +202,9 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro } private updateWriteValue = (value: ModelValue): void => { - let fwResource = this.configurationValue.clientLwM2mSettings.fwUpdateStrategy === '2' && - isDefinedAndNotNull(this.configurationValue.clientLwM2mSettings.fwUpdateRecourse) ? + const fwResource = isDefinedAndNotNull(this.configurationValue.clientLwM2mSettings.fwUpdateRecourse) ? this.configurationValue.clientLwM2mSettings.fwUpdateRecourse : ''; - let swResource = this.configurationValue.clientLwM2mSettings.swUpdateStrategy === '2' && - isDefinedAndNotNull(this.configurationValue.clientLwM2mSettings.fwUpdateRecourse) ? + const swResource = isDefinedAndNotNull(this.configurationValue.clientLwM2mSettings.fwUpdateRecourse) ? this.configurationValue.clientLwM2mSettings.swUpdateRecourse : ''; this.lwm2mDeviceProfileFormGroup.patchValue({ objectIds: value, @@ -193,16 +217,16 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro bootstrapServer: this.configurationValue.bootstrap.bootstrapServer, lwm2mServer: this.configurationValue.bootstrap.lwm2mServer, clientStrategy: this.configurationValue.clientLwM2mSettings.clientStrategy, - fwUpdateStrategy: this.configurationValue.clientLwM2mSettings.fwUpdateStrategy, - swUpdateStrategy: this.configurationValue.clientLwM2mSettings.swUpdateStrategy, + fwUpdateStrategy: this.configurationValue.clientLwM2mSettings.fwUpdateStrategy || 1, + swUpdateStrategy: this.configurationValue.clientLwM2mSettings.swUpdateStrategy || 1, fwUpdateRecourse: fwResource, swUpdateRecourse: swResource }, {emitEvent: false}); this.configurationValue.clientLwM2mSettings.fwUpdateRecourse = fwResource; this.configurationValue.clientLwM2mSettings.swUpdateRecourse = swResource; - this.isFwUpdateStrategy = this.configurationValue.clientLwM2mSettings.fwUpdateStrategy === '2'; - this.isSwUpdateStrategy = this.configurationValue.clientLwM2mSettings.swUpdateStrategy === '2'; + this.isFwUpdateStrategy = this.configurationValue.clientLwM2mSettings.fwUpdateStrategy === 2; + this.isSwUpdateStrategy = this.configurationValue.clientLwM2mSettings.swUpdateStrategy === 2; this.otaUpdateSwStrategyValidate(); this.otaUpdateFwStrategyValidate(); } @@ -239,8 +263,8 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro this.configurationValue.clientLwM2mSettings.fwUpdateRecourse = config.fwUpdateRecourse; this.configurationValue.clientLwM2mSettings.swUpdateRecourse = config.swUpdateRecourse; this.upDateJsonAllConfig(); - this.updateModel(); } + this.updateModel(); } private getObserveAttrTelemetryObjects = (objectList: ObjectLwM2M[]): object => { @@ -513,53 +537,22 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro }); } - changeFwUpdateStrategy($event: MatSelectChange) { - if ($event.value === '2') { - this.isFwUpdateStrategy = true; - if (isEmpty(this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').value)) { - this.lwm2mDeviceProfileFormGroup.patchValue({ - fwUpdateRecourse: DEFAULT_FW_UPDATE_RESOURCE - }, - {emitEvent: false}); - } - } else { - this.isFwUpdateStrategy = false; - } - this.otaUpdateFwStrategyValidate(); - } - - changeSwUpdateStrategy($event: MatSelectChange) { - if ($event.value === '2') { - this.isSwUpdateStrategy = true; - if (isEmpty(this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').value)) { - this.lwm2mDeviceProfileFormGroup.patchValue({ - swUpdateRecourse: DEFAULT_SW_UPDATE_RESOURCE - }, - {emitEvent: false}); - - } - } else { - this.isSwUpdateStrategy = false; - } - this.otaUpdateSwStrategyValidate(); - } - - private otaUpdateFwStrategyValidate(): void { + private otaUpdateFwStrategyValidate(updated = false): void { if (this.isFwUpdateStrategy) { this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').setValidators([Validators.required]); } else { this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').clearValidators(); } - this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').updateValueAndValidity(); + this.lwm2mDeviceProfileFormGroup.get('fwUpdateRecourse').updateValueAndValidity({emitEvent: updated}); } - private otaUpdateSwStrategyValidate(): void { + private otaUpdateSwStrategyValidate(updated = false): void { if (this.isSwUpdateStrategy) { this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').setValidators([Validators.required]); } else { this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').clearValidators(); } - this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').updateValueAndValidity(); + this.lwm2mDeviceProfileFormGroup.get('swUpdateRecourse').updateValueAndValidity({emitEvent: updated}); } } diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-profile-config.models.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-profile-config.models.ts index ff8225a27d..1f2d125d9f 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-profile-config.models.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-profile-config.models.ts @@ -20,7 +20,6 @@ export const INSTANCE = 'instance'; export const RESOURCES = 'resources'; export const ATTRIBUTE_LWM2M = 'attributeLwm2m'; export const CLIENT_LWM2M = 'clientLwM2M'; -export const CLIENT_LWM2M_SETTINGS = 'clientLwM2mSettings'; export const OBSERVE_ATTR_TELEMETRY = 'observeAttrTelemetry'; export const OBSERVE = 'observe'; export const ATTRIBUTE = 'attribute'; @@ -43,9 +42,9 @@ export const KEY_REGEXP_HEX_DEC = /^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/; export const KEY_REGEXP_NUMBER = /^(\-?|\+?)\d*$/; export const INSTANCES_ID_VALUE_MIN = 0; export const INSTANCES_ID_VALUE_MAX = 65535; -export const DEFAULT_OTA_UPDATE_PROTOCOL = "coap://"; -export const DEFAULT_FW_UPDATE_RESOURCE = DEFAULT_OTA_UPDATE_PROTOCOL + DEFAULT_LOCAL_HOST_NAME + ":"+ DEFAULT_PORT_SERVER_NO_SEC; -export const DEFAULT_SW_UPDATE_RESOURCE = DEFAULT_OTA_UPDATE_PROTOCOL + DEFAULT_LOCAL_HOST_NAME + ":"+ DEFAULT_PORT_SERVER_NO_SEC; +export const DEFAULT_OTA_UPDATE_PROTOCOL = 'coap://'; +export const DEFAULT_FW_UPDATE_RESOURCE = DEFAULT_OTA_UPDATE_PROTOCOL + DEFAULT_LOCAL_HOST_NAME + ':' + DEFAULT_PORT_SERVER_NO_SEC; +export const DEFAULT_SW_UPDATE_RESOURCE = DEFAULT_OTA_UPDATE_PROTOCOL + DEFAULT_LOCAL_HOST_NAME + ':' + DEFAULT_PORT_SERVER_NO_SEC; export enum BINDING_MODE { @@ -113,19 +112,19 @@ export const ATTRIBUTE_LWM2M_MAP = new Map( export const ATTRIBUTE_KEYS = Object.keys(ATTRIBUTE_LWM2M_ENUM) as string[]; -export enum SECURITY_CONFIG_MODE { +export enum securityConfigMode { PSK = 'PSK', RPK = 'RPK', X509 = 'X509', NO_SEC = 'NO_SEC' } -export const SECURITY_CONFIG_MODE_NAMES = new Map( +export const securityConfigModeNames = new Map( [ - [SECURITY_CONFIG_MODE.PSK, 'Pre-Shared Key'], - [SECURITY_CONFIG_MODE.RPK, 'Raw Public Key'], - [SECURITY_CONFIG_MODE.X509, 'X.509 Certificate'], - [SECURITY_CONFIG_MODE.NO_SEC, 'No Security'] + [securityConfigMode.PSK, 'Pre-Shared Key'], + [securityConfigMode.RPK, 'Raw Public Key'], + [securityConfigMode.X509, 'X.509 Certificate'], + [securityConfigMode.NO_SEC, 'No Security'] ] ); @@ -144,9 +143,10 @@ export interface BootstrapServersSecurityConfig { export interface ServerSecurityConfig { host?: string; + securityHost?: string; port?: number; - bootstrapServerIs?: boolean; - securityMode: string; + securityPort?: number; + securityMode: securityConfigMode; clientPublicKeyOrId?: string; clientSecretKey?: string; serverPublicKey?: string; @@ -169,8 +169,8 @@ export interface Lwm2mProfileConfigModels { export interface ClientLwM2mSettings { clientStrategy: string; - fwUpdateStrategy: string; - swUpdateStrategy: string; + fwUpdateStrategy: number; + swUpdateStrategy: number; fwUpdateRecourse: string; swUpdateRecourse: string; } @@ -193,12 +193,11 @@ export function getDefaultBootstrapServersSecurityConfig(): BootstrapServersSecu }; } -export function getDefaultBootstrapServerSecurityConfig(hostname: any): ServerSecurityConfig { +export function getDefaultBootstrapServerSecurityConfig(hostname: string): ServerSecurityConfig { return { host: hostname, port: DEFAULT_PORT_BOOTSTRAP_NO_SEC, - bootstrapServerIs: true, - securityMode: SECURITY_CONFIG_MODE.NO_SEC.toString(), + securityMode: securityConfigMode.NO_SEC, serverPublicKey: '', clientHoldOffTime: DEFAULT_CLIENT_HOLD_OFF_TIME, serverId: DEFAULT_ID_BOOTSTRAP, @@ -208,7 +207,6 @@ export function getDefaultBootstrapServerSecurityConfig(hostname: any): ServerSe export function getDefaultLwM2MServerSecurityConfig(hostname): ServerSecurityConfig { const DefaultLwM2MServerSecurityConfig = getDefaultBootstrapServerSecurityConfig(hostname); - DefaultLwM2MServerSecurityConfig.bootstrapServerIs = false; DefaultLwM2MServerSecurityConfig.port = DEFAULT_PORT_SERVER_NO_SEC; DefaultLwM2MServerSecurityConfig.serverId = DEFAULT_ID_SERVER; return DefaultLwM2MServerSecurityConfig; @@ -242,9 +240,9 @@ export function getDefaultProfileConfig(hostname?: any): Lwm2mProfileConfigModel function getDefaultProfileClientLwM2mSettingsConfig(): ClientLwM2mSettings { return { - clientStrategy: "1", - fwUpdateStrategy: "1", - swUpdateStrategy: "1", + clientStrategy: '1', + fwUpdateStrategy: 1, + swUpdateStrategy: 1, fwUpdateRecourse: DEFAULT_FW_UPDATE_RESOURCE, swUpdateRecourse: DEFAULT_SW_UPDATE_RESOURCE }; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/canvas-digital-gauge.ts b/ui-ngx/src/app/modules/home/components/widget/lib/canvas-digital-gauge.ts index 00687e9b7c..898ceb3b81 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/canvas-digital-gauge.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/canvas-digital-gauge.ts @@ -772,7 +772,7 @@ function drawDigitalLabel(context: DigitalGaugeCanvasRenderingContext2D, options context.textAlign = 'center'; context.font = Drawings.font(options, 'Label', fontSizeFactor); context.lineWidth = 0; - drawText(context, options, 'Label', options.label.toUpperCase(), textX, textY); + drawText(context, options, 'Label', options.label, textX, textY); } function drawDigitalMinMax(context: DigitalGaugeCanvasRenderingContext2D, options: CanvasDigitalGaugeOptions) { diff --git a/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.html b/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.html index 39be34b823..54cf110d5b 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.html @@ -48,20 +48,6 @@ device.label - - device-profile.transport-type - - - {{deviceTransportTypeTranslations.get(type) | translate}} - - - - {{deviceTransportTypeHints.get(deviceWizardFormGroup.get('transportType').value) | translate}} - - - {{ 'device-profile.transport-type-required' | translate }} - -
@@ -74,13 +60,10 @@
- +
- {{ 'device-profile.transport-configuration' | translate }} + {{ 'device-profile.transport-configuration' | translate }} + device-profile.transport-type + + + {{deviceTransportTypeTranslations.get(type) | translate}} + + + + {{deviceTransportTypeHints.get(transportConfigFormGroup.get('transportType').value) | translate}} + + + {{ 'device-profile.transport-type-required' | translate }} + + diff --git a/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.ts b/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.ts index 4e2b5b2ff8..b9c38d24dd 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/wizard/device-wizard-dialog.component.ts @@ -29,7 +29,6 @@ import { DeviceProvisionConfiguration, DeviceProvisionType, DeviceTransportType, - deviceTransportTypeConfigurationInfoMap, deviceTransportTypeHintMap, deviceTransportTypeTranslationMap } from '@shared/models/device.models'; @@ -66,7 +65,6 @@ export class DeviceWizardDialogComponent extends showNext = true; createProfile = false; - createTransportConfiguration = false; entityType = EntityType; @@ -88,7 +86,7 @@ export class DeviceWizardDialogComponent extends customerFormGroup: FormGroup; - labelPosition = 'end'; + labelPosition: MatHorizontalStepper['labelPosition'] = 'end'; serviceType = ServiceType.TB_RULE_ENGINE; @@ -109,7 +107,6 @@ export class DeviceWizardDialogComponent extends label: [''], gateway: [false], overwriteActivityTime: [false], - transportType: [DeviceTransportType.DEFAULT, Validators.required], addProfileType: [0], deviceProfileId: [null, Validators.required], newDeviceProfileTitle: [{value: null, disabled: true}], @@ -130,7 +127,6 @@ export class DeviceWizardDialogComponent extends this.deviceWizardFormGroup.get('defaultQueueName').disable(); this.deviceWizardFormGroup.updateValueAndValidity(); this.createProfile = false; - this.createTransportConfiguration = false; } else { this.deviceWizardFormGroup.get('deviceProfileId').setValidators(null); this.deviceWizardFormGroup.get('deviceProfileId').disable(); @@ -141,18 +137,18 @@ export class DeviceWizardDialogComponent extends this.deviceWizardFormGroup.updateValueAndValidity(); this.createProfile = true; - this.createTransportConfiguration = this.deviceWizardFormGroup.get('transportType').value && - deviceTransportTypeConfigurationInfoMap.get(this.deviceWizardFormGroup.get('transportType').value).hasProfileConfiguration; } } )); this.transportConfigFormGroup = this.fb.group( { + transportType: [DeviceTransportType.DEFAULT, Validators.required], transportConfiguration: [createDeviceProfileTransportConfiguration(DeviceTransportType.DEFAULT), Validators.required] } ); - this.subscriptions.push(this.deviceWizardFormGroup.get('transportType').valueChanges.subscribe((transportType) => { + + this.subscriptions.push(this.transportConfigFormGroup.get('transportType').valueChanges.subscribe((transportType) => { this.deviceProfileTransportTypeChanged(transportType); })); @@ -229,8 +225,6 @@ export class DeviceWizardDialogComponent extends if (index > 0) { if (!this.createProfile) { index += 3; - } else if (!this.createTransportConfiguration) { - index += 1; } } switch (index) { @@ -256,8 +250,6 @@ export class DeviceWizardDialogComponent extends private deviceProfileTransportTypeChanged(deviceTransportType: DeviceTransportType): void { this.transportConfigFormGroup.patchValue( {transportConfiguration: createDeviceProfileTransportConfiguration(deviceTransportType)}); - this.createTransportConfiguration = this.createProfile && deviceTransportType && - deviceTransportTypeConfigurationInfoMap.get(deviceTransportType).hasProfileConfiguration; } add(): void { @@ -281,7 +273,7 @@ export class DeviceWizardDialogComponent extends const deviceProfile: DeviceProfile = { name: this.deviceWizardFormGroup.get('newDeviceProfileTitle').value, type: DeviceProfileType.DEFAULT, - transportType: this.deviceWizardFormGroup.get('transportType').value, + transportType: this.transportConfigFormGroup.get('transportType').value, provisionType: deviceProvisionConfiguration.type, provisionDeviceKey, profileData: { diff --git a/ui-ngx/src/app/modules/home/pages/admin/oauth2-settings.component.html b/ui-ngx/src/app/modules/home/pages/admin/oauth2-settings.component.html index c56dc6a793..a983266434 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/oauth2-settings.component.html +++ b/ui-ngx/src/app/modules/home/pages/admin/oauth2-settings.component.html @@ -90,23 +90,26 @@ admin.oauth2.redirect-uri-template - + + - - + +
@@ -144,18 +147,32 @@
- + admin.oauth2.mobile-package - + + admin.oauth2.mobile-package-hint {{ 'admin.oauth2.mobile-package-unique' | translate }}
- - admin.oauth2.mobile-callback-url-scheme - - +
+ + admin.oauth2.mobile-app-secret + + + + + {{ 'admin.oauth2.invalid-mobile-app-secret' | translate }} + + +
diff --git a/ui-ngx/src/app/shared/components/button/copy-button.component.ts b/ui-ngx/src/app/shared/components/button/copy-button.component.ts index 8d5d72efe3..60f5db12e0 100644 --- a/ui-ngx/src/app/shared/components/button/copy-button.component.ts +++ b/ui-ngx/src/app/shared/components/button/copy-button.component.ts @@ -26,7 +26,6 @@ import { TranslateService } from '@ngx-translate/core'; }) export class CopyButtonComponent { - private copedIcon = ''; private timer; copied = false; @@ -52,6 +51,9 @@ export class CopyButtonComponent { @Input() style: {[key: string]: any} = {}; + @Input() + color: string; + @Output() successCopied = new EventEmitter(); @@ -67,23 +69,13 @@ export class CopyButtonComponent { } this.clipboardService.copy(this.copyText); this.successCopied.emit(this.copyText); - this.copedIcon = 'done'; this.copied = true; this.timer = setTimeout(() => { - this.copedIcon = null; this.copied = false; this.cd.detectChanges(); }, 1500); } - get iconSymbol(): string { - return this.copedIcon || this.icon; - } - - get mdiIconSymbol(): string { - return this.copedIcon ? '' : this.mdiIcon; - } - get matTooltipText(): string { return this.copied ? this.translate.instant('ota-update.copied') : this.tooltipText; } diff --git a/ui-ngx/src/app/shared/models/oauth2.models.ts b/ui-ngx/src/app/shared/models/oauth2.models.ts index d334e89bdd..b434302a9a 100644 --- a/ui-ngx/src/app/shared/models/oauth2.models.ts +++ b/ui-ngx/src/app/shared/models/oauth2.models.ts @@ -34,7 +34,7 @@ export interface OAuth2DomainInfo { export interface OAuth2MobileInfo { pkgName: string; - callbackUrlScheme: string; + appSecret: string; } export enum DomainSchema{ diff --git a/ui-ngx/src/app/shared/models/query/query.models.ts b/ui-ngx/src/app/shared/models/query/query.models.ts index fd7fa68b5e..dbe114e18e 100644 --- a/ui-ngx/src/app/shared/models/query/query.models.ts +++ b/ui-ngx/src/app/shared/models/query/query.models.ts @@ -819,12 +819,14 @@ export function updateDatasourceFromEntityInfo(datasource: Datasource, entity: E datasource.entityId = entity.id; datasource.entityType = entity.entityType; if (datasource.type === DatasourceType.entity || datasource.type === DatasourceType.entityCount) { - datasource.entityName = entity.name; - datasource.entityLabel = entity.label; - datasource.name = entity.name; - datasource.entityDescription = entity.entityDescription; - datasource.entity.label = entity.label; - datasource.entity.name = entity.name; + if (datasource.type === DatasourceType.entity) { + datasource.entityName = entity.name; + datasource.entityLabel = entity.label; + datasource.name = entity.name; + datasource.entityDescription = entity.entityDescription; + datasource.entity.label = entity.label; + datasource.entity.name = entity.name; + } if (createFilter) { datasource.entityFilter = { type: AliasFilterType.singleEntity, diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index abe4cba802..cb09d84731 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -224,8 +224,12 @@ "mobile-apps": "Mobile applications", "no-mobile-apps": "No applications configured", "mobile-package": "Application package", + "mobile-package-placeholder": "Ex.: my.example.app", + "mobile-package-hint": "For Android: your own unique Application ID. For iOS: Product bundle identifier.", "mobile-package-unique": "Application package must be unique.", - "mobile-callback-url-scheme": "Callback URL scheme", + "mobile-app-secret": "Application secret", + "invalid-mobile-app-secret": "Application secret must contain only alphanumeric characters and must be between 16 and 2048 characters long.", + "copy-mobile-app-secret": "Copy application secret", "add-mobile-app": "Add application", "delete-mobile-app": "Delete application info", "providers": "Providers", @@ -1248,7 +1252,7 @@ "pattern_hex_dec": "{ count, plural, 0 {must be hex decimal format} other {must be # characters} }", "servers": "Servers", "short-id": "Short ID", - "short-id-tip": "Short Server ID", + "short-id-required": "Short ID is required.", "lifetime": "Lifetime of the registration for this LwM2M client", "default-min-period": "Minimum Period between two notifications (sec)", "notif-if-disabled": "Notification Storing When Disabled or Offline", @@ -1257,28 +1261,37 @@ "bootstrap-server": "Bootstrap Server", "lwm2m-server": "LwM2M Server", "server-host": "Host", - "server-host-tip": "Server Host", + "server-host-required": "Host is required.", "server-port": "Port", - "server-port-tip": "Server Port", + "server-port-required": "Port is required.", "server-public-key": "Server Public Key", - "server-public-key-tip": "Server Public Key only for X509, RPK", + "server-public-key-required": "Server Public Key is required.", + "server-public-key-pattern": "Server Public Key must be hex decimal format.", + "server-public-key-length": "Server Public Key must be {{ count }} characters.", "client-hold-off-time": "Hold Off Time", - "client-hold-off-time-tip": "Client Hold Off Time for use with a Bootstrap-Server only", - "bootstrap-server-account-timeout": "Account after the timeout", - "bootstrap-server-account-timeout-tip": "Bootstrap-Server Account after the timeout value given by this resource.", - "others-tab": "Other settings...", + "client-hold-off-time-required": "Hold Off Time is required.", + "client-hold-off-time-tooltip": "Client Hold Off Time for use with a Bootstrap-Server only", + "account-after-timeout": "Account after the timeout", + "account-after-timeout-required": "Account after the timeout is required.", + "account-after-timeout-tooltip": "Bootstrap-Server Account after the timeout value given by this resource.", + "others-tab": "Other settings", "client-strategy": "Client strategy when connecting", "client-strategy-label": "Strategy", "client-strategy-connect": "{ count, plural, 1 {1: Only Observe Request to the client after the initial connection} other {2: Read All Resources & Observe Request to the client after registration} }", "client-strategy-tip": "{ count, plural, 1 {Strategy 1: After the initial connection of the LWM2M Client, the server sends Observe resources Request to the client, those resources that are marked as observation in the Device profile and which exist on the LWM2M client.} other {Strategy 2: After the registration, request the client to read all the resource values for all objects that the LWM2M client has,\n then execute: the server sends Observe resources Request to the client, those resources that are marked as observation in the Device profile and which exist on the LWM2M client.} }", - "ota-update-strategy": "Ota update strategy", - "fw-update-strategy-label": "Firmware update strategy", - "fw-update-strategy": "{ count, plural, 1 {Push firmware update as binary file using Object 5 and Resource 0 (Package).} 2 {Auto-generate unique CoAP URL to download the package and push firmware update as Object 5 and Resource 1 (Package URI).} other {Push firmware update as binary file using Object 19 and Resource 0 (Data).} }", - "sw-update-strategy-label": "Software update strategy", - "sw-update-strategy": "{ count, plural, 1 {Push binary file using Object 9 and Resource 2 (Package).} other {Auto-generate unique CoAP URL to download the package and push software update using Object 9 and Resource 3 (Package URI).} }", - "ota-update-recourse": "Ota update Coap recourse", - "fw-update-recourse": "Firmware update Coap recourse", - "sw-update-recourse": "Software update Coap recourse", + "fw-update": "Firmware update", + "fw-update-strategy": "Firmware update strategy", + "fw-update-strategy-data": "Push firmware update as binary file using Object 19 and Resource 0 (Data)", + "fw-update-strategy-package": "Push firmware update as binary file using Object 5 and Resource 0 (Package)", + "fw-update-strategy-package-uri": "Auto-generate unique CoAP URL to download the package and push firmware update as Object 5 and Resource 1 (Package URI)", + "sw-update": "Software update", + "sw-update-strategy": "Software update strategy", + "sw-update-strategy-package": "Push binary file using Object 9 and Resource 2 (Package)", + "sw-update-strategy-package-uri": "Auto-generate unique CoAP URL to download the package and push software update using Object 9 and Resource 3 (Package URI)", + "fw-update-recourse": "Firmware update CoAP recourse", + "fw-update-recourse-required": "Firmware update CoAP recourse is required.", + "sw-update-recourse": "Software update CoAP recourse", + "sw-update-recourse-required": "Software update CoAP recourse is required.", "config-json-tab": "Json Config Profile Device" } }, diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json index 99b0864d36..6a60db96fc 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json @@ -76,6 +76,7 @@ "general": "基本设置", "general-policy": "基本策略", "general-settings": "基本设置", + "home-settings": "首页设置", "mail-from": "邮件来自", "mail-from-required": "邮件发件人必填。", "max-failed-login-attempts": "登录失败之前的最大登录尝试次数", @@ -115,7 +116,7 @@ "customer-name-pattern": "客户名称模式", "default-dashboard-name": "默认仪表板名称", "delete-domain": "删除域", - "delete-domain-text": "注意,确认后域和所有 provider data 将不可用。", + "delete-domain-text": "请注意:确认后域和所有 provider data 将不可用。", "delete-domain-title": "确实要删除域 '{{domainName}}' 的设置吗?", "delete-provider": "删除 Provider", "delete-registration-text": "请注意:确认后 provider data 将不可用。", @@ -413,7 +414,7 @@ "assignedToCustomer": "分配客户", "copyId": "复制资产ID", "delete": "删除资产", - "delete-asset-text": "小心!确认后资产及其所有相关数据将不可恢复。", + "delete-asset-text": "请注意:确认后资产及其所有相关数据将不可恢复。", "delete-asset-title": "确定要删除资产 '{{assetName}}'?", "delete-assets": "删除资产", "delete-assets-action-title": "删除 { count, plural, 1 {# 个资产} other {# 个资产} }", @@ -589,10 +590,10 @@ "default-customer": "默认客户", "default-customer-required": "为了调试租户级别上的仪表板,需要默认客户。", "delete": "删除此客户", - "delete-customer-text": "小心!确认后,客户及其所有相关数据将不可恢复。", + "delete-customer-text": "请注意:确认后,客户及其所有相关数据将不可恢复。", "delete-customer-title": "您确定要删除客户'{{customerTitle}}'吗?", "delete-customers-action-title": "删除 { count, plural, 1 {# 个客户} other {# 个客户} }", - "delete-customers-text": "小心!确认后,所有选定的客户将被删除,所有相关数据将不可恢复。", + "delete-customers-text": "请注意:确认后,所有选定的客户将被删除,所有相关数据将不可恢复。", "delete-customers-title": "您确定要删除 { count, plural, 1 {# 个客户} other {# 个客户} }吗?", "description": "说明", "details": "详情", @@ -647,6 +648,7 @@ "background-color": "背景颜色", "background-image": "背景图片", "background-size-mode": "背景大小模式", + "cannot-upload-file": "无法上传文件", "close-toolbar": "关闭工具栏", "columns-count": "列数", "columns-count-required": "需要列数。", @@ -659,14 +661,15 @@ "dashboard-details": "仪表板详情", "dashboard-file": "仪表板文件", "dashboard-import-missing-aliases-title": "配置导入仪表板使用的别名", + "dashboard-logo-image": "仪表板 Logo 图片", "dashboard-required": "仪表板必填。", "dashboards": "仪表板库", "delete": "删除仪表板", - "delete-dashboard-text": "小心!确认后仪表板及其所有相关数据将不可恢复。", + "delete-dashboard-text": "请注意:确认后仪表板及其所有相关数据将不可恢复。", "delete-dashboard-title": "您确定要删除仪表板 '{{dashboardTitle}}'吗?", "delete-dashboards": "删除仪表板", "delete-dashboards-action-title": "删除 { count, plural, 1 {# 个仪表板} other {# 个仪表板} }", - "delete-dashboards-text": "小心!确认后所有选定的仪表板将被删除,所有相关数据将不可恢复。", + "delete-dashboards-text": "请注意:确认后所有选定的仪表板将被删除,所有相关数据将不可恢复。", "delete-dashboards-title": "确定要删除 { count, plural, 1 {# 个仪表板} other {# 个仪表板} }吗?", "delete-state": "删除仪表板状态", "delete-state-text": "确定要删除仪表板状态 '{{stateName}}' 吗?", @@ -674,6 +677,7 @@ "description": "说明", "details": "详情", "display-dashboard-export": "显示导出", + "display-dashboard-logo": "在仪表板全屏模式下显示 Logo", "display-dashboard-timewindow": "显示时间窗口", "display-dashboards-selection": "显示仪表板选项", "display-entities-selection": "显示实体选项", @@ -684,6 +688,8 @@ "export": "导出仪表板", "export-failed-error": "无法导出仪表板: {{error}}", "hide-details": "隐藏详情", + "home-dashboard": "首页仪表板", + "home-dashboard-hide-toolbar": "隐藏首页仪表板工具栏", "horizontal-margin": "水平边距", "horizontal-margin-required": "需要水平边距值。", "import": "导入仪表板", @@ -736,6 +742,7 @@ "select-state": "选择目标状态", "select-widget-subtitle": "可用的部件类型列表", "select-widget-title": "选择部件", + "select-widget-value": "{{title}}: 选择部件", "selected-dashboards": "已选择 { count, plural, 1 {# 个仪表盘} other {# 个仪表盘} }", "selected-states": "已选择 { count, plural, 1 {# 个仪表板状态} other {# 个仪表板状态} }", "set-background": "设置背景", @@ -803,6 +810,7 @@ }, "datasource": { "add-datasource-prompt": "请添加数据源", + "label": "标签", "name": "名称", "type": "数据源类型" }, @@ -843,6 +851,11 @@ "attributes-topic-filter": "Attributes topic filter", "attributes-topic-filter-required": "Attributes topic 筛选器必填。", "clear-alarm-rule": "清除报警规则", + "coap-device-payload-type": "CoAP 设备消息 Payload", + "coap-device-type": "CoAP 设备类型", + "coap-device-type-default": "默认", + "coap-device-type-efento": "Efento NB-IoT", + "coap-device-type-required": "CoAP 设备类型必填。", "condition": "条件", "condition-duration": "条件持续时间", "condition-duration-time-unit": "时间单位", @@ -867,17 +880,19 @@ "copyId": "复制设备配置 ID", "create-alarm-pattern": "创建 {{alarmType}} 报警", "create-alarm-rules": "创建报警规则", + "create-device-profile": "创建设备配置", "create-new-device-profile": "创建一个新的!", "default": "默认", "default-rule-chain": "默认规则链", "delete": "删除设备配置", - "delete-device-profile-text": "注意,确认后设备配置和所有相关数据将不可恢复。", + "delete-device-profile-text": "请注意:确认后设备配置和所有相关数据将不可恢复。", "delete-device-profile-title": "是否确实要删除设备配置 '{{deviceProfileName}}'?", "delete-device-profiles-text": "请注意:确认后,所有选定的设备配置将被删除,所有相关数据将不可恢复。", "delete-device-profiles-title": "确定要删除 { count, plural, 1 {# 个设备配置} other {# 个设备配置} }?", "description": "说明", "device-profile": "设备配置", "device-profile-details": "设备配置详情", + "device-profile-file": "设备配置文件", "device-profile-required": "设备配置必填", "device-profiles": "设备配置", "device-provisioning": "设备预配置", @@ -886,7 +901,11 @@ "edit-alarm-rule-condition": "编辑报警规则条件", "edit-schedule": "编辑报警日程表", "enter-alarm-rule-condition-prompt": "请添加报警规则条件", + "export": "导出设备配置", + "export-failed-error": "无法导出设备配置文件: {{error}}", "idCopiedMessage": "设备配置 ID 已复制到剪贴板", + "import": "导入设备配置", + "invalid-device-profile-file-error": "无法导入设备配置文件:无效的设备配置文件数据结构。", "mqtt-device-payload-type": "MQTT 设备 Payload", "mqtt-device-payload-type-json": "JSON", "mqtt-device-payload-type-proto": "Protobuf", @@ -920,6 +939,11 @@ "provision-strategy-created-new": "允许创建新设备", "provision-strategy-disabled": "禁用", "provision-strategy-required": "预配置策略必填。", + "rpc-request-proto-schema": "RPC 请求 proto schema", + "rpc-request-proto-schema-hint": "RPC 请求消息应始终包含字段:string method = 1; int32 requestId = 2; 和params = 3的任何数据类型。", + "rpc-request-proto-schema-required": "RPC 请求 proto schema 必填。", + "rpc-response-proto-schema": "RPC 响应 proto schema", + "rpc-response-proto-schema-required": "RPC 响应 proto schema 必填。", "rpc-response-topic-filter": "RPC响应 Topic 筛选器", "rpc-response-topic-filter-required": "RPC响应 Topic 筛选器必填。", "schedule": "启用规则:", @@ -957,6 +981,7 @@ "telemetry-topic-filter-required": "遥测数据 topic 筛选器必填。", "transport-configuration": "传输配置", "transport-type": "传输方式", + "transport-type-coap-hint": "启用高级 CoAP 传输设置", "transport-type-default": "默认", "transport-type-default-hint": "支持基本MQTT、HTTP和CoAP传输", "transport-type-lwm2m": "LWM2M", @@ -964,6 +989,7 @@ "transport-type-mqtt": "MQTT", "transport-type-mqtt-hint": "启用高级MQTT传输设置", "transport-type-required": "传输方式必填。", + "transport-type-snmp-hint": "指定 SNMP 传输配置", "type": "配置类型", "type-default": "默认", "type-required": "配置类型必填。" @@ -1000,11 +1026,11 @@ "credentials": "凭据", "credentials-type": "凭据类型", "delete": "删除设备", - "delete-device-text": "小心!确认后设备及其所有相关数据将不可恢复。", + "delete-device-text": "请注意:确认后设备及其所有相关数据将不可恢复。", "delete-device-title": "您确定要删除设备的{{deviceName}}吗?", "delete-devices": "删除设备", "delete-devices-action-title": "删除 {count,plural,1 {# 个设备} other {# 个设备} }", - "delete-devices-text": "小心!确认后所有选定的设备将被删除,所有相关数据将不可恢复。", + "delete-devices-text": "请注意:确认后所有选定的设备将被删除,所有相关数据将不可恢复。", "delete-devices-title": "确定要删除{count,plural,1 {# 个设备} other {# 个设备} } 吗?", "description": "说明", "details": "详情", @@ -1051,6 +1077,7 @@ "no-devices-text": "找不到设备", "no-key-matching": "'{{key}}' 没有找到。", "no-keys-found": "找不到密钥。", + "overwrite-activity-time": "覆盖已连接设备的活动时间", "password": "密码", "public": "公开", "remove-alias": "删除设备别名", @@ -1139,7 +1166,7 @@ "created-time": "创建时间", "date-limits": "日期限制", "delete": "删除实体视图", - "delete-entity-view-text": "小心!确认后实体视图及其所有相关数据将不可恢复。", + "delete-entity-view-text": "请注意:确认后实体视图及其所有相关数据将不可恢复。", "delete-entity-view-title": "确定要删除实体视图 '{{entityViewName}}'?", "delete-entity-views": "删除实体视图", "delete-entity-views-action-title": "删除 { count, plural, 1 {# 个实体视图} other {# 个实体视图} }", @@ -1235,6 +1262,7 @@ "duplicate-alias-error": "别名 '{{alias}}' 重复。
同一仪表板别名必须唯一。", "enter-entity-type": "输入实体类型", "entities": "实体", + "entities-count": "实体数量", "entity": "实体", "entity-alias": "实体别名", "entity-label": "实体标签", @@ -1334,12 +1362,15 @@ "body": "整体", "data": "数据", "data-type": "数据类型", + "entity-id": "实体ID", "error": "错误", "errors-occurred": "错误发生", "event": "事件", "event-time": "事件时间", "event-type": "事件类型", + "events-filter": "事件筛选器", "failed": "失败", + "has-error": "有错误", "message-id": "消息ID", "message-type": "消息类型", "messages-processed": "消息处理", @@ -1552,6 +1583,7 @@ "key-name-required": "键名必填。", "key-type": { "attribute": "属性", + "constant": "常量", "entity-field": "实体", "key-type": "键类型", "timeseries": "Timeseries" @@ -1603,6 +1635,51 @@ "value-type": "值类型" } }, + "firmware": { + "add": "添加固件", + "checksum": "校验和", + "checksum-algorithm": "校验和算法", + "checksum-copied-message": "固件校验和已复制到剪贴板", + "checksum-required": "校验和为必填项。", + "content-type": "Content type", + "copy-checksum": "复制校验和", + "copyId": "复制固件ID", + "delete": "删除固件", + "delete-firmware-text": "请注意:确认后固件将无法恢复。", + "delete-firmware-title": "确定要删除固件'{{firmwareTitle}}'?", + "delete-firmwares-action-title": "Delete { count, plural, 1 {# 个固件} other {# 个固件} }", + "delete-firmwares-text": "请注意:确认后所有选定的资源都将被删除。", + "delete-firmwares-title": "确定要删除固件 { count, plural, 1 {# 个固件} other {# 个固件} }?", + "description": "描述", + "download": "下载固件", + "drop-file": "拖拽固件文件或单击以选择要上传的文件。", + "empty": "固件为空", + "file-name": "文件名", + "file-size": "文件大小", + "file-size-bytes": "文件大小(字节)", + "firmware": "固件", + "firmware-details": "固件详情", + "firmware-required": "固件为必选项。", + "idCopiedMessage": "固件ID已复制到剪贴板", + "no-firmware-matching": "找不到与 '{{entity}}' 匹配的固件。", + "no-firmware-text": "没有找到固件", + "no-software-matching": "找不到与 '{{entity}}' 匹配的软件。", + "no-software-text": "没有找到软件", + "search": "查找固件", + "selected-firmware": "已选择{ count, plural, 1 {# 个固件} other {# 个固件}", + "software": "软件", + "software-required": "软件为必选项。", + "title": "标题", + "title-required": "标题为必填项。", + "type": "固件类型", + "types": { + "firmware": "固件", + "software": "软件" + }, + "version": "版本号", + "version-required": "版本号为必填项。", + "warning-after-save-no-edit": "保存固件后,将无法更改标题和版本号。" +}, "fullscreen": { "exit": "退出全屏", "expand": "展开到全屏", @@ -1907,6 +1984,30 @@ "to-relations": "向内的关联", "type": "类型" }, + "resource": { + "add": "添加资源", + "delete": "删除资源", + "delete-resource-text": "请注意:确认后资源将不可恢复。", + "delete-resource-title": "确定要删除资源 '{{resourceTitle}}' 吗?", + "delete-resources-action-title": "删除 { count, plural, 1 {# 个资源} other {# 个资源} }", + "delete-resources-text": "请注意:确认后所有选定的资源都将被删除。", + "delete-resources-title": "确定要删除 { count, plural, 1 {# 个资源} other {# 个资源} }?", + "drop-file": "拖拽资源文件或单击以选择要上传的文件。", + "empty": "资源为空", + "export": "导出资源", + "no-resource-matching": "找不到与 '{{widgetsBundle}}' 匹配的资源。", + "no-resource-text": "找不到资源", + "open-widgets-bundle": "打开部件库", + "resource": "资源", + "resource-library-details": "资源库详情", + "resource-type": "资源类型", + "resources-library": "资源库", + "search": "查找资源", + "selected-resources": "已选择{ count, plural, 1 {# 个资源} other {# 个资源} }", + "system": "系统", + "title": "标题", + "title-required": "标题是必填项。" +}, "rulechain": { "add": "添加规则链", "add-rulechain-text": "添加新的规则链", @@ -2098,10 +2199,10 @@ "admins": "管理员", "copyId": "复制租户ID", "delete": "删除租户", - "delete-tenant-text": "小心!确认后,租户和所有相关数据将不可恢复。", + "delete-tenant-text": "请注意:确认后,租户和所有相关数据将不可恢复。", "delete-tenant-title": "您确定要删除租户'{{tenantTitle}}'吗?", "delete-tenants-action-title": "删除 { count, plural, 1 {# 个租户} other {# 个租户} }", - "delete-tenants-text": "小心!确认后,所有选定的租户将被删除,所有相关数据将不可恢复。", + "delete-tenants-text": "请注意:确认后,所有选定的租户将被删除,所有相关数据将不可恢复。", "delete-tenants-title": "确定要删除 {count,plural,1 {# 个租户} other {# 个租户} } 吗?", "description": "说明", "details": "详情", @@ -2178,10 +2279,10 @@ "customer-users": "客户用户", "default-dashboard": "默认面板", "delete": "删除用户", - "delete-user-text": "小心!确认后,用户和所有相关数据将不可恢复。", + "delete-user-text": "请注意:确认后,用户和所有相关数据将不可恢复。", "delete-user-title": "您确定要删除用户 '{{userEmail}}' 吗?", "delete-users-action-title": "删除 { count, plural, 1 {# 个用户} other {# 个用户} }", - "delete-users-text": "小心!确认后,所有选定的用户将被删除,所有相关数据将不可恢复。", + "delete-users-text": "请注意:确认后,所有选定的用户将被删除,所有相关数据将不可恢复。", "delete-users-title": "确定要删除 { count, plural, 1 {# 个用户} other {# 个用户} } 吗?", "description": "说明", "details": "详情", @@ -2343,11 +2444,11 @@ "run": "运行部件", "save": "保存部件", "save-widget-type-as": "部件类型另存为", - "save-widget-type-as-text": "请输入新的部件标题或选择目标部件组", + "save-widget-type-as-text": "请输入新的部件标题或选择目标部件包", "saveAs": "部件另存为", "search-data": "查找数据", "select-widget-type": "选择窗口部件类型", - "select-widgets-bundle": "选择部件组", + "select-widgets-bundle": "选择部件包", "settings-schema": "设置模式", "static": "静态部件", "tidy": "Tidy", @@ -2358,7 +2459,7 @@ "type": "部件类型", "unable-to-save-widget-error": "无法保存部件!控件有错误!", "undo": "撤消部件更改", - "widget-bundle": "部件组", + "widget-bundle": "部件包", "widget-library": "部件库", "widget-saved": "部件已保存", "widget-template-load-failed-error": "无法加载部件模板!", @@ -2367,33 +2468,36 @@ "widget-type-not-found": "加载部件配置出错。
可能关联的部件已经删除了。" }, "widgets-bundle": { - "add": "添加部件组", - "add-widgets-bundle-text": "添加新的部件组", - "create-new-widgets-bundle": "创建新的部件组", + "add": "添加部件包", + "add-widgets-bundle-text": "添加新的部件包", + "create-new-widgets-bundle": "创建新的部件包", "current": "当前组", - "delete": "删除部件组", - "delete-widgets-bundle-text": "小心!确认后,部件组和所有相关数据将不可恢复。", - "delete-widgets-bundle-title": "您确定要删除部件组 '{{widgetsBundleTitle}}'吗?", - "delete-widgets-bundles-action-title": "删除 { count, plural, 1 {# 个部件组} other {# 个部件组} }", - "delete-widgets-bundles-text": "小心!确认后,所有选定的部件组将被删除,所有相关数据将不可恢复。", - "delete-widgets-bundles-title": "确定要删除 { count, plural, 1 {# 个部件组} other {# 个部件组} } 吗?", + "delete": "删除部件包", + "delete-widgets-bundle-text": "请注意:确认后,部件包和所有相关数据将不可恢复。", + "delete-widgets-bundle-title": "您确定要删除部件包 '{{widgetsBundleTitle}}'吗?", + "delete-widgets-bundles-action-title": "删除 { count, plural, 1 {# 个部件包} other {# 个部件包} }", + "delete-widgets-bundles-text": "请注意:确认后,所有选定的部件包将被删除,所有相关数据将不可恢复。", + "delete-widgets-bundles-title": "确定要删除 { count, plural, 1 {# 个部件包} other {# 个部件包} } 吗?", + "description": "描述", "details": "详情", - "empty": "部件组是空的", - "export": "导出部件组", - "export-failed-error": "无法导出部件组: {{error}}", - "import": "导入部件组", - "invalid-widgets-bundle-file-error": "无法导入部件组:无效的部件组数据结构。", - "no-widgets-bundles-matching": "没有找到与 '{{widgetsBundle}}' 匹配的部件组。", - "no-widgets-bundles-text": "找不到部件组", - "open-widgets-bundle": "打开部件组", - "search": "查找部件组", - "selected-widgets-bundles": "已选择 { count, plural, 1 {# 个部件组} other {# 个部件组} }", + "empty": "部件包是空的", + "export": "导出部件包", + "export-failed-error": "无法导出部件包: {{error}}", + "image-preview": "图片预览", + "import": "导入部件包", + "invalid-widgets-bundle-file-error": "无法导入部件包:无效的部件包数据结构。", + "loading-widgets-bundles": "加载部件包...", + "no-widgets-bundles-matching": "没有找到与 '{{widgetsBundle}}' 匹配的部件包。", + "no-widgets-bundles-text": "找不到部件包", + "open-widgets-bundle": "打开部件包", + "search": "查找部件包", + "selected-widgets-bundles": "已选择 { count, plural, 1 {# 个部件包} other {# 个部件包} }", "system": "系统", "title": "标题", "title-required": "标题必填。", - "widgets-bundle-details": "部件组详细信息", - "widgets-bundle-file": "部件组文件", - "widgets-bundle-required": "部件组必填。", + "widgets-bundle-details": "部件包详细信息", + "widgets-bundle-file": "部件包文件", + "widgets-bundle-required": "部件包必填。", "widgets-bundles": "部件包" }, "widgets": {