527 changed files with 21706 additions and 6694 deletions
File diff suppressed because one or more lines are too long
@ -0,0 +1,37 @@ |
|||
-- |
|||
-- Copyright © 2016-2022 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. |
|||
-- |
|||
|
|||
CREATE TABLE IF NOT EXISTS queue ( |
|||
id uuid NOT NULL CONSTRAINT queue_pkey PRIMARY KEY, |
|||
created_time bigint NOT NULL, |
|||
tenant_id uuid, |
|||
name varchar(255), |
|||
topic varchar(255), |
|||
poll_interval int, |
|||
partitions int, |
|||
consumer_per_partition boolean, |
|||
pack_processing_timeout bigint, |
|||
submit_strategy varchar(255), |
|||
processing_strategy varchar(255), |
|||
additional_info varchar |
|||
); |
|||
|
|||
CREATE TABLE IF NOT EXISTS user_auth_settings ( |
|||
id uuid NOT NULL CONSTRAINT user_auth_settings_pkey PRIMARY KEY, |
|||
created_time bigint NOT NULL, |
|||
user_id uuid UNIQUE NOT NULL CONSTRAINT fk_user_auth_settings_user_id REFERENCES tb_user(id), |
|||
two_fa_settings varchar |
|||
); |
|||
@ -0,0 +1,49 @@ |
|||
-- |
|||
-- Copyright © 2016-2022 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. |
|||
-- |
|||
|
|||
ALTER TABLE device_profile |
|||
ADD COLUMN IF NOT EXISTS default_queue_id uuid; |
|||
|
|||
DO |
|||
$$ |
|||
BEGIN |
|||
IF EXISTS |
|||
(SELECT column_name |
|||
FROM information_schema.columns |
|||
WHERE table_name = 'device_profile' |
|||
AND column_name = 'default_queue_name' |
|||
) |
|||
THEN |
|||
UPDATE device_profile |
|||
SET default_queue_id = q.id |
|||
FROM queue as q |
|||
WHERE default_queue_name = q.name; |
|||
END IF; |
|||
END |
|||
$$; |
|||
|
|||
DO |
|||
$$ |
|||
BEGIN |
|||
IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conname = 'fk_default_queue_device_profile') THEN |
|||
ALTER TABLE device_profile |
|||
ADD CONSTRAINT fk_default_queue_device_profile FOREIGN KEY (default_queue_id) REFERENCES queue (id); |
|||
END IF; |
|||
END; |
|||
$$; |
|||
|
|||
ALTER TABLE device_profile |
|||
DROP COLUMN IF EXISTS default_queue_name; |
|||
@ -0,0 +1,272 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.controller; |
|||
|
|||
import io.swagger.annotations.ApiOperation; |
|||
import io.swagger.annotations.ApiParam; |
|||
import lombok.Data; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.security.access.prepost.PreAuthorize; |
|||
import org.springframework.web.bind.annotation.DeleteMapping; |
|||
import org.springframework.web.bind.annotation.GetMapping; |
|||
import org.springframework.web.bind.annotation.PostMapping; |
|||
import org.springframework.web.bind.annotation.PutMapping; |
|||
import org.springframework.web.bind.annotation.RequestBody; |
|||
import org.springframework.web.bind.annotation.RequestMapping; |
|||
import org.springframework.web.bind.annotation.RequestParam; |
|||
import org.springframework.web.bind.annotation.RestController; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.AccountTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; |
|||
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import javax.validation.Valid; |
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
import java.util.stream.Collectors; |
|||
|
|||
import static org.thingsboard.server.controller.ControllerConstants.NEW_LINE; |
|||
|
|||
@RestController |
|||
@RequestMapping("/api/2fa") |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class TwoFaConfigController extends BaseController { |
|||
|
|||
private final TwoFaConfigManager twoFaConfigManager; |
|||
private final TwoFactorAuthService twoFactorAuthService; |
|||
|
|||
|
|||
@ApiOperation(value = "Get account 2FA settings (getAccountTwoFaSettings)", |
|||
notes = "Get user's account 2FA configuration. Configuration contains configs for different 2FA providers." + NEW_LINE + |
|||
"Example:\n" + |
|||
"```\n{\n \"configs\": {\n" + |
|||
" \"EMAIL\": {\n \"providerType\": \"EMAIL\",\n \"useByDefault\": true,\n \"email\": \"tenant@thingsboard.org\"\n },\n" + |
|||
" \"TOTP\": {\n \"providerType\": \"TOTP\",\n \"useByDefault\": false,\n \"authUrl\": \"otpauth://totp/TB%202FA:tenant@thingsboard.org?issuer=TB+2FA&secret=P6Z2TLYTASOGP6LCJZAD24ETT5DACNNX\"\n },\n" + |
|||
" \"SMS\": {\n \"providerType\": \"SMS\",\n \"useByDefault\": false,\n \"phoneNumber\": \"+380501253652\"\n }\n" + |
|||
" }\n}\n```" + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@GetMapping("/account/settings") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public AccountTwoFaSettings getAccountTwoFaSettings() throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
return twoFaConfigManager.getAccountTwoFaSettings(user.getTenantId(), user.getId()).orElse(null); |
|||
} |
|||
|
|||
|
|||
@ApiOperation(value = "Generate 2FA account config (generateTwoFaAccountConfig)", |
|||
notes = "Generate new 2FA account config template for specified provider type. " + NEW_LINE + |
|||
"For TOTP, this will return a corresponding account config template " + |
|||
"with a generated OTP auth URL (with new random secret key for each API call) that can be then " + |
|||
"converted to a QR code to scan with an authenticator app. Example:\n" + |
|||
"```\n{\n" + |
|||
" \"providerType\": \"TOTP\",\n" + |
|||
" \"useByDefault\": false,\n" + |
|||
" \"authUrl\": \"otpauth://totp/TB%202FA:tenant@thingsboard.org?issuer=TB+2FA&secret=PNJDNWJVAK4ZTUYT7RFGPQLXA7XGU7PX\"\n" + |
|||
"}\n```" + NEW_LINE + |
|||
"For EMAIL, the generated config will contain email from user's account:\n" + |
|||
"```\n{\n" + |
|||
" \"providerType\": \"EMAIL\",\n" + |
|||
" \"useByDefault\": false,\n" + |
|||
" \"email\": \"tenant@thingsboard.org\"\n" + |
|||
"}\n```" + NEW_LINE + |
|||
"For SMS 2FA this method will just return a config with empty/default values as there is nothing to generate/preset:\n" + |
|||
"```\n{\n" + |
|||
" \"providerType\": \"SMS\",\n" + |
|||
" \"useByDefault\": false,\n" + |
|||
" \"phoneNumber\": null\n" + |
|||
"}\n```" + NEW_LINE + |
|||
"Will throw an error (Bad Request) if the provider is not configured for usage. " + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@PostMapping("/account/config/generate") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public TwoFaAccountConfig generateTwoFaAccountConfig(@ApiParam(value = "2FA provider type to generate new account config for", defaultValue = "TOTP", required = true) |
|||
@RequestParam TwoFaProviderType providerType) throws Exception { |
|||
SecurityUser user = getCurrentUser(); |
|||
return twoFactorAuthService.generateNewAccountConfig(user, providerType); |
|||
} |
|||
|
|||
@ApiOperation(value = "Submit 2FA account config (submitTwoFaAccountConfig)", |
|||
notes = "Submit 2FA account config to prepare for a future verification. " + |
|||
"Basically, this method will send a verification code for a given account config, if this has " + |
|||
"sense for a chosen 2FA provider. This code is needed to then verify and save the account config." + NEW_LINE + |
|||
"Example of EMAIL 2FA account config:\n" + |
|||
"```\n{\n" + |
|||
" \"providerType\": \"EMAIL\",\n" + |
|||
" \"useByDefault\": true,\n" + |
|||
" \"email\": \"separate-email-for-2fa@thingsboard.org\"\n" + |
|||
"}\n```" + NEW_LINE + |
|||
"Example of SMS 2FA account config:\n" + |
|||
"```\n{\n" + |
|||
" \"providerType\": \"SMS\",\n" + |
|||
" \"useByDefault\": false,\n" + |
|||
" \"phoneNumber\": \"+38012312321\"\n" + |
|||
"}\n```" + NEW_LINE + |
|||
"For TOTP this method does nothing." + NEW_LINE + |
|||
"Will throw an error (Bad Request) if submitted account config is not valid, " + |
|||
"or if the provider is not configured for usage. " + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@PostMapping("/account/config/submit") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public void submitTwoFaAccountConfig(@Valid @RequestBody TwoFaAccountConfig accountConfig) throws Exception { |
|||
SecurityUser user = getCurrentUser(); |
|||
twoFactorAuthService.prepareVerificationCode(user, accountConfig, false); |
|||
} |
|||
|
|||
@ApiOperation(value = "Verify and save 2FA account config (verifyAndSaveTwoFaAccountConfig)", |
|||
notes = "Checks the verification code for submitted config, and if it is correct, saves the provided account config. " + NEW_LINE + |
|||
"Returns whole account's 2FA settings object.\n" + |
|||
"Will throw an error (Bad Request) if the provider is not configured for usage. " + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@PostMapping("/account/config") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public AccountTwoFaSettings verifyAndSaveTwoFaAccountConfig(@Valid @RequestBody TwoFaAccountConfig accountConfig, |
|||
@RequestParam(required = false) String verificationCode) throws Exception { |
|||
SecurityUser user = getCurrentUser(); |
|||
if (twoFaConfigManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig.getProviderType()).isPresent()) { |
|||
throw new IllegalArgumentException("2FA provider is already configured"); |
|||
} |
|||
|
|||
boolean verificationSuccess; |
|||
if (accountConfig.getProviderType() != TwoFaProviderType.BACKUP_CODE) { |
|||
verificationSuccess = twoFactorAuthService.checkVerificationCode(user, verificationCode, accountConfig, false); |
|||
} else { |
|||
verificationSuccess = true; |
|||
} |
|||
if (verificationSuccess) { |
|||
return twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig); |
|||
} else { |
|||
throw new IllegalArgumentException("Verification code is incorrect"); |
|||
} |
|||
} |
|||
|
|||
@ApiOperation(value = "Update 2FA account config (updateTwoFaAccountConfig)", notes = |
|||
"Update config for a given provider type. \n" + |
|||
"Update request example:\n" + |
|||
"```\n{\n \"useByDefault\": true\n}\n```\n" + |
|||
"Returns whole account's 2FA settings object.\n" + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@PutMapping("/account/config") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public AccountTwoFaSettings updateTwoFaAccountConfig(@RequestParam TwoFaProviderType providerType, |
|||
@RequestBody TwoFaAccountConfigUpdateRequest updateRequest) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
|
|||
TwoFaAccountConfig accountConfig = twoFaConfigManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType) |
|||
.orElseThrow(() -> new IllegalArgumentException("Config for " + providerType + " 2FA provider not found")); |
|||
accountConfig.setUseByDefault(updateRequest.isUseByDefault()); |
|||
return twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig); |
|||
} |
|||
|
|||
@ApiOperation(value = "Delete 2FA account config (deleteTwoFaAccountConfig)", notes = |
|||
"Delete 2FA config for a given 2FA provider type. \n" + |
|||
"Returns whole account's 2FA settings object.\n" + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
|||
@DeleteMapping("/account/config") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public AccountTwoFaSettings deleteTwoFaAccountConfig(@RequestParam TwoFaProviderType providerType) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
return twoFaConfigManager.deleteTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType); |
|||
} |
|||
|
|||
|
|||
@ApiOperation(value = "Get available 2FA providers (getAvailableTwoFaProviders)", notes = |
|||
"Get the list of provider types available for user to use (the ones configured by tenant or sysadmin).\n" + |
|||
"Example of response:\n" + |
|||
"```\n[\n \"TOTP\",\n \"EMAIL\",\n \"SMS\"\n]\n```" + |
|||
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER |
|||
) |
|||
@GetMapping("/providers") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
|||
public List<TwoFaProviderType> getAvailableTwoFaProviders() throws ThingsboardException { |
|||
return twoFaConfigManager.getPlatformTwoFaSettings(getTenantId(), true) |
|||
.map(PlatformTwoFaSettings::getProviders).orElse(Collections.emptyList()).stream() |
|||
.map(TwoFaProviderConfig::getProviderType) |
|||
.collect(Collectors.toList()); |
|||
} |
|||
|
|||
|
|||
@ApiOperation(value = "Get platform 2FA settings (getPlatformTwoFaSettings)", |
|||
notes = "Get platform settings for 2FA. The settings are described for savePlatformTwoFaSettings API method. " + |
|||
"If 2FA is not configured, then an empty response will be returned." + |
|||
ControllerConstants.SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) |
|||
@GetMapping("/settings") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')") |
|||
public PlatformTwoFaSettings getPlatformTwoFaSettings() throws ThingsboardException { |
|||
return twoFaConfigManager.getPlatformTwoFaSettings(getTenantId(), false).orElse(null); |
|||
} |
|||
|
|||
@ApiOperation(value = "Save platform 2FA settings (savePlatformTwoFaSettings)", |
|||
notes = "Save 2FA settings for platform. The settings have following properties:\n" + |
|||
"- `providers` - the list of 2FA providers' configs. Users will only be allowed to use 2FA providers from this list. \n\n" + |
|||
"- `minVerificationCodeSendPeriod` - minimal period in seconds to wait after verification code send request to send next request. \n" + |
|||
"- `verificationCodeCheckRateLimit` - rate limit configuration for verification code checking.\n" + |
|||
"The format is standard: 'amountOfRequests:periodInSeconds'. The value of '1:60' would limit verification " + |
|||
"code checking requests to one per minute.\n" + |
|||
"- `maxVerificationFailuresBeforeUserLockout` - maximum number of verification failures before a user gets disabled.\n" + |
|||
"- `totalAllowedTimeForVerification` - total amount of time in seconds allotted for verification. " + |
|||
"Basically, this property sets a lifetime for pre-verification token. If not set, default value of 30 minutes is used.\n" + NEW_LINE + |
|||
"TOTP 2FA provider config has following settings:\n" + |
|||
"- `issuerName` - issuer name that will be displayed in an authenticator app near a username. Must not be blank.\n\n" + |
|||
"For SMS 2FA provider:\n" + |
|||
"- `smsVerificationMessageTemplate` - verification message template. Available template variables " + |
|||
"are ${code} and ${userEmail}. It must not be blank and must contain verification code variable.\n" + |
|||
"- `verificationCodeLifetime` - verification code lifetime in seconds. Required to be positive.\n\n" + |
|||
"For EMAIL provider type:\n" + |
|||
"- `verificationCodeLifetime` - the same as for SMS." + NEW_LINE + |
|||
"Example of the settings:\n" + |
|||
"```\n{\n" + |
|||
" \"providers\": [\n" + |
|||
" {\n" + |
|||
" \"providerType\": \"TOTP\",\n" + |
|||
" \"issuerName\": \"TB\"\n" + |
|||
" },\n" + |
|||
" {\n" + |
|||
" \"providerType\": \"EMAIL\",\n" + |
|||
" \"verificationCodeLifetime\": 60\n" + |
|||
" },\n" + |
|||
" {\n" + |
|||
" \"providerType\": \"SMS\",\n" + |
|||
" \"verificationCodeLifetime\": 60,\n" + |
|||
" \"smsVerificationMessageTemplate\": \"Here is your verification code: ${code}\"\n" + |
|||
" }\n" + |
|||
" ],\n" + |
|||
" \"minVerificationCodeSendPeriod\": 60,\n" + |
|||
" \"verificationCodeCheckRateLimit\": \"3:900\",\n" + |
|||
" \"maxVerificationFailuresBeforeUserLockout\": 10,\n" + |
|||
" \"totalAllowedTimeForVerification\": 600\n" + |
|||
"}\n```" + |
|||
ControllerConstants.SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) |
|||
@PostMapping("/settings") |
|||
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')") |
|||
public PlatformTwoFaSettings savePlatformTwoFaSettings(@ApiParam(value = "Settings value", required = true) |
|||
@RequestBody PlatformTwoFaSettings twoFaSettings) throws ThingsboardException { |
|||
return twoFaConfigManager.savePlatformTwoFaSettings(getTenantId(), twoFaSettings); |
|||
} |
|||
|
|||
|
|||
@Data |
|||
public static class TwoFaAccountConfigUpdateRequest { |
|||
private boolean useByDefault; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,152 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.controller; |
|||
|
|||
import io.swagger.annotations.ApiOperation; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.security.access.prepost.PreAuthorize; |
|||
import org.springframework.web.bind.annotation.GetMapping; |
|||
import org.springframework.web.bind.annotation.PostMapping; |
|||
import org.springframework.web.bind.annotation.RequestMapping; |
|||
import org.springframework.web.bind.annotation.RequestParam; |
|||
import org.springframework.web.bind.annotation.RestController; |
|||
import org.thingsboard.server.common.data.StringUtils; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.EmailTwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.SmsTwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.dao.user.UserService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; |
|||
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
|||
import org.thingsboard.server.service.security.auth.rest.RestAuthenticationDetails; |
|||
import org.thingsboard.server.service.security.model.JwtTokenPair; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; |
|||
import org.thingsboard.server.service.security.system.SystemSecurityService; |
|||
|
|||
import javax.servlet.http.HttpServletRequest; |
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
import java.util.Optional; |
|||
import java.util.stream.Collectors; |
|||
|
|||
import static org.thingsboard.server.controller.ControllerConstants.NEW_LINE; |
|||
|
|||
@RestController |
|||
@RequestMapping("/api/auth/2fa") |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class TwoFactorAuthController extends BaseController { |
|||
|
|||
private final TwoFactorAuthService twoFactorAuthService; |
|||
private final TwoFaConfigManager twoFaConfigManager; |
|||
private final JwtTokenFactory tokenFactory; |
|||
private final SystemSecurityService systemSecurityService; |
|||
private final UserService userService; |
|||
|
|||
|
|||
@ApiOperation(value = "Request 2FA verification code (requestTwoFaVerificationCode)", |
|||
notes = "Request 2FA verification code." + NEW_LINE + |
|||
"To make a request to this endpoint, you need an access token with the scope of PRE_VERIFICATION_TOKEN, " + |
|||
"which is issued on username/password auth if 2FA is enabled." + NEW_LINE + |
|||
"The API method is rate limited (using rate limit config from TwoFactorAuthSettings). " + |
|||
"Will return a Bad Request error if provider is not configured for usage, " + |
|||
"and Too Many Requests error if rate limits are exceeded.") |
|||
@PostMapping("/verification/send") |
|||
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
|||
public void requestTwoFaVerificationCode(@RequestParam TwoFaProviderType providerType) throws Exception { |
|||
SecurityUser user = getCurrentUser(); |
|||
twoFactorAuthService.prepareVerificationCode(user, providerType, true); |
|||
} |
|||
|
|||
@ApiOperation(value = "Check 2FA verification code (checkTwoFaVerificationCode)", |
|||
notes = "Checks 2FA verification code, and if it is correct the method returns a regular access and refresh token pair." + NEW_LINE + |
|||
"The API method is rate limited (using rate limit config from TwoFactorAuthSettings), and also will block a user " + |
|||
"after X unsuccessful verification attempts if such behavior is configured (in TwoFactorAuthSettings)." + NEW_LINE + |
|||
"Will return a Bad Request error if provider is not configured for usage, " + |
|||
"and Too Many Requests error if rate limits are exceeded.") |
|||
@PostMapping("/verification/check") |
|||
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
|||
public JwtTokenPair checkTwoFaVerificationCode(@RequestParam TwoFaProviderType providerType, |
|||
@RequestParam String verificationCode, HttpServletRequest servletRequest) throws Exception { |
|||
SecurityUser user = getCurrentUser(); |
|||
boolean verificationSuccess = twoFactorAuthService.checkVerificationCode(user, providerType, verificationCode, true); |
|||
if (verificationSuccess) { |
|||
systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(servletRequest), ActionType.LOGIN, null); |
|||
user = new SecurityUser(userService.findUserById(user.getTenantId(), user.getId()), true, user.getUserPrincipal()); |
|||
return tokenFactory.createTokenPair(user); |
|||
} else { |
|||
ThingsboardException error = new ThingsboardException("Verification code is incorrect", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(servletRequest), ActionType.LOGIN, error); |
|||
throw error; |
|||
} |
|||
} |
|||
|
|||
|
|||
@ApiOperation(value = "Get available 2FA providers (getAvailableTwoFaProviders)", notes = |
|||
"Get the list of 2FA provider infos available for user to use. Example:\n" + |
|||
"```\n[\n" + |
|||
" {\n \"type\": \"EMAIL\",\n \"default\": true,\n \"contact\": \"ab*****ko@gmail.com\"\n },\n" + |
|||
" {\n \"type\": \"TOTP\",\n \"default\": false,\n \"contact\": null\n },\n" + |
|||
" {\n \"type\": \"SMS\",\n \"default\": false,\n \"contact\": \"+38********12\"\n }\n" + |
|||
"]\n```") |
|||
@GetMapping("/providers") |
|||
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
|||
public List<TwoFaProviderInfo> getAvailableTwoFaProviders() throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
Optional<PlatformTwoFaSettings> platformTwoFaSettings = twoFaConfigManager.getPlatformTwoFaSettings(user.getTenantId(), true); |
|||
return twoFaConfigManager.getAccountTwoFaSettings(user.getTenantId(), user.getId()) |
|||
.map(settings -> settings.getConfigs().values()).orElse(Collections.emptyList()) |
|||
.stream().map(config -> { |
|||
String contact = null; |
|||
switch (config.getProviderType()) { |
|||
case SMS: |
|||
String phoneNumber = ((SmsTwoFaAccountConfig) config).getPhoneNumber(); |
|||
contact = StringUtils.obfuscate(phoneNumber, 2, '*', phoneNumber.indexOf('+') + 1, phoneNumber.length()); |
|||
break; |
|||
case EMAIL: |
|||
String email = ((EmailTwoFaAccountConfig) config).getEmail(); |
|||
contact = StringUtils.obfuscate(email, 2, '*', 0, email.indexOf('@')); |
|||
break; |
|||
} |
|||
return TwoFaProviderInfo.builder() |
|||
.type(config.getProviderType()) |
|||
.isDefault(config.isUseByDefault()) |
|||
.contact(contact) |
|||
.minVerificationCodeSendPeriod(platformTwoFaSettings.get().getMinVerificationCodeSendPeriod()) |
|||
.build(); |
|||
}) |
|||
.collect(Collectors.toList()); |
|||
} |
|||
|
|||
@Data |
|||
@AllArgsConstructor |
|||
@Builder |
|||
public static class TwoFaProviderInfo { |
|||
private TwoFaProviderType type; |
|||
private boolean isDefault; |
|||
private String contact; |
|||
private Integer minVerificationCodeSendPeriod; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,275 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.dashboard; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.Dashboard; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.ShortCustomerInfo; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.HashSet; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
public class DefaultTbDashboardService extends AbstractTbEntityService implements TbDashboardService { |
|||
|
|||
@Override |
|||
public Dashboard save(Dashboard dashboard, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
|||
TenantId tenantId = dashboard.getTenantId(); |
|||
try { |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); |
|||
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, |
|||
null, actionType, user); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), dashboard, null, actionType, user, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(Dashboard dashboard, SecurityUser user) throws ThingsboardException { |
|||
DashboardId dashboardId = dashboard.getId(); |
|||
TenantId tenantId = dashboard.getTenantId(); |
|||
try { |
|||
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); |
|||
dashboardService.deleteDashboard(tenantId, dashboardId); |
|||
notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, |
|||
ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
ActionType.DELETED, user, e, dashboardId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard assignDashboardToCustomer(DashboardId dashboardId, Customer customer, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
CustomerId customerId = customer.getId(); |
|||
try { |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(user.getTenantId(), dashboardId, customerId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboardId, customerId, savedDashboard, |
|||
actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboardId.toString(), customerId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard assignDashboardToPublicCustomer(DashboardId dashboardId, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
try { |
|||
Customer publicCustomer = customerService.findOrCreatePublicCustomer(user.getTenantId()); |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(user.getTenantId(), dashboardId, publicCustomer.getId())); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboardId, user.getCustomerId(), savedDashboard, |
|||
actionType, null, user, false, dashboardId.toString(), |
|||
publicCustomer.getId().toString(), publicCustomer.getName()); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboardId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; |
|||
try { |
|||
Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId()); |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(user.getTenantId(), dashboard.getId(), publicCustomer.getId())); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboard.getId(), user.getCustomerId(), dashboard, |
|||
actionType, null, user, false, dashboard.getId().toString(), |
|||
publicCustomer.getId().toString(), publicCustomer.getName()); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboard.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard updateDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
TenantId tenantId = user.getTenantId(); |
|||
try { |
|||
Set<CustomerId> addedCustomerIds = new HashSet<>(); |
|||
Set<CustomerId> removedCustomerIds = new HashSet<>(); |
|||
for (CustomerId customerId : customerIds) { |
|||
if (!dashboard.isAssignedToCustomer(customerId)) { |
|||
addedCustomerIds.add(customerId); |
|||
} |
|||
} |
|||
|
|||
Set<ShortCustomerInfo> assignedCustomers = dashboard.getAssignedCustomers(); |
|||
if (assignedCustomers != null) { |
|||
for (ShortCustomerInfo customerInfo : assignedCustomers) { |
|||
if (!customerIds.contains(customerInfo.getCustomerId())) { |
|||
removedCustomerIds.add(customerInfo.getCustomerId()); |
|||
} |
|||
} |
|||
} |
|||
|
|||
if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { |
|||
return dashboard; |
|||
} else { |
|||
Dashboard savedDashboard = null; |
|||
for (CustomerId customerId : addedCustomerIds) { |
|||
savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); |
|||
ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, |
|||
actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); |
|||
} |
|||
for (CustomerId customerId : removedCustomerIds) { |
|||
ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); |
|||
savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, |
|||
ActionType.UNASSIGNED_FROM_CUSTOMER, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); |
|||
} |
|||
return savedDashboard; |
|||
} |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboard.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard addDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
TenantId tenantId = user.getTenantId(); |
|||
try { |
|||
if (customerIds.isEmpty()) { |
|||
return dashboard; |
|||
} else { |
|||
Dashboard savedDashboard = null; |
|||
for (CustomerId customerId : customerIds) { |
|||
savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); |
|||
ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, |
|||
actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); |
|||
} |
|||
return savedDashboard; |
|||
} |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboard.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard removeDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; |
|||
TenantId tenantId = user.getTenantId(); |
|||
try { |
|||
if (customerIds.isEmpty()) { |
|||
return dashboard; |
|||
} else { |
|||
Dashboard savedDashboard = null; |
|||
for (CustomerId customerId : customerIds) { |
|||
ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); |
|||
savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, |
|||
actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); |
|||
} |
|||
return savedDashboard; |
|||
} |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboard.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard asignDashboardToEdge(DashboardId dashboardId, Edge edge, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_EDGE; |
|||
TenantId tenantId = user.getTenantId(); |
|||
EdgeId edgeId = edge.getId(); |
|||
try { |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, user.getCustomerId(), |
|||
edgeId, savedDashboard, actionType, user, dashboardId.toString(), |
|||
edgeId.toString(), edge.getName()); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, |
|||
actionType, user, e, dashboardId.toString(), edgeId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; |
|||
TenantId tenantId = dashboard.getTenantId(); |
|||
DashboardId dashboardId = dashboard.getId(); |
|||
EdgeId edgeId = edge.getId(); |
|||
try { |
|||
Dashboard savedDevice = checkNotNull(dashboardService.unassignDashboardFromEdge(tenantId, dashboardId, edgeId)); |
|||
|
|||
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, user.getCustomerId(), |
|||
edgeId, dashboard, actionType, user, dashboardId.toString(), |
|||
edgeId.toString(), edge.getName()); |
|||
return savedDevice; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboardId.toString(), edgeId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; |
|||
TenantId tenantId = dashboard.getTenantId(); |
|||
try { |
|||
Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, |
|||
actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); |
|||
return savedDashboard; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, |
|||
actionType, user, e, dashboard.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.dashboard; |
|||
|
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.Dashboard; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.service.entitiy.SimpleTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.Set; |
|||
|
|||
public interface TbDashboardService extends SimpleTbEntityService<Dashboard> { |
|||
|
|||
Dashboard assignDashboardToCustomer(DashboardId dashboardId, Customer customer, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard assignDashboardToPublicCustomer(DashboardId dashboardId, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard updateDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard addDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard removeDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard asignDashboardToEdge(DashboardId dashboardId, Edge edge, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, SecurityUser user) throws ThingsboardException; |
|||
|
|||
Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, SecurityUser user) throws ThingsboardException; |
|||
|
|||
} |
|||
@ -0,0 +1,111 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.deviceProfile; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.DeviceProfileId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.Objects; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
@Slf4j |
|||
public class DefaultTbDeviceProfileService extends AbstractTbEntityService implements TbDeviceProfileService { |
|||
@Override |
|||
public DeviceProfile save(DeviceProfile deviceProfile, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
|||
TenantId tenantId = deviceProfile.getTenantId(); |
|||
try { |
|||
boolean isFirmwareChanged = false; |
|||
boolean isSoftwareChanged = false; |
|||
|
|||
if (actionType.equals(ActionType.UPDATED)) { |
|||
DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); |
|||
if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { |
|||
isFirmwareChanged = true; |
|||
} |
|||
if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { |
|||
isSoftwareChanged = true; |
|||
} |
|||
} |
|||
DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile)); |
|||
|
|||
tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); |
|||
tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), |
|||
actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); |
|||
|
|||
otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); |
|||
|
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), savedDeviceProfile, user, actionType, true, null); |
|||
return savedDeviceProfile; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.DEVICE_PROFILE), deviceProfile, user, actionType, false, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(DeviceProfile deviceProfile, SecurityUser user) throws ThingsboardException { |
|||
DeviceProfileId deviceProfileId = deviceProfile.getId(); |
|||
TenantId tenantId = deviceProfile.getTenantId(); |
|||
try { |
|||
deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); |
|||
|
|||
tbClusterService.onDeviceProfileDelete(deviceProfile, null); |
|||
tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, user, ActionType.DELETED, true, null, deviceProfileId.toString()); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.DEVICE_PROFILE), null, user, ActionType.DELETED, false, e, deviceProfileId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, SecurityUser user) throws ThingsboardException { |
|||
TenantId tenantId = deviceProfile.getTenantId(); |
|||
try { |
|||
|
|||
if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfile.getId())) { |
|||
if (previousDefaultDeviceProfile != null) { |
|||
previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); |
|||
notificationEntityService.notifyEntity(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, null, |
|||
ActionType.UPDATED, user, null); |
|||
} |
|||
deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); |
|||
|
|||
notificationEntityService.notifyEntity(tenantId, deviceProfile.getId(), deviceProfile, null, |
|||
ActionType.UPDATED, user, null); |
|||
} |
|||
return deviceProfile; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE_PROFILE), null, null, |
|||
ActionType.UPDATED, user, e, deviceProfile.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.deviceProfile; |
|||
|
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.service.entitiy.SimpleTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TbDeviceProfileService extends SimpleTbEntityService<DeviceProfile> { |
|||
|
|||
DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, SecurityUser user) throws ThingsboardException; |
|||
} |
|||
@ -0,0 +1,76 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.entityRelation; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.relation.EntityRelation; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
@Slf4j |
|||
public class DefaultTbEntityRelationService extends AbstractTbEntityService implements TbEntityRelationService { |
|||
@Override |
|||
public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, SecurityUser user) throws ThingsboardException { |
|||
try { |
|||
relationService.saveRelation(tenantId, relation); |
|||
notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, |
|||
relation, user, ActionType.RELATION_ADD_OR_UPDATE, null, relation); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, |
|||
relation, user, ActionType.RELATION_ADD_OR_UPDATE, e, relation); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, SecurityUser user) throws ThingsboardException { |
|||
try { |
|||
Boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); |
|||
if (!found) { |
|||
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); |
|||
} |
|||
notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, |
|||
relation, user, ActionType.RELATION_DELETED, null, relation); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, |
|||
relation, user, ActionType.RELATION_DELETED, e, relation); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, SecurityUser user) throws ThingsboardException { |
|||
try { |
|||
relationService.deleteEntityRelations(tenantId, entityId); |
|||
notificationEntityService.notifyEntity(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user, null); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.entityRelation; |
|||
|
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.relation.EntityRelation; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TbEntityRelationService { |
|||
|
|||
void save(TenantId tenantId, CustomerId customerId, EntityRelation entity, SecurityUser user) throws ThingsboardException; |
|||
|
|||
void delete (TenantId tenantId, CustomerId customerId, EntityRelation entity, SecurityUser user) throws ThingsboardException; |
|||
|
|||
void deleteRelations (TenantId tenantId, CustomerId customerId, EntityId entityId, SecurityUser user) throws ThingsboardException; |
|||
|
|||
} |
|||
@ -0,0 +1,388 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.entityView; |
|||
|
|||
import com.google.common.util.concurrent.FutureCallback; |
|||
import com.google.common.util.concurrent.Futures; |
|||
import com.google.common.util.concurrent.ListenableFuture; |
|||
import com.google.common.util.concurrent.MoreExecutors; |
|||
import com.google.common.util.concurrent.SettableFuture; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.DataConstants; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.EntityView; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.EntityViewId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.kv.AttributeKvEntry; |
|||
import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; |
|||
import org.thingsboard.server.common.data.kv.ReadTsKvQuery; |
|||
import org.thingsboard.server.common.data.kv.TsKvEntry; |
|||
import org.thingsboard.server.dao.timeseries.TimeseriesService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import javax.annotation.Nullable; |
|||
import java.util.ArrayList; |
|||
import java.util.Collection; |
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
import java.util.concurrent.ExecutionException; |
|||
import java.util.stream.Collectors; |
|||
|
|||
import static org.apache.commons.lang3.StringUtils.isBlank; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
@Slf4j |
|||
public class DefaultTbEntityViewService extends AbstractTbEntityService implements TbEntityViewService { |
|||
|
|||
private final TimeseriesService tsService; |
|||
|
|||
@Override |
|||
public EntityView save(EntityView entityView, EntityView existingEntityView, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
|||
try { |
|||
List<ListenableFuture<?>> futures = new ArrayList<>(); |
|||
if (existingEntityView != null) { |
|||
if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { |
|||
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); |
|||
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); |
|||
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); |
|||
} |
|||
List<String> tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? |
|||
existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); |
|||
futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); |
|||
} |
|||
EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); |
|||
if (savedEntityView.getKeys() != null) { |
|||
if (savedEntityView.getKeys().getAttributes() != null) { |
|||
futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); |
|||
futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user)); |
|||
futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user)); |
|||
} |
|||
futures.add(copyLatestFromEntityToEntityView(savedEntityView, user)); |
|||
} |
|||
for (ListenableFuture<?> future : futures) { |
|||
try { |
|||
future.get(); |
|||
} catch (InterruptedException | ExecutionException e) { |
|||
throw new RuntimeException("Failed to copy attributes to entity view", e); |
|||
} |
|||
} |
|||
|
|||
notificationEntityService.notifyCreateOrUpdateEntity(savedEntityView.getTenantId(), savedEntityView.getId(), savedEntityView, |
|||
null, actionType, user); |
|||
|
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.ENTITY_VIEW), entityView, null, actionType, user, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(EntityView entityView, SecurityUser user) throws ThingsboardException { |
|||
TenantId tenantId = entityView.getTenantId(); |
|||
EntityViewId entityViewId = entityView.getId(); |
|||
try { |
|||
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); |
|||
entityViewService.deleteEntityView(tenantId, entityViewId); |
|||
notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, |
|||
relatedEdgeIds, user, entityViewId.toString()); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, |
|||
ActionType.DELETED, user, e, entityViewId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
CustomerId customerId = customer.getId(); |
|||
try { |
|||
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, |
|||
actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); |
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, |
|||
actionType, user, e, entityViewId.toString(), customerId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, |
|||
EntityViewId entityViewId, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; |
|||
try { |
|||
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, |
|||
entityViewId, publicCustomer.getId())); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, |
|||
actionType, null, user, false, savedEntityView.getEntityId().toString(), |
|||
publicCustomer.getId().toString(), publicCustomer.getName()); |
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, |
|||
actionType, user, e, entityViewId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.ASSIGNED_TO_EDGE; |
|||
EdgeId edgeId = edge.getId(); |
|||
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId)); |
|||
try { |
|||
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, |
|||
edgeId, savedEntityView, actionType, user, savedEntityView.getEntityId().toString(), |
|||
edgeId.toString(), edge.getName()); |
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, |
|||
actionType, user, e, entityViewId.toString(), edgeId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public EntityView unassignEntityViewFromEdge(TenantId tenantId, CustomerId customerId, EntityView entityView, |
|||
Edge edge, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; |
|||
EntityViewId entityViewId = entityView.getId(); |
|||
EdgeId edgeId = edge.getId(); |
|||
try { |
|||
EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, |
|||
edgeId, entityView, actionType, user, entityViewId.toString(), |
|||
edgeId.toString(), edge.getName()); |
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, |
|||
actionType, user, e, entityViewId.toString(), edgeId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; |
|||
try { |
|||
EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); |
|||
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, |
|||
actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); |
|||
return savedEntityView; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, |
|||
actionType, user, e, entityViewId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, SecurityUser user) throws ThingsboardException { |
|||
EntityViewId entityId = entityView.getId(); |
|||
if (keys != null && !keys.isEmpty()) { |
|||
ListenableFuture<List<AttributeKvEntry>> getAttrFuture = attributesService.find(entityView.getTenantId(), entityView.getEntityId(), scope, keys); |
|||
return Futures.transform(getAttrFuture, attributeKvEntries -> { |
|||
List<AttributeKvEntry> attributes; |
|||
if (attributeKvEntries != null && !attributeKvEntries.isEmpty()) { |
|||
attributes = |
|||
attributeKvEntries.stream() |
|||
.filter(attributeKvEntry -> { |
|||
long startTime = entityView.getStartTimeMs(); |
|||
long endTime = entityView.getEndTimeMs(); |
|||
long lastUpdateTs = attributeKvEntry.getLastUpdateTs(); |
|||
return startTime == 0 && endTime == 0 || |
|||
(endTime == 0 && startTime < lastUpdateTs) || |
|||
(startTime == 0 && endTime > lastUpdateTs) |
|||
? true : startTime < lastUpdateTs && endTime > lastUpdateTs; |
|||
}).collect(Collectors.toList()); |
|||
tsSubService.saveAndNotify(entityView.getTenantId(), entityId, scope, attributes, new FutureCallback<Void>() { |
|||
@Override |
|||
public void onSuccess(@Nullable Void tmp) { |
|||
try { |
|||
logAttributesUpdated(entityView.getTenantId(), user, entityId, scope, attributes, null); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log attribute updates", e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void onFailure(Throwable t) { |
|||
try { |
|||
logAttributesUpdated(entityView.getTenantId(), user, entityId, scope, attributes, t); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log attribute updates", e); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
return null; |
|||
}, MoreExecutors.directExecutor()); |
|||
} else { |
|||
return Futures.immediateFuture(null); |
|||
} |
|||
} |
|||
|
|||
private ListenableFuture<List<Void>> copyLatestFromEntityToEntityView(EntityView entityView, SecurityUser user) { |
|||
EntityViewId entityId = entityView.getId(); |
|||
List<String> keys = entityView.getKeys() != null && entityView.getKeys().getTimeseries() != null ? |
|||
entityView.getKeys().getTimeseries() : Collections.emptyList(); |
|||
long startTs = entityView.getStartTimeMs(); |
|||
long endTs = entityView.getEndTimeMs() == 0 ? Long.MAX_VALUE : entityView.getEndTimeMs(); |
|||
ListenableFuture<List<String>> keysFuture; |
|||
if (keys.isEmpty()) { |
|||
keysFuture = Futures.transform(tsService.findAllLatest(user.getTenantId(), |
|||
entityView.getEntityId()), latest -> latest.stream().map(TsKvEntry::getKey).collect(Collectors.toList()), MoreExecutors.directExecutor()); |
|||
} else { |
|||
keysFuture = Futures.immediateFuture(keys); |
|||
} |
|||
ListenableFuture<List<TsKvEntry>> latestFuture = Futures.transformAsync(keysFuture, fetchKeys -> { |
|||
List<ReadTsKvQuery> queries = fetchKeys.stream().filter(key -> !isBlank(key)).map(key -> new BaseReadTsKvQuery(key, startTs, endTs, 1, "DESC")).collect(Collectors.toList()); |
|||
if (!queries.isEmpty()) { |
|||
return tsService.findAll(user.getTenantId(), entityView.getEntityId(), queries); |
|||
} else { |
|||
return Futures.immediateFuture(null); |
|||
} |
|||
}, MoreExecutors.directExecutor()); |
|||
return Futures.transform(latestFuture, latestValues -> { |
|||
if (latestValues != null && !latestValues.isEmpty()) { |
|||
tsSubService.saveLatestAndNotify(entityView.getTenantId(), entityId, latestValues, new FutureCallback<Void>() { |
|||
@Override |
|||
public void onSuccess(@Nullable Void tmp) { |
|||
} |
|||
|
|||
@Override |
|||
public void onFailure(Throwable t) { |
|||
} |
|||
}); |
|||
} |
|||
return null; |
|||
}, MoreExecutors.directExecutor()); |
|||
} |
|||
|
|||
private ListenableFuture<Void> deleteAttributesFromEntityView(EntityView entityView, String scope, List<String> keys, SecurityUser user) { |
|||
EntityViewId entityId = entityView.getId(); |
|||
SettableFuture<Void> resultFuture = SettableFuture.create(); |
|||
if (keys != null && !keys.isEmpty()) { |
|||
tsSubService.deleteAndNotify(entityView.getTenantId(), entityId, scope, keys, new FutureCallback<Void>() { |
|||
@Override |
|||
public void onSuccess(@Nullable Void tmp) { |
|||
try { |
|||
logAttributesDeleted(entityView.getTenantId(), user, entityId, scope, keys, null); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log attribute delete", e); |
|||
} |
|||
resultFuture.set(tmp); |
|||
} |
|||
|
|||
@Override |
|||
public void onFailure(Throwable t) { |
|||
try { |
|||
logAttributesDeleted(entityView.getTenantId(), user, entityId, scope, keys, t); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log attribute delete", e); |
|||
} |
|||
resultFuture.setException(t); |
|||
} |
|||
}); |
|||
} else { |
|||
resultFuture.set(null); |
|||
} |
|||
return resultFuture; |
|||
} |
|||
|
|||
private ListenableFuture<Void> deleteLatestFromEntityView(EntityView entityView, List<String> keys, SecurityUser user) { |
|||
EntityViewId entityId = entityView.getId(); |
|||
SettableFuture<Void> resultFuture = SettableFuture.create(); |
|||
if (keys != null && !keys.isEmpty()) { |
|||
tsSubService.deleteLatest(entityView.getTenantId(), entityId, keys, new FutureCallback<Void>() { |
|||
@Override |
|||
public void onSuccess(@Nullable Void tmp) { |
|||
try { |
|||
logTimeseriesDeleted(entityView.getTenantId(), user, entityId, keys, null); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log timeseries delete", e); |
|||
} |
|||
resultFuture.set(tmp); |
|||
} |
|||
|
|||
@Override |
|||
public void onFailure(Throwable t) { |
|||
try { |
|||
logTimeseriesDeleted(entityView.getTenantId(),user, entityId, keys, t); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log timeseries delete", e); |
|||
} |
|||
resultFuture.setException(t); |
|||
} |
|||
}); |
|||
} else { |
|||
tsSubService.deleteAllLatest(entityView.getTenantId(), entityId, new FutureCallback<Collection<String>>() { |
|||
@Override |
|||
public void onSuccess(@Nullable Collection<String> keys) { |
|||
try { |
|||
logTimeseriesDeleted(entityView.getTenantId(), user, entityId, new ArrayList<>(keys), null); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log timeseries delete", e); |
|||
} |
|||
resultFuture.set(null); |
|||
} |
|||
|
|||
@Override |
|||
public void onFailure(Throwable t) { |
|||
try { |
|||
logTimeseriesDeleted(entityView.getTenantId(), user, entityId, Collections.emptyList(), t); |
|||
} catch (ThingsboardException e) { |
|||
log.error("Failed to log timeseries delete", e); |
|||
} |
|||
resultFuture.setException(t); |
|||
} |
|||
}); |
|||
} |
|||
return resultFuture; |
|||
} |
|||
|
|||
private void logAttributesUpdated(TenantId tenantId, SecurityUser user, EntityId entityId, String scope, List<AttributeKvEntry> attributes, Throwable e) throws ThingsboardException { |
|||
notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.ATTRIBUTES_UPDATED, user, toException(e), scope, attributes); |
|||
} |
|||
|
|||
private void logAttributesDeleted(TenantId tenantId, SecurityUser user, EntityId entityId, String scope, List<String> keys, Throwable e) throws ThingsboardException { |
|||
notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys); |
|||
} |
|||
|
|||
private void logTimeseriesDeleted(TenantId tenantId, SecurityUser user, EntityId entityId, List<String> keys, Throwable e) throws ThingsboardException { |
|||
notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.TIMESERIES_DELETED, user, toException(e), keys); |
|||
} |
|||
|
|||
public static Exception toException(Throwable error) { |
|||
return error != null ? (Exception.class.isInstance(error) ? (Exception) error : new Exception(error)) : null; |
|||
} |
|||
} |
|||
@ -0,0 +1,47 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.entityView; |
|||
|
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.EntityView; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.EntityViewId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TbEntityViewService { |
|||
|
|||
EntityView save(EntityView entityView, EntityView existingEntityView, SecurityUser user) throws ThingsboardException; |
|||
|
|||
void delete (EntityView entity, SecurityUser user) throws ThingsboardException; |
|||
|
|||
EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, |
|||
SecurityUser user) throws ThingsboardException; |
|||
|
|||
EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, |
|||
EntityViewId entityViewId, SecurityUser user) throws ThingsboardException; |
|||
|
|||
EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, |
|||
SecurityUser user) throws ThingsboardException; |
|||
|
|||
EntityView unassignEntityViewFromEdge(TenantId tenantId, CustomerId customerId, EntityView entityView, |
|||
Edge edge, SecurityUser user) throws ThingsboardException; |
|||
|
|||
EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, |
|||
SecurityUser user) throws ThingsboardException; |
|||
} |
|||
@ -0,0 +1,107 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.otaPackageController; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.thingsboard.server.common.data.StringUtils; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.OtaPackage; |
|||
import org.thingsboard.server.common.data.OtaPackageInfo; |
|||
import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.OtaPackageId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.ota.ChecksumAlgorithm; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.nio.ByteBuffer; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
@Slf4j |
|||
public class DefaultTbOtaPackageService extends AbstractTbEntityService implements TbOtaPackageService { |
|||
@Override |
|||
public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, SecurityUser user) throws ThingsboardException { |
|||
TenantId tenantId = saveOtaPackageInfoRequest.getTenantId(); |
|||
ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
|||
try { |
|||
OtaPackageInfo savedOtaPackageInfo = otaPackageService.saveOtaPackageInfo(new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl()); |
|||
notificationEntityService.notifyEntity(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, null, |
|||
actionType, user, null); |
|||
return savedOtaPackageInfo; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), saveOtaPackageInfoRequest, null, |
|||
actionType, user, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(OtaPackageInfo otaPackageInfo, SecurityUser user) throws ThingsboardException { |
|||
TenantId tenantId = otaPackageInfo.getTenantId(); |
|||
OtaPackageId otaPackageId = otaPackageInfo.getId(); |
|||
try { |
|||
otaPackageService.deleteOtaPackage(tenantId, otaPackageId); |
|||
notificationEntityService.notifyEntity(tenantId, otaPackageId, otaPackageInfo, null, |
|||
ActionType.DELETED, user, null, otaPackageInfo.getId().toString()); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), null, null, |
|||
ActionType.DELETED, user, e, otaPackageInfo.getId().toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm, |
|||
byte[] data, String filename, String contentType, SecurityUser user) throws ThingsboardException { |
|||
TenantId tenantId = otaPackageInfo.getTenantId(); |
|||
OtaPackageId otaPackageId = otaPackageInfo.getId(); |
|||
try { |
|||
if (StringUtils.isEmpty(checksum)) { |
|||
checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); |
|||
} |
|||
OtaPackage otaPackage = new OtaPackage(otaPackageId); |
|||
otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime()); |
|||
otaPackage.setTenantId(tenantId); |
|||
otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId()); |
|||
otaPackage.setType(otaPackageInfo.getType()); |
|||
otaPackage.setTitle(otaPackageInfo.getTitle()); |
|||
otaPackage.setVersion(otaPackageInfo.getVersion()); |
|||
otaPackage.setTag(otaPackageInfo.getTag()); |
|||
otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo()); |
|||
otaPackage.setChecksumAlgorithm(checksumAlgorithm); |
|||
otaPackage.setChecksum(checksum); |
|||
otaPackage.setFileName(filename); |
|||
otaPackage.setContentType(contentType); |
|||
otaPackage.setData(ByteBuffer.wrap(data)); |
|||
otaPackage.setDataSize((long) data.length); |
|||
OtaPackageInfo savedOtaPackage = otaPackageService.saveOtaPackage(otaPackage); |
|||
notificationEntityService.notifyEntity(tenantId, savedOtaPackage.getId(), savedOtaPackage, null, |
|||
ActionType.UPDATED, user, null); |
|||
return savedOtaPackage; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), null, null, |
|||
ActionType.UPDATED, user, e, otaPackageId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.otaPackageController; |
|||
|
|||
import org.thingsboard.server.common.data.OtaPackageInfo; |
|||
import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.ota.ChecksumAlgorithm; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TbOtaPackageService { |
|||
|
|||
OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, SecurityUser user) throws ThingsboardException; |
|||
|
|||
void delete(OtaPackageInfo otaPackageInfo, SecurityUser user) throws ThingsboardException; |
|||
|
|||
OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm, |
|||
byte[] data, String filename, String contentType, SecurityUser securityUser) throws ThingsboardException; |
|||
} |
|||
@ -0,0 +1,269 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.queue; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.TenantProfile; |
|||
import org.thingsboard.server.common.data.id.QueueId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.page.PageLink; |
|||
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; |
|||
import org.thingsboard.server.common.data.queue.Queue; |
|||
import org.thingsboard.server.common.data.tenant.profile.TenantProfileQueueConfiguration; |
|||
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.queue.TbQueueAdmin; |
|||
import org.thingsboard.server.queue.scheduler.SchedulerComponent; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.concurrent.TimeUnit; |
|||
import java.util.stream.Collectors; |
|||
|
|||
@Slf4j |
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
public class DefaultTbQueueService extends AbstractTbEntityService implements TbQueueService { |
|||
private static final String MAIN = "Main"; |
|||
private static final long DELETE_DELAY = 30; |
|||
|
|||
private final TbClusterService tbClusterService; |
|||
private final TbQueueAdmin tbQueueAdmin; |
|||
private final DeviceProfileService deviceProfileService; |
|||
private final SchedulerComponent scheduler; |
|||
|
|||
@Override |
|||
public Queue saveQueue(Queue queue) { |
|||
boolean create = queue.getId() == null; |
|||
Queue oldQueue; |
|||
|
|||
if (create) { |
|||
oldQueue = null; |
|||
} else { |
|||
oldQueue = queueService.findQueueById(queue.getTenantId(), queue.getId()); |
|||
} |
|||
|
|||
//TODO: add checkNotNull
|
|||
Queue savedQueue = queueService.saveQueue(queue); |
|||
|
|||
if (create) { |
|||
onQueueCreated(savedQueue); |
|||
} else { |
|||
onQueueUpdated(savedQueue, oldQueue); |
|||
} |
|||
|
|||
return savedQueue; |
|||
} |
|||
|
|||
@Override |
|||
public void deleteQueue(TenantId tenantId, QueueId queueId) { |
|||
Queue queue = queueService.findQueueById(tenantId, queueId); |
|||
queueService.deleteQueue(tenantId, queueId); |
|||
onQueueDeleted(queue); |
|||
} |
|||
|
|||
@Override |
|||
public void deleteQueueByQueueName(TenantId tenantId, String queueName) { |
|||
Queue queue = queueService.findQueueByTenantIdAndNameInternal(tenantId, queueName); |
|||
queueService.deleteQueue(tenantId, queue.getId()); |
|||
onQueueDeleted(queue); |
|||
} |
|||
|
|||
private void onQueueCreated(Queue queue) { |
|||
for (int i = 0; i < queue.getPartitions(); i++) { |
|||
tbQueueAdmin.createTopicIfNotExists( |
|||
new TopicPartitionInfo(queue.getTopic(), queue.getTenantId(), i, false).getFullTopicName()); |
|||
} |
|||
|
|||
tbClusterService.onQueueChange(queue); |
|||
} |
|||
|
|||
private void onQueueUpdated(Queue queue, Queue oldQueue) { |
|||
int oldPartitions = oldQueue.getPartitions(); |
|||
int currentPartitions = queue.getPartitions(); |
|||
|
|||
if (currentPartitions != oldPartitions) { |
|||
if (currentPartitions > oldPartitions) { |
|||
log.info("Added [{}] new partitions to [{}] queue", currentPartitions - oldPartitions, queue.getName()); |
|||
for (int i = oldPartitions; i < currentPartitions; i++) { |
|||
tbQueueAdmin.createTopicIfNotExists( |
|||
new TopicPartitionInfo(queue.getTopic(), queue.getTenantId(), i, false).getFullTopicName()); |
|||
} |
|||
tbClusterService.onQueueChange(queue); |
|||
} else { |
|||
log.info("Removed [{}] partitions from [{}] queue", oldPartitions - currentPartitions, queue.getName()); |
|||
tbClusterService.onQueueChange(queue); |
|||
|
|||
scheduler.schedule(() -> { |
|||
for (int i = currentPartitions; i < oldPartitions; i++) { |
|||
String fullTopicName = new TopicPartitionInfo(queue.getTopic(), queue.getTenantId(), i, false).getFullTopicName(); |
|||
log.info("Removed partition [{}]", fullTopicName); |
|||
tbQueueAdmin.deleteTopic( |
|||
fullTopicName); |
|||
} |
|||
}, DELETE_DELAY, TimeUnit.SECONDS); |
|||
} |
|||
} else if (!oldQueue.equals(queue)) { |
|||
tbClusterService.onQueueChange(queue); |
|||
} |
|||
} |
|||
|
|||
private void onQueueDeleted(Queue queue) { |
|||
tbClusterService.onQueueDelete(queue); |
|||
|
|||
// queueStatsService.deleteQueueStatsByQueueId(tenantId, queueId);
|
|||
|
|||
scheduler.schedule(() -> { |
|||
for (int i = 0; i < queue.getPartitions(); i++) { |
|||
String fullTopicName = new TopicPartitionInfo(queue.getTopic(), queue.getTenantId(), i, false).getFullTopicName(); |
|||
log.info("Deleting queue [{}]", fullTopicName); |
|||
try { |
|||
tbQueueAdmin.deleteTopic(fullTopicName); |
|||
} catch (Exception e) { |
|||
log.error("Failed to delete queue [{}]", fullTopicName); |
|||
} |
|||
} |
|||
}, DELETE_DELAY, TimeUnit.SECONDS); |
|||
} |
|||
|
|||
@Override |
|||
public void updateQueuesByTenants(List<TenantId> tenantIds, TenantProfile newTenantProfile, TenantProfile |
|||
oldTenantProfile) { |
|||
boolean oldIsolated = oldTenantProfile != null && oldTenantProfile.isIsolatedTbRuleEngine(); |
|||
boolean newIsolated = newTenantProfile.isIsolatedTbRuleEngine(); |
|||
|
|||
if (!oldIsolated && !newIsolated) { |
|||
return; |
|||
} |
|||
|
|||
if (newTenantProfile.equals(oldTenantProfile)) { |
|||
return; |
|||
} |
|||
|
|||
Map<String, TenantProfileQueueConfiguration> oldQueues; |
|||
Map<String, TenantProfileQueueConfiguration> newQueues; |
|||
|
|||
if (oldIsolated) { |
|||
oldQueues = oldTenantProfile.getProfileData().getQueueConfiguration().stream() |
|||
.collect(Collectors.toMap(TenantProfileQueueConfiguration::getName, q -> q)); |
|||
} else { |
|||
oldQueues = Collections.emptyMap(); |
|||
} |
|||
|
|||
if (newIsolated) { |
|||
newQueues = newTenantProfile.getProfileData().getQueueConfiguration().stream() |
|||
.collect(Collectors.toMap(TenantProfileQueueConfiguration::getName, q -> q)); |
|||
} else { |
|||
newQueues = Collections.emptyMap(); |
|||
} |
|||
|
|||
List<String> toRemove = new ArrayList<>(); |
|||
List<String> toCreate = new ArrayList<>(); |
|||
List<String> toUpdate = new ArrayList<>(); |
|||
|
|||
for (String oldQueue : oldQueues.keySet()) { |
|||
if (!newQueues.containsKey(oldQueue)) { |
|||
toRemove.add(oldQueue); |
|||
} |
|||
} |
|||
|
|||
for (String newQueue : newQueues.keySet()) { |
|||
if (oldQueues.containsKey(newQueue)) { |
|||
toUpdate.add(newQueue); |
|||
} else { |
|||
toCreate.add(newQueue); |
|||
} |
|||
} |
|||
|
|||
tenantIds.forEach(tenantId -> { |
|||
Map<QueueId, List<DeviceProfile>> deviceProfileQueues; |
|||
|
|||
if (oldTenantProfile != null && !newTenantProfile.getId().equals(oldTenantProfile.getId()) || !toRemove.isEmpty()) { |
|||
List<DeviceProfile> deviceProfiles = deviceProfileService.findDeviceProfiles(tenantId, new PageLink(Integer.MAX_VALUE)).getData(); |
|||
deviceProfileQueues = deviceProfiles.stream() |
|||
.filter(dp -> dp.getDefaultQueueId() != null) |
|||
.collect(Collectors.groupingBy(DeviceProfile::getDefaultQueueId)); |
|||
} else { |
|||
deviceProfileQueues = Collections.emptyMap(); |
|||
} |
|||
|
|||
Map<String, QueueId> createdQueues = toCreate.stream() |
|||
.map(key -> saveQueue(new Queue(tenantId, newQueues.get(key)))) |
|||
.collect(Collectors.toMap(Queue::getName, Queue::getId)); |
|||
|
|||
// assigning created queues to device profiles instead of system queues
|
|||
if (oldTenantProfile != null && !oldTenantProfile.isIsolatedTbRuleEngine()) { |
|||
deviceProfileQueues.forEach((queueId, list) -> { |
|||
Queue queue = queueService.findQueueById(TenantId.SYS_TENANT_ID, queueId); |
|||
QueueId queueIdToAssign = createdQueues.get(queue.getName()); |
|||
if (queueIdToAssign == null) { |
|||
queueIdToAssign = createdQueues.get(MAIN); |
|||
} |
|||
for (DeviceProfile deviceProfile : list) { |
|||
deviceProfile.setDefaultQueueId(queueIdToAssign); |
|||
saveDeviceProfile(deviceProfile); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
toUpdate.forEach(key -> { |
|||
Queue queueToUpdate = new Queue(tenantId, newQueues.get(key)); |
|||
Queue foundQueue = queueService.findQueueByTenantIdAndName(tenantId, key); |
|||
queueToUpdate.setId(foundQueue.getId()); |
|||
queueToUpdate.setCreatedTime(foundQueue.getCreatedTime()); |
|||
|
|||
if (queueToUpdate.equals(foundQueue)) { |
|||
//Queue not changed
|
|||
} else { |
|||
saveQueue(queueToUpdate); |
|||
} |
|||
}); |
|||
|
|||
toRemove.forEach(q -> { |
|||
Queue queue = queueService.findQueueByTenantIdAndNameInternal(tenantId, q); |
|||
QueueId queueIdForRemove = queue.getId(); |
|||
if (deviceProfileQueues.containsKey(queueIdForRemove)) { |
|||
Queue foundQueue = queueService.findQueueByTenantIdAndName(tenantId, q); |
|||
if (foundQueue == null || queue.equals(foundQueue)) { |
|||
foundQueue = queueService.findQueueByTenantIdAndName(tenantId, MAIN); |
|||
} |
|||
QueueId newQueueId = foundQueue.getId(); |
|||
deviceProfileQueues.get(queueIdForRemove).stream() |
|||
.peek(dp -> dp.setDefaultQueueId(newQueueId)) |
|||
.forEach(this::saveDeviceProfile); |
|||
} |
|||
deleteQueue(tenantId, queueIdForRemove); |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
//TODO: remove after implementing TbDeviceProfileService
|
|||
private void saveDeviceProfile(DeviceProfile deviceProfile) { |
|||
DeviceProfile savedDeviceProfile = deviceProfileService.saveDeviceProfile(deviceProfile); |
|||
tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); |
|||
tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), savedDeviceProfile.getId(), ComponentLifecycleEvent.UPDATED); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.queue; |
|||
|
|||
import org.thingsboard.server.common.data.TenantProfile; |
|||
import org.thingsboard.server.common.data.id.QueueId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.queue.Queue; |
|||
|
|||
import java.util.List; |
|||
|
|||
public interface TbQueueService { |
|||
|
|||
Queue saveQueue(Queue queue); |
|||
|
|||
void deleteQueue(TenantId tenantId, QueueId queueId); |
|||
|
|||
void deleteQueueByQueueName(TenantId tenantId, String queueName); |
|||
|
|||
void updateQueuesByTenants(List<TenantId> tenantIds, TenantProfile newTenantProfile, TenantProfile oldTenantProfile); |
|||
} |
|||
@ -0,0 +1,50 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.tenant_profile; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.TenantProfile; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.tenant.TenantProfileService; |
|||
import org.thingsboard.server.dao.tenant.TenantService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.queue.TbQueueService; |
|||
|
|||
import java.util.List; |
|||
|
|||
@Slf4j |
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
public class DefaultTbTenantProfileService implements TbTenantProfileService { |
|||
private final TbQueueService tbQueueService; |
|||
private final TenantProfileService tenantProfileService; |
|||
private final TenantService tenantService; |
|||
|
|||
@Override |
|||
public TenantProfile saveTenantProfile(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile) { |
|||
TenantProfile savedTenantProfile = tenantProfileService.saveTenantProfile(tenantId, tenantProfile); |
|||
|
|||
if (oldTenantProfile != null && savedTenantProfile.isIsolatedTbRuleEngine()) { |
|||
List<TenantId> tenantIds = tenantService.findTenantIdsByTenantProfileId(savedTenantProfile.getId()); |
|||
tbQueueService.updateQueuesByTenants(tenantIds, savedTenantProfile, oldTenantProfile); |
|||
} |
|||
|
|||
return savedTenantProfile; |
|||
} |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.tenant_profile; |
|||
|
|||
import org.thingsboard.server.common.data.TenantProfile; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
|
|||
public interface TbTenantProfileService { |
|||
TenantProfile saveTenantProfile(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile); |
|||
} |
|||
@ -0,0 +1,95 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.user; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.rule.engine.api.MailService; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.id.UserId; |
|||
import org.thingsboard.server.common.data.security.UserCredentials; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.security.system.SystemSecurityService; |
|||
|
|||
import javax.servlet.http.HttpServletRequest; |
|||
import java.util.List; |
|||
|
|||
import static org.thingsboard.server.controller.UserController.ACTIVATE_URL_PATTERN; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
@Slf4j |
|||
public class DefaultUserService extends AbstractTbEntityService implements TbUserService { |
|||
|
|||
private final MailService mailService; |
|||
private final SystemSecurityService systemSecurityService; |
|||
|
|||
@Override |
|||
public User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, |
|||
HttpServletRequest request, SecurityUser user) throws ThingsboardException { |
|||
ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
|||
try { |
|||
boolean sendEmail = tbUser.getId() == null && sendActivationMail; |
|||
User savedUser = checkNotNull(userService.saveUser(tbUser)); |
|||
if (sendEmail) { |
|||
UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); |
|||
String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); |
|||
String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, |
|||
userCredentials.getActivateToken()); |
|||
String email = savedUser.getEmail(); |
|||
try { |
|||
mailService.sendActivationEmail(activateUrl, email); |
|||
} catch (ThingsboardException e) { |
|||
userService.deleteUser(tenantId, savedUser.getId()); |
|||
throw e; |
|||
} |
|||
} |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, customerId, savedUser.getId(), |
|||
savedUser, user, actionType, true, null); |
|||
return savedUser; |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.USER), |
|||
tbUser, user, actionType, false, e); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(TenantId tenantId, CustomerId customerId, User tbUser, SecurityUser user) throws ThingsboardException { |
|||
UserId userId = tbUser.getId(); |
|||
try { |
|||
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, userId); |
|||
|
|||
userService.deleteUser(tenantId, userId); |
|||
notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, |
|||
ActionType.DELETED, relatedEdgeIds, user, userId.toString()); |
|||
} catch (Exception e) { |
|||
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.USER), |
|||
null, user, ActionType.DELETED, false, e, userId.toString()); |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,30 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.user; |
|||
|
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import javax.servlet.http.HttpServletRequest; |
|||
|
|||
public interface TbUserService { |
|||
User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, HttpServletRequest request, SecurityUser user) throws ThingsboardException; |
|||
|
|||
void delete (TenantId tenantId, CustomerId customerId, User tbUser, SecurityUser user) throws ThingsboardException; |
|||
} |
|||
@ -0,0 +1,53 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.widgetsBundle; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.widget.WidgetsBundle; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@AllArgsConstructor |
|||
public class DefaultWidgetsBundleService extends AbstractTbEntityService implements TbWidgetsBundleService{ |
|||
@Override |
|||
public WidgetsBundle save(WidgetsBundle widgetsBundle, SecurityUser user) throws ThingsboardException { |
|||
try { |
|||
WidgetsBundle savedWidgetsBundle = checkNotNull(widgetsBundleService.saveWidgetsBundle(widgetsBundle)); |
|||
notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), savedWidgetsBundle.getId(), |
|||
widgetsBundle.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED); |
|||
return savedWidgetsBundle; |
|||
} catch (Exception e) { |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void delete(WidgetsBundle widgetsBundle, SecurityUser user) throws ThingsboardException { |
|||
try { |
|||
widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getTenantId(), widgetsBundle.getId()); |
|||
notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), widgetsBundle.getId(), |
|||
EdgeEventActionType.DELETED); |
|||
} catch (Exception e) { |
|||
throw handleException(e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,22 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.entitiy.widgetsBundle; |
|||
|
|||
import org.thingsboard.server.common.data.widget.WidgetsBundle; |
|||
import org.thingsboard.server.service.entitiy.SimpleTbEntityService; |
|||
|
|||
public interface TbWidgetsBundleService extends SimpleTbEntityService<WidgetsBundle> { |
|||
} |
|||
@ -0,0 +1,48 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.install; |
|||
|
|||
import lombok.Data; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; |
|||
import org.springframework.boot.context.properties.ConfigurationProperties; |
|||
import org.springframework.context.annotation.Configuration; |
|||
import org.springframework.context.annotation.Profile; |
|||
import org.thingsboard.server.queue.settings.TbRuleEngineQueueConfiguration; |
|||
|
|||
import javax.annotation.PostConstruct; |
|||
import java.util.List; |
|||
|
|||
@Slf4j |
|||
@Data |
|||
@EnableAutoConfiguration |
|||
@Configuration |
|||
@ConfigurationProperties(prefix = "queue.rule-engine") |
|||
@Profile("install") |
|||
public class TbRuleEngineQueueConfigService { |
|||
|
|||
private String topic; |
|||
private List<TbRuleEngineQueueConfiguration> queues; |
|||
|
|||
@PostConstruct |
|||
public void validate() { |
|||
queues.stream().filter(queue -> queue.getName().equals("Main")).findFirst().orElseThrow(() -> { |
|||
log.error("Main queue is not configured in thingsboard.yml"); |
|||
return new RuntimeException("No \"Main\" queue configured!"); |
|||
}); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,44 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.queue; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.dao.queue.QueueService; |
|||
import org.thingsboard.server.queue.discovery.QueueRoutingInfo; |
|||
import org.thingsboard.server.queue.discovery.QueueRoutingInfoService; |
|||
|
|||
import java.util.List; |
|||
import java.util.stream.Collectors; |
|||
|
|||
@Slf4j |
|||
@Service |
|||
@ConditionalOnExpression("'${service.type:null}'=='monolith' || '${service.type:null}'=='tb-core' || '${service.type:null}'=='tb-rule-engine'") |
|||
public class DefaultQueueRoutingInfoService implements QueueRoutingInfoService { |
|||
|
|||
private final QueueService queueService; |
|||
|
|||
public DefaultQueueRoutingInfoService(QueueService queueService) { |
|||
this.queueService = queueService; |
|||
} |
|||
|
|||
@Override |
|||
public List<QueueRoutingInfo> getAllQueuesRoutingInfo() { |
|||
return queueService.findAllQueues().stream().map(QueueRoutingInfo::new).collect(Collectors.toList()); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth; |
|||
|
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public class MfaAuthenticationToken extends AbstractJwtAuthenticationToken { |
|||
public MfaAuthenticationToken(SecurityUser securityUser) { |
|||
super(securityUser); |
|||
} |
|||
} |
|||
@ -0,0 +1,190 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa; |
|||
|
|||
import lombok.RequiredArgsConstructor; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.security.authentication.LockedException; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.id.UserId; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.common.msg.tools.TbRateLimits; |
|||
import org.thingsboard.server.dao.user.UserService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
|||
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; |
|||
import org.thingsboard.server.service.security.auth.mfa.provider.TwoFaProvider; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.security.system.SystemSecurityService; |
|||
|
|||
import java.util.Collection; |
|||
import java.util.EnumMap; |
|||
import java.util.Map; |
|||
import java.util.Optional; |
|||
import java.util.concurrent.ConcurrentHashMap; |
|||
import java.util.concurrent.ConcurrentMap; |
|||
|
|||
@Service |
|||
@RequiredArgsConstructor |
|||
@TbCoreComponent |
|||
public class DefaultTwoFactorAuthService implements TwoFactorAuthService { |
|||
|
|||
private final TwoFaConfigManager configManager; |
|||
private final SystemSecurityService systemSecurityService; |
|||
private final UserService userService; |
|||
private final Map<TwoFaProviderType, TwoFaProvider<TwoFaProviderConfig, TwoFaAccountConfig>> providers = new EnumMap<>(TwoFaProviderType.class); |
|||
|
|||
private static final ThingsboardException ACCOUNT_NOT_CONFIGURED_ERROR = new ThingsboardException("2FA is not configured for account", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
private static final ThingsboardException PROVIDER_NOT_CONFIGURED_ERROR = new ThingsboardException("2FA provider is not configured", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
private static final ThingsboardException PROVIDER_NOT_AVAILABLE_ERROR = new ThingsboardException("2FA provider is not available", ThingsboardErrorCode.GENERAL); |
|||
|
|||
private final ConcurrentMap<UserId, ConcurrentMap<TwoFaProviderType, TbRateLimits>> verificationCodeSendingRateLimits = new ConcurrentHashMap<>(); |
|||
private final ConcurrentMap<UserId, ConcurrentMap<TwoFaProviderType, TbRateLimits>> verificationCodeCheckingRateLimits = new ConcurrentHashMap<>(); |
|||
|
|||
@Override |
|||
public boolean isTwoFaEnabled(TenantId tenantId, UserId userId) { |
|||
return configManager.getAccountTwoFaSettings(tenantId, userId) |
|||
.map(settings -> !settings.getConfigs().isEmpty()) |
|||
.orElse(false); |
|||
} |
|||
|
|||
@Override |
|||
public void checkProvider(TenantId tenantId, TwoFaProviderType providerType) throws ThingsboardException { |
|||
getTwoFaProvider(providerType).check(tenantId); |
|||
} |
|||
|
|||
|
|||
@Override |
|||
public void prepareVerificationCode(SecurityUser user, TwoFaProviderType providerType, boolean checkLimits) throws Exception { |
|||
TwoFaAccountConfig accountConfig = configManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType) |
|||
.orElseThrow(() -> ACCOUNT_NOT_CONFIGURED_ERROR); |
|||
prepareVerificationCode(user, accountConfig, checkLimits); |
|||
} |
|||
|
|||
@Override |
|||
public void prepareVerificationCode(SecurityUser user, TwoFaAccountConfig accountConfig, boolean checkLimits) throws ThingsboardException { |
|||
PlatformTwoFaSettings twoFaSettings = configManager.getPlatformTwoFaSettings(user.getTenantId(), true) |
|||
.orElseThrow(() -> PROVIDER_NOT_CONFIGURED_ERROR); |
|||
if (checkLimits) { |
|||
Integer minVerificationCodeSendPeriod = twoFaSettings.getMinVerificationCodeSendPeriod(); |
|||
String rateLimit = null; |
|||
if (minVerificationCodeSendPeriod != null && minVerificationCodeSendPeriod > 4) { |
|||
rateLimit = "1:" + minVerificationCodeSendPeriod; |
|||
} |
|||
checkRateLimits(user.getId(), accountConfig.getProviderType(), rateLimit, verificationCodeSendingRateLimits); |
|||
} |
|||
|
|||
TwoFaProviderConfig providerConfig = twoFaSettings.getProviderConfig(accountConfig.getProviderType()) |
|||
.orElseThrow(() -> PROVIDER_NOT_CONFIGURED_ERROR); |
|||
getTwoFaProvider(accountConfig.getProviderType()).prepareVerificationCode(user, providerConfig, accountConfig); |
|||
} |
|||
|
|||
|
|||
@Override |
|||
public boolean checkVerificationCode(SecurityUser user, TwoFaProviderType providerType, String verificationCode, boolean checkLimits) throws ThingsboardException { |
|||
TwoFaAccountConfig accountConfig = configManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType) |
|||
.orElseThrow(() -> ACCOUNT_NOT_CONFIGURED_ERROR); |
|||
return checkVerificationCode(user, verificationCode, accountConfig, checkLimits); |
|||
} |
|||
|
|||
@Override |
|||
public boolean checkVerificationCode(SecurityUser user, String verificationCode, TwoFaAccountConfig accountConfig, boolean checkLimits) throws ThingsboardException { |
|||
if (!userService.findUserCredentialsByUserId(user.getTenantId(), user.getId()).isEnabled()) { |
|||
throw new ThingsboardException("User is disabled", ThingsboardErrorCode.AUTHENTICATION); |
|||
} |
|||
|
|||
PlatformTwoFaSettings twoFaSettings = configManager.getPlatformTwoFaSettings(user.getTenantId(), true) |
|||
.orElseThrow(() -> PROVIDER_NOT_CONFIGURED_ERROR); |
|||
if (checkLimits) { |
|||
checkRateLimits(user.getId(), accountConfig.getProviderType(), twoFaSettings.getVerificationCodeCheckRateLimit(), verificationCodeCheckingRateLimits); |
|||
} |
|||
TwoFaProviderConfig providerConfig = twoFaSettings.getProviderConfig(accountConfig.getProviderType()) |
|||
.orElseThrow(() -> PROVIDER_NOT_CONFIGURED_ERROR); |
|||
|
|||
boolean verificationSuccess = false; |
|||
if (StringUtils.isNotBlank(verificationCode)) { |
|||
if (StringUtils.isNumeric(verificationCode) || accountConfig.getProviderType() == TwoFaProviderType.BACKUP_CODE) { |
|||
verificationSuccess = getTwoFaProvider(accountConfig.getProviderType()).checkVerificationCode(user, verificationCode, providerConfig, accountConfig); |
|||
} |
|||
} |
|||
if (checkLimits) { |
|||
try { |
|||
systemSecurityService.validateTwoFaVerification(user, verificationSuccess, twoFaSettings); |
|||
} catch (LockedException e) { |
|||
verificationCodeCheckingRateLimits.remove(user.getId()); |
|||
verificationCodeSendingRateLimits.remove(user.getId()); |
|||
throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.AUTHENTICATION); |
|||
} |
|||
if (verificationSuccess) { |
|||
verificationCodeCheckingRateLimits.remove(user.getId()); |
|||
verificationCodeSendingRateLimits.remove(user.getId()); |
|||
} |
|||
} |
|||
return verificationSuccess; |
|||
} |
|||
|
|||
private void checkRateLimits(UserId userId, TwoFaProviderType providerType, String rateLimitConfig, |
|||
ConcurrentMap<UserId, ConcurrentMap<TwoFaProviderType, TbRateLimits>> rateLimits) throws ThingsboardException { |
|||
if (StringUtils.isNotEmpty(rateLimitConfig)) { |
|||
ConcurrentMap<TwoFaProviderType, TbRateLimits> providersRateLimits = rateLimits.computeIfAbsent(userId, i -> new ConcurrentHashMap<>()); |
|||
|
|||
TbRateLimits rateLimit = providersRateLimits.get(providerType); |
|||
if (rateLimit == null || !rateLimit.getConfig().equals(rateLimitConfig)) { |
|||
rateLimit = new TbRateLimits(rateLimitConfig, true); |
|||
providersRateLimits.put(providerType, rateLimit); |
|||
} |
|||
if (!rateLimit.tryConsume()) { |
|||
throw new ThingsboardException("Too many requests", ThingsboardErrorCode.TOO_MANY_REQUESTS); |
|||
} |
|||
} else { |
|||
rateLimits.remove(userId); |
|||
} |
|||
} |
|||
|
|||
|
|||
@Override |
|||
public TwoFaAccountConfig generateNewAccountConfig(User user, TwoFaProviderType providerType) throws ThingsboardException { |
|||
TwoFaProviderConfig providerConfig = getTwoFaProviderConfig(user.getTenantId(), providerType); |
|||
return getTwoFaProvider(providerType).generateNewAccountConfig(user, providerConfig); |
|||
} |
|||
|
|||
|
|||
private TwoFaProviderConfig getTwoFaProviderConfig(TenantId tenantId, TwoFaProviderType providerType) throws ThingsboardException { |
|||
return configManager.getPlatformTwoFaSettings(tenantId, true) |
|||
.flatMap(twoFaSettings -> twoFaSettings.getProviderConfig(providerType)) |
|||
.orElseThrow(() -> PROVIDER_NOT_CONFIGURED_ERROR); |
|||
} |
|||
|
|||
private TwoFaProvider<TwoFaProviderConfig, TwoFaAccountConfig> getTwoFaProvider(TwoFaProviderType providerType) throws ThingsboardException { |
|||
return Optional.ofNullable(providers.get(providerType)) |
|||
.orElseThrow(() -> PROVIDER_NOT_AVAILABLE_ERROR); |
|||
} |
|||
|
|||
@Autowired |
|||
private void setProviders(Collection<TwoFaProvider> providers) { |
|||
providers.forEach(provider -> { |
|||
this.providers.put(provider.getType(), provider); |
|||
}); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,45 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa; |
|||
|
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.id.UserId; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TwoFactorAuthService { |
|||
|
|||
boolean isTwoFaEnabled(TenantId tenantId, UserId userId); |
|||
|
|||
void checkProvider(TenantId tenantId, TwoFaProviderType providerType) throws ThingsboardException; |
|||
|
|||
|
|||
void prepareVerificationCode(SecurityUser user, TwoFaProviderType providerType, boolean checkLimits) throws Exception; |
|||
|
|||
void prepareVerificationCode(SecurityUser user, TwoFaAccountConfig accountConfig, boolean checkLimits) throws ThingsboardException; |
|||
|
|||
|
|||
boolean checkVerificationCode(SecurityUser user, TwoFaProviderType providerType, String verificationCode, boolean checkLimits) throws ThingsboardException; |
|||
|
|||
boolean checkVerificationCode(SecurityUser user, String verificationCode, TwoFaAccountConfig accountConfig, boolean checkLimits) throws ThingsboardException; |
|||
|
|||
|
|||
TwoFaAccountConfig generateNewAccountConfig(User user, TwoFaProviderType providerType) throws ThingsboardException; |
|||
|
|||
} |
|||
@ -0,0 +1,187 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa.config; |
|||
|
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.context.annotation.Lazy; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.id.UserId; |
|||
import org.thingsboard.server.common.data.security.UserAuthSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.AccountTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.dao.service.ConstraintValidator; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsDao; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
import org.thingsboard.server.dao.user.UserAuthSettingsDao; |
|||
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; |
|||
|
|||
import java.util.Comparator; |
|||
import java.util.LinkedHashMap; |
|||
import java.util.Map; |
|||
import java.util.Optional; |
|||
|
|||
@Service |
|||
@RequiredArgsConstructor |
|||
public class DefaultTwoFaConfigManager implements TwoFaConfigManager { |
|||
|
|||
private final UserAuthSettingsDao userAuthSettingsDao; |
|||
private final AdminSettingsService adminSettingsService; |
|||
private final AdminSettingsDao adminSettingsDao; |
|||
@Autowired @Lazy |
|||
private TwoFactorAuthService twoFactorAuthService; |
|||
|
|||
protected static final String TWO_FACTOR_AUTH_SETTINGS_KEY = "twoFaSettings"; |
|||
|
|||
|
|||
@Override |
|||
public Optional<AccountTwoFaSettings> getAccountTwoFaSettings(TenantId tenantId, UserId userId) { |
|||
PlatformTwoFaSettings platformTwoFaSettings = getPlatformTwoFaSettings(tenantId, true).orElse(null); |
|||
return Optional.ofNullable(userAuthSettingsDao.findByUserId(userId)) |
|||
.map(userAuthSettings -> { |
|||
AccountTwoFaSettings twoFaSettings = userAuthSettings.getTwoFaSettings(); |
|||
if (twoFaSettings == null) return null; |
|||
boolean updateNeeded; |
|||
|
|||
Map<TwoFaProviderType, TwoFaAccountConfig> configs = twoFaSettings.getConfigs(); |
|||
updateNeeded = configs.keySet().removeIf(providerType -> { |
|||
return platformTwoFaSettings == null || platformTwoFaSettings.getProviderConfig(providerType).isEmpty(); |
|||
}); |
|||
if (configs.size() == 1 && configs.containsKey(TwoFaProviderType.BACKUP_CODE)) { |
|||
configs.remove(TwoFaProviderType.BACKUP_CODE); |
|||
updateNeeded = true; |
|||
} |
|||
if (!configs.isEmpty() && configs.values().stream().noneMatch(TwoFaAccountConfig::isUseByDefault)) { |
|||
configs.values().stream() |
|||
.filter(config -> config.getProviderType() != TwoFaProviderType.BACKUP_CODE) |
|||
.findFirst().ifPresent(config -> config.setUseByDefault(true)); |
|||
updateNeeded = true; |
|||
} |
|||
|
|||
if (updateNeeded) { |
|||
twoFaSettings = saveAccountTwoFaSettings(tenantId, userId, twoFaSettings); |
|||
} |
|||
return twoFaSettings; |
|||
}); |
|||
} |
|||
|
|||
protected AccountTwoFaSettings saveAccountTwoFaSettings(TenantId tenantId, UserId userId, AccountTwoFaSettings settings) { |
|||
UserAuthSettings userAuthSettings = Optional.ofNullable(userAuthSettingsDao.findByUserId(userId)) |
|||
.orElseGet(() -> { |
|||
UserAuthSettings newUserAuthSettings = new UserAuthSettings(); |
|||
newUserAuthSettings.setUserId(userId); |
|||
return newUserAuthSettings; |
|||
}); |
|||
userAuthSettings.setTwoFaSettings(settings); |
|||
settings.getConfigs().values().forEach(accountConfig -> accountConfig.setSerializeHiddenFields(true)); |
|||
userAuthSettingsDao.save(tenantId, userAuthSettings); |
|||
settings.getConfigs().values().forEach(accountConfig -> accountConfig.setSerializeHiddenFields(false)); |
|||
return settings; |
|||
} |
|||
|
|||
|
|||
@Override |
|||
public Optional<TwoFaAccountConfig> getTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaProviderType providerType) { |
|||
return getAccountTwoFaSettings(tenantId, userId) |
|||
.map(AccountTwoFaSettings::getConfigs) |
|||
.flatMap(configs -> Optional.ofNullable(configs.get(providerType))); |
|||
} |
|||
|
|||
@Override |
|||
public AccountTwoFaSettings saveTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaAccountConfig accountConfig) { |
|||
getTwoFaProviderConfig(tenantId, accountConfig.getProviderType()) |
|||
.orElseThrow(() -> new IllegalArgumentException("2FA provider is not configured")); |
|||
|
|||
AccountTwoFaSettings settings = getAccountTwoFaSettings(tenantId, userId).orElseGet(() -> { |
|||
AccountTwoFaSettings newSettings = new AccountTwoFaSettings(); |
|||
newSettings.setConfigs(new LinkedHashMap<>()); |
|||
return newSettings; |
|||
}); |
|||
Map<TwoFaProviderType, TwoFaAccountConfig> configs = settings.getConfigs(); |
|||
if (configs.isEmpty() && accountConfig.getProviderType() == TwoFaProviderType.BACKUP_CODE) { |
|||
throw new IllegalArgumentException("To use 2FA backup codes you first need to configure at least one provider"); |
|||
} |
|||
if (accountConfig.isUseByDefault()) { |
|||
configs.values().forEach(config -> config.setUseByDefault(false)); |
|||
} |
|||
configs.put(accountConfig.getProviderType(), accountConfig); |
|||
if (configs.values().stream().noneMatch(TwoFaAccountConfig::isUseByDefault)) { |
|||
configs.values().stream().findFirst().ifPresent(config -> config.setUseByDefault(true)); |
|||
} |
|||
return saveAccountTwoFaSettings(tenantId, userId, settings); |
|||
} |
|||
|
|||
@Override |
|||
public AccountTwoFaSettings deleteTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaProviderType providerType) { |
|||
AccountTwoFaSettings settings = getAccountTwoFaSettings(tenantId, userId) |
|||
.orElseThrow(() -> new IllegalArgumentException("2FA not configured")); |
|||
settings.getConfigs().remove(providerType); |
|||
if (settings.getConfigs().size() == 1) { |
|||
settings.getConfigs().remove(TwoFaProviderType.BACKUP_CODE); |
|||
} |
|||
if (!settings.getConfigs().isEmpty() && settings.getConfigs().values().stream() |
|||
.noneMatch(TwoFaAccountConfig::isUseByDefault)) { |
|||
settings.getConfigs().values().stream() |
|||
.min(Comparator.comparing(TwoFaAccountConfig::getProviderType)) |
|||
.ifPresent(config -> config.setUseByDefault(true)); |
|||
} |
|||
return saveAccountTwoFaSettings(tenantId, userId, settings); |
|||
} |
|||
|
|||
|
|||
private Optional<TwoFaProviderConfig> getTwoFaProviderConfig(TenantId tenantId, TwoFaProviderType providerType) { |
|||
return getPlatformTwoFaSettings(tenantId, true) |
|||
.flatMap(twoFaSettings -> twoFaSettings.getProviderConfig(providerType)); |
|||
} |
|||
|
|||
@Override |
|||
public Optional<PlatformTwoFaSettings> getPlatformTwoFaSettings(TenantId tenantId, boolean sysadminSettingsAsDefault) { |
|||
return Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, TWO_FACTOR_AUTH_SETTINGS_KEY)) |
|||
.map(adminSettings -> JacksonUtil.treeToValue(adminSettings.getJsonValue(), PlatformTwoFaSettings.class)); |
|||
} |
|||
|
|||
@Override |
|||
public PlatformTwoFaSettings savePlatformTwoFaSettings(TenantId tenantId, PlatformTwoFaSettings twoFactorAuthSettings) throws ThingsboardException { |
|||
ConstraintValidator.validateFields(twoFactorAuthSettings); |
|||
for (TwoFaProviderConfig providerConfig : twoFactorAuthSettings.getProviders()) { |
|||
twoFactorAuthService.checkProvider(tenantId, providerConfig.getProviderType()); |
|||
} |
|||
|
|||
AdminSettings settings = Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) |
|||
.orElseGet(() -> { |
|||
AdminSettings newSettings = new AdminSettings(); |
|||
newSettings.setKey(TWO_FACTOR_AUTH_SETTINGS_KEY); |
|||
return newSettings; |
|||
}); |
|||
settings.setJsonValue(JacksonUtil.valueToTree(twoFactorAuthSettings)); |
|||
adminSettingsService.saveAdminSettings(tenantId, settings); |
|||
return twoFactorAuthSettings; |
|||
} |
|||
|
|||
@Override |
|||
public void deletePlatformTwoFaSettings(TenantId tenantId) { |
|||
Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) |
|||
.ifPresent(adminSettings -> adminSettingsDao.removeById(tenantId, adminSettings.getId().getId())); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,46 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa.config; |
|||
|
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.id.UserId; |
|||
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.AccountTwoFaSettings; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
|
|||
import java.util.Optional; |
|||
|
|||
public interface TwoFaConfigManager { |
|||
|
|||
Optional<AccountTwoFaSettings> getAccountTwoFaSettings(TenantId tenantId, UserId userId); |
|||
|
|||
|
|||
Optional<TwoFaAccountConfig> getTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaProviderType providerType); |
|||
|
|||
AccountTwoFaSettings saveTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaAccountConfig accountConfig); |
|||
|
|||
AccountTwoFaSettings deleteTwoFaAccountConfig(TenantId tenantId, UserId userId, TwoFaProviderType providerType); |
|||
|
|||
|
|||
Optional<PlatformTwoFaSettings> getPlatformTwoFaSettings(TenantId tenantId, boolean sysadminSettingsAsDefault); |
|||
|
|||
PlatformTwoFaSettings savePlatformTwoFaSettings(TenantId tenantId, PlatformTwoFaSettings twoFactorAuthSettings) throws ThingsboardException; |
|||
|
|||
void deletePlatformTwoFaSettings(TenantId tenantId); |
|||
|
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa.provider; |
|||
|
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
public interface TwoFaProvider<C extends TwoFaProviderConfig, A extends TwoFaAccountConfig> { |
|||
|
|||
A generateNewAccountConfig(User user, C providerConfig); |
|||
|
|||
default void prepareVerificationCode(SecurityUser user, C providerConfig, A accountConfig) throws ThingsboardException {} |
|||
|
|||
boolean checkVerificationCode(SecurityUser user, String code, C providerConfig, A accountConfig); |
|||
|
|||
default void check(TenantId tenantId) throws ThingsboardException {}; |
|||
|
|||
|
|||
TwoFaProviderType getType(); |
|||
|
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa.provider.impl; |
|||
|
|||
import org.apache.commons.lang3.RandomStringUtils; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.context.annotation.Lazy; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.common.util.CollectionsUtil; |
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.BackupCodeTwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.BackupCodeTwoFaProviderConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
|||
import org.thingsboard.server.service.security.auth.mfa.provider.TwoFaProvider; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.Set; |
|||
import java.util.stream.Collectors; |
|||
import java.util.stream.Stream; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
public class BackupCodeTwoFaProvider implements TwoFaProvider<BackupCodeTwoFaProviderConfig, BackupCodeTwoFaAccountConfig> { |
|||
|
|||
@Autowired @Lazy |
|||
private TwoFaConfigManager twoFaConfigManager; |
|||
|
|||
@Override |
|||
public BackupCodeTwoFaAccountConfig generateNewAccountConfig(User user, BackupCodeTwoFaProviderConfig providerConfig) { |
|||
BackupCodeTwoFaAccountConfig config = new BackupCodeTwoFaAccountConfig(); |
|||
config.setCodes(generateCodes(providerConfig.getCodesQuantity(), 8)); |
|||
config.setSerializeHiddenFields(true); |
|||
return config; |
|||
} |
|||
|
|||
private static Set<String> generateCodes(int count, int length) { |
|||
return Stream.generate(() -> RandomStringUtils.random(length, "0123456789abcdef")) |
|||
.distinct().limit(count) |
|||
.collect(Collectors.toSet()); |
|||
} |
|||
|
|||
@Override |
|||
public boolean checkVerificationCode(SecurityUser user, String code, BackupCodeTwoFaProviderConfig providerConfig, BackupCodeTwoFaAccountConfig accountConfig) { |
|||
if (CollectionsUtil.contains(accountConfig.getCodes(), code)) { |
|||
accountConfig.getCodes().remove(code); |
|||
twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig); |
|||
return true; |
|||
} else { |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public TwoFaProviderType getType() { |
|||
return TwoFaProviderType.BACKUP_CODE; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,68 @@ |
|||
/** |
|||
* Copyright © 2016-2022 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.auth.mfa.provider.impl; |
|||
|
|||
import org.springframework.cache.CacheManager; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.rule.engine.api.MailService; |
|||
import org.thingsboard.server.common.data.User; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.security.model.mfa.account.EmailTwoFaAccountConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.EmailTwoFaProviderConfig; |
|||
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
public class EmailTwoFaProvider extends OtpBasedTwoFaProvider<EmailTwoFaProviderConfig, EmailTwoFaAccountConfig> { |
|||
|
|||
private final MailService mailService; |
|||
|
|||
protected EmailTwoFaProvider(CacheManager cacheManager, MailService mailService) { |
|||
super(cacheManager); |
|||
this.mailService = mailService; |
|||
} |
|||
|
|||
@Override |
|||
public EmailTwoFaAccountConfig generateNewAccountConfig(User user, EmailTwoFaProviderConfig providerConfig) { |
|||
EmailTwoFaAccountConfig config = new EmailTwoFaAccountConfig(); |
|||
config.setEmail(user.getEmail()); |
|||
return config; |
|||
} |
|||
|
|||
@Override |
|||
public void check(TenantId tenantId) throws ThingsboardException { |
|||
try { |
|||
mailService.testConnection(tenantId); |
|||
} catch (Exception e) { |
|||
throw new ThingsboardException("Mail service is not set up", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
protected void sendVerificationCode(SecurityUser user, String verificationCode, EmailTwoFaProviderConfig providerConfig, EmailTwoFaAccountConfig accountConfig) throws ThingsboardException { |
|||
mailService.sendTwoFaVerificationEmail(accountConfig.getEmail(), verificationCode, providerConfig.getVerificationCodeLifetime()); |
|||
} |
|||
|
|||
@Override |
|||
public TwoFaProviderType getType() { |
|||
return TwoFaProviderType.EMAIL; |
|||
} |
|||
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue