Search in sources :

Example 51 with ThingsboardException

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

the class AuthController method resetPassword.

@ApiOperation(value = "Reset password (resetPassword)", notes = "Checks the password reset token and updates the password. " + "If token is valid, returns the object that contains [JWT](https://jwt.io/) access and refresh tokens. " + "If token is not valid, returns '404 Bad Request'.")
@RequestMapping(value = "/noauth/resetPassword", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JwtTokenPair resetPassword(@ApiParam(value = "Reset password request.") @RequestBody ResetPasswordRequest resetPasswordRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String resetToken = resetPasswordRequest.getResetToken();
        String password = resetPasswordRequest.getPassword();
        UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
        if (userCredentials != null) {
            systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, userCredentials);
            if (passwordEncoder.matches(password, userCredentials.getPassword())) {
                throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
            }
            String encodedPassword = passwordEncoder.encode(password);
            userCredentials.setPassword(encodedPassword);
            userCredentials.setResetToken(null);
            userCredentials = userService.replaceUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
            User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
            SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
            String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
            String loginUrl = String.format("%s/login", baseUrl);
            String email = user.getEmail();
            mailService.sendPasswordWasResetEmail(loginUrl, email);
            eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
            JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
            JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
            return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
        } else {
            throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 52 with ThingsboardException

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

the class AuthController method logLogoutAction.

private void logLogoutAction(HttpServletRequest request) throws ThingsboardException {
    try {
        SecurityUser user = getCurrentUser();
        RestAuthenticationDetails details = new RestAuthenticationDetails(request);
        String clientAddress = details.getClientAddress();
        String browser = "Unknown";
        String os = "Unknown";
        String device = "Unknown";
        if (details.getUserAgent() != null) {
            Client userAgent = details.getUserAgent();
            if (userAgent.userAgent != null) {
                browser = userAgent.userAgent.family;
                if (userAgent.userAgent.major != null) {
                    browser += " " + userAgent.userAgent.major;
                    if (userAgent.userAgent.minor != null) {
                        browser += "." + userAgent.userAgent.minor;
                        if (userAgent.userAgent.patch != null) {
                            browser += "." + userAgent.userAgent.patch;
                        }
                    }
                }
            }
            if (userAgent.os != null) {
                os = userAgent.os.family;
                if (userAgent.os.major != null) {
                    os += " " + userAgent.os.major;
                    if (userAgent.os.minor != null) {
                        os += "." + userAgent.os.minor;
                        if (userAgent.os.patch != null) {
                            os += "." + userAgent.os.patch;
                            if (userAgent.os.patchMinor != null) {
                                os += "." + userAgent.os.patchMinor;
                            }
                        }
                    }
                }
            }
            if (userAgent.device != null) {
                device = userAgent.device.family;
            }
        }
        auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), null, ActionType.LOGOUT, null, clientAddress, browser, os, device);
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) RestAuthenticationDetails(org.thingsboard.server.service.security.auth.rest.RestAuthenticationDetails) Client(ua_parser.Client) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException)

Example 53 with ThingsboardException

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

the class AuthController method requestResetPasswordByEmail.

@ApiOperation(value = "Request reset password email (requestResetPasswordByEmail)", notes = "Request to send the reset password email if the user with specified email address is present in the database. " + "Always return '200 OK' status for security purposes.")
@RequestMapping(value = "/noauth/resetPasswordByEmail", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void requestResetPasswordByEmail(@ApiParam(value = "The JSON object representing the reset password email request.") @RequestBody ResetPasswordEmailRequest resetPasswordByEmailRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String email = resetPasswordByEmailRequest.getEmail();
        UserCredentials userCredentials = userService.requestPasswordReset(TenantId.SYS_TENANT_ID, email);
        User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
        String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
        String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl, userCredentials.getResetToken());
        mailService.sendResetPasswordEmailAsync(resetUrl, email);
    } catch (Exception e) {
        log.warn("Error occurred: {}", e.getMessage());
    }
}
Also used : User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 54 with ThingsboardException

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

the class CustomerController method getCustomers.

@ApiOperation(value = "Get Tenant Customers (getCustomers)", notes = "Returns a page of customers owned by tenant. " + PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customers", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<Customer> getCustomers(@ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = CUSTOMER_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = CUSTOMER_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder) throws ThingsboardException {
    try {
        PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
        TenantId tenantId = getCurrentUser().getTenantId();
        return checkNotNull(customerService.findCustomersByTenantId(tenantId, pageLink));
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) PageLink(org.thingsboard.server.common.data.page.PageLink) 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 55 with ThingsboardException

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

the class CustomerController method saveCustomer.

@ApiOperation(value = "Create or update Customer (saveCustomer)", notes = "Creates or Updates the Customer. When creating customer, platform generates Customer Id as " + UUID_WIKI_LINK + "The newly created Customer Id will be present in the response. " + "Specify existing Customer Id to update the Customer. " + "Referencing non-existing Customer Id will cause 'Not Found' error." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer", method = RequestMethod.POST)
@ResponseBody
public Customer saveCustomer(@ApiParam(value = "A JSON value representing the customer.") @RequestBody Customer customer) throws ThingsboardException {
    try {
        customer.setTenantId(getCurrentUser().getTenantId());
        checkEntity(customer.getId(), customer, Resource.CUSTOMER);
        Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer));
        logEntityAction(savedCustomer.getId(), savedCustomer, savedCustomer.getId(), customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED, null);
        if (customer.getId() != null) {
            sendEntityNotificationMsg(savedCustomer.getTenantId(), savedCustomer.getId(), EdgeEventActionType.UPDATED);
        }
        return savedCustomer;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.CUSTOMER), customer, null, customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
        throw handleException(e);
    }
}
Also used : Customer(org.thingsboard.server.common.data.Customer) 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