Search in sources :

Example 1 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class DefaultSmsService method sendTestSms.

@Override
public void sendTestSms(TestSmsRequest testSmsRequest) throws ThingsboardException {
    SmsSender testSmsSender;
    try {
        testSmsSender = this.smsSenderFactory.createSmsSender(testSmsRequest.getProviderConfiguration());
    } catch (Exception e) {
        throw handleException(e);
    }
    this.sendSms(testSmsSender, testSmsRequest.getNumberTo(), testSmsRequest.getMessage());
    testSmsSender.destroy();
}
Also used : NestedRuntimeException(org.springframework.core.NestedRuntimeException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) SmsSender(org.thingsboard.rule.engine.api.sms.SmsSender)

Example 2 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class DefaultSystemSecurityService method validateUserCredentials.

@Override
public void validateUserCredentials(TenantId tenantId, UserCredentials userCredentials, String username, String password) throws AuthenticationException {
    if (!encoder.matches(password, userCredentials.getPassword())) {
        int failedLoginAttempts = userService.onUserLoginIncorrectCredentials(tenantId, userCredentials.getUserId());
        SecuritySettings securitySettings = getSecuritySettings(tenantId);
        if (securitySettings.getMaxFailedLoginAttempts() != null && securitySettings.getMaxFailedLoginAttempts() > 0) {
            if (failedLoginAttempts > securitySettings.getMaxFailedLoginAttempts() && userCredentials.isEnabled()) {
                userService.setUserCredentialsEnabled(TenantId.SYS_TENANT_ID, userCredentials.getUserId(), false);
                if (StringUtils.isNoneBlank(securitySettings.getUserLockoutNotificationEmail())) {
                    try {
                        mailService.sendAccountLockoutEmail(username, securitySettings.getUserLockoutNotificationEmail(), securitySettings.getMaxFailedLoginAttempts());
                    } catch (ThingsboardException e) {
                        log.warn("Can't send email regarding user account [{}] lockout to provided email [{}]", username, securitySettings.getUserLockoutNotificationEmail(), e);
                    }
                }
                throw new LockedException("Authentication Failed. Username was locked due to security policy.");
            }
        }
        throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
    }
    if (!userCredentials.isEnabled()) {
        throw new DisabledException("User is not active");
    }
    userService.onUserLoginSuccessful(tenantId, userCredentials.getUserId());
    SecuritySettings securitySettings = self.getSecuritySettings(tenantId);
    if (isPositiveInteger(securitySettings.getPasswordPolicy().getPasswordExpirationPeriodDays())) {
        if ((userCredentials.getCreatedTime() + TimeUnit.DAYS.toMillis(securitySettings.getPasswordPolicy().getPasswordExpirationPeriodDays())) < System.currentTimeMillis()) {
            userCredentials = userService.requestExpiredPasswordReset(tenantId, userCredentials.getId());
            throw new UserPasswordExpiredException("User password expired!", userCredentials.getResetToken());
        }
    }
}
Also used : LockedException(org.springframework.security.authentication.LockedException) DisabledException(org.springframework.security.authentication.DisabledException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserPasswordExpiredException(org.thingsboard.server.service.security.exception.UserPasswordExpiredException) SecuritySettings(org.thingsboard.server.common.data.security.model.SecuritySettings) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 3 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class AlarmController method saveAlarm.

@ApiOperation(value = "Create or update Alarm (saveAlarm)", notes = "Creates or Updates the Alarm. " + "When creating alarm, platform generates Alarm Id as " + UUID_WIKI_LINK + "The newly created Alarm id will be present in the response. Specify existing Alarm id to update the alarm. " + "Referencing non-existing Alarm Id will cause 'Not Found' error. " + "\n\nPlatform also deduplicate the alarms based on the entity id of originator and alarm 'type'. " + "For example, if the user or system component create the alarm with the type 'HighTemperature' for device 'Device A' the new active alarm is created. " + "If the user tries to create 'HighTemperature' alarm for the same device again, the previous alarm will be updated (the 'end_ts' will be set to current timestamp). " + "If the user clears the alarm (see 'Clear Alarm(clearAlarm)'), than new alarm with the same type and same device may be created. " + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm", method = RequestMethod.POST)
@ResponseBody
public Alarm saveAlarm(@ApiParam(value = "A JSON value representing the alarm.") @RequestBody Alarm alarm) throws ThingsboardException {
    try {
        alarm.setTenantId(getCurrentUser().getTenantId());
        checkEntity(alarm.getId(), alarm, Resource.ALARM);
        Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm));
        logEntityAction(savedAlarm.getOriginator(), savedAlarm, getCurrentUser().getCustomerId(), alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED, null);
        sendEntityNotificationMsg(getTenantId(), savedAlarm.getId(), alarm.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
        return savedAlarm;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.ALARM), alarm, null, alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
        throw handleException(e);
    }
}
Also used : Alarm(org.thingsboard.server.common.data.alarm.Alarm) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class AlarmController method getAlarms.

@ApiOperation(value = "Get Alarms (getAlarms)", notes = "Returns a page of alarms for the selected entity. Specifying both parameters 'searchStatus' and 'status' at the same time will cause an error. " + PAGE_DATA_PARAMETERS + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{entityType}/{entityId}", method = RequestMethod.GET)
@ResponseBody
public PageData<AlarmInfo> getAlarms(@ApiParam(value = ENTITY_TYPE_PARAM_DESCRIPTION, required = true, defaultValue = "DEVICE") @PathVariable(ENTITY_TYPE) String strEntityType, @ApiParam(value = ENTITY_ID_PARAM_DESCRIPTION, required = true) @PathVariable(ENTITY_ID) String strEntityId, @ApiParam(value = ALARM_QUERY_SEARCH_STATUS_DESCRIPTION, allowableValues = ALARM_QUERY_SEARCH_STATUS_ALLOWABLE_VALUES) @RequestParam(required = false) String searchStatus, @ApiParam(value = ALARM_QUERY_STATUS_DESCRIPTION, allowableValues = ALARM_QUERY_STATUS_ALLOWABLE_VALUES) @RequestParam(required = false) String status, @ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = ALARM_QUERY_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ALARM_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder, @ApiParam(value = ALARM_QUERY_START_TIME_DESCRIPTION) @RequestParam(required = false) Long startTime, @ApiParam(value = ALARM_QUERY_END_TIME_DESCRIPTION) @RequestParam(required = false) Long endTime, @ApiParam(value = ALARM_QUERY_FETCH_ORIGINATOR_DESCRIPTION) @RequestParam(required = false) Boolean fetchOriginator) throws ThingsboardException {
    checkParameter("EntityId", strEntityId);
    checkParameter("EntityType", strEntityType);
    EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId);
    AlarmSearchStatus alarmSearchStatus = StringUtils.isEmpty(searchStatus) ? null : AlarmSearchStatus.valueOf(searchStatus);
    AlarmStatus alarmStatus = StringUtils.isEmpty(status) ? null : AlarmStatus.valueOf(status);
    if (alarmSearchStatus != null && alarmStatus != null) {
        throw new ThingsboardException("Invalid alarms search query: Both parameters 'searchStatus' " + "and 'status' can't be specified at the same time!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
    }
    checkEntityId(entityId, Operation.READ);
    TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
    try {
        return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(entityId, pageLink, alarmSearchStatus, alarmStatus, fetchOriginator)).get());
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : EntityId(org.thingsboard.server.common.data.id.EntityId) AlarmSearchStatus(org.thingsboard.server.common.data.alarm.AlarmSearchStatus) AlarmStatus(org.thingsboard.server.common.data.alarm.AlarmStatus) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) AlarmQuery(org.thingsboard.server.common.data.alarm.AlarmQuery) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class AlarmController method deleteAlarm.

@ApiOperation(value = "Delete Alarm (deleteAlarm)", notes = "Deletes the Alarm. Referencing non-existing Alarm Id will cause an error." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}", method = RequestMethod.DELETE)
@ResponseBody
public Boolean deleteAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
    checkParameter(ALARM_ID, strAlarmId);
    try {
        AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
        Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);
        List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(getTenantId(), alarm.getOriginator());
        logEntityAction(alarm.getOriginator(), alarm, getCurrentUser().getCustomerId(), ActionType.ALARM_DELETE, null);
        sendAlarmDeleteNotificationMsg(getTenantId(), alarmId, relatedEdgeIds, alarm);
        return alarmService.deleteAlarm(getTenantId(), alarmId);
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : AlarmId(org.thingsboard.server.common.data.id.AlarmId) Alarm(org.thingsboard.server.common.data.alarm.Alarm) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)225 ApiOperation (io.swagger.annotations.ApiOperation)176 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)176 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)172 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)150 IncorrectParameterException (org.thingsboard.server.dao.exception.IncorrectParameterException)102 TenantId (org.thingsboard.server.common.data.id.TenantId)75 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)48 CustomerId (org.thingsboard.server.common.data.id.CustomerId)42 EdgeId (org.thingsboard.server.common.data.id.EdgeId)42 DataValidationException (org.thingsboard.server.dao.exception.DataValidationException)42 Customer (org.thingsboard.server.common.data.Customer)39 IOException (java.io.IOException)38 Edge (org.thingsboard.server.common.data.edge.Edge)34 PageLink (org.thingsboard.server.common.data.page.PageLink)34 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)30 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)25 MessagingException (javax.mail.MessagingException)25 EntityId (org.thingsboard.server.common.data.id.EntityId)25 TimePageLink (org.thingsboard.server.common.data.page.TimePageLink)25