Search in sources :

Example 56 with CustomerId

use of org.thingsboard.server.common.data.id.CustomerId in project thingsboard by thingsboard.

the class AssetController method getAssetsByIds.

@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/assets", params = { "assetIds" }, method = RequestMethod.GET)
@ResponseBody
public List<Asset> getAssetsByIds(@RequestParam("assetIds") String[] strAssetIds) throws ThingsboardException {
    checkArrayParameter("assetIds", strAssetIds);
    try {
        SecurityUser user = getCurrentUser();
        TenantId tenantId = user.getTenantId();
        CustomerId customerId = user.getCustomerId();
        List<AssetId> assetIds = new ArrayList<>();
        for (String strAssetId : strAssetIds) {
            assetIds.add(new AssetId(toUUID(strAssetId)));
        }
        ListenableFuture<List<Asset>> assets;
        if (customerId == null || customerId.isNullUid()) {
            assets = assetService.findAssetsByTenantIdAndIdsAsync(tenantId, assetIds);
        } else {
            assets = assetService.findAssetsByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, assetIds);
        }
        return checkNotNull(assets.get());
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) CustomerId(org.thingsboard.server.common.data.id.CustomerId) AssetId(org.thingsboard.server.common.data.id.AssetId) ThingsboardException(org.thingsboard.server.exception.ThingsboardException) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 57 with CustomerId

use of org.thingsboard.server.common.data.id.CustomerId in project thingsboard by thingsboard.

the class DatabaseHelper method upgradeTo40_assignDashboards.

public static void upgradeTo40_assignDashboards(Path dashboardsDump, DashboardService dashboardService, boolean sql) throws Exception {
    JavaType assignedCustomersType = objectMapper.getTypeFactory().constructCollectionType(HashSet.class, ShortCustomerInfo.class);
    try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(dashboardsDump), CSV_DUMP_FORMAT.withFirstRecordAsHeader())) {
        csvParser.forEach(record -> {
            String customerIdString = record.get(CUSTOMER_ID);
            String assignedCustomersString = record.get(ASSIGNED_CUSTOMERS);
            DashboardId dashboardId = new DashboardId(toUUID(record.get(ID), sql));
            List<CustomerId> customerIds = new ArrayList<>();
            if (!StringUtils.isEmpty(assignedCustomersString)) {
                try {
                    Set<ShortCustomerInfo> assignedCustomers = objectMapper.readValue(assignedCustomersString, assignedCustomersType);
                    assignedCustomers.forEach((customerInfo) -> {
                        CustomerId customerId = customerInfo.getCustomerId();
                        if (!customerId.isNullUid()) {
                            customerIds.add(customerId);
                        }
                    });
                } catch (IOException e) {
                    log.error("Unable to parse assigned customers field", e);
                }
            }
            if (!StringUtils.isEmpty(customerIdString)) {
                CustomerId customerId = new CustomerId(toUUID(customerIdString, sql));
                if (!customerId.isNullUid()) {
                    customerIds.add(customerId);
                }
            }
            for (CustomerId customerId : customerIds) {
                dashboardService.assignDashboardToCustomer(dashboardId, customerId);
            }
        });
    }
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) ShortCustomerInfo(org.thingsboard.server.common.data.ShortCustomerInfo) CSVParser(org.apache.commons.csv.CSVParser) DashboardId(org.thingsboard.server.common.data.id.DashboardId) CustomerId(org.thingsboard.server.common.data.id.CustomerId) IOException(java.io.IOException)

Example 58 with CustomerId

use of org.thingsboard.server.common.data.id.CustomerId in project thingsboard by thingsboard.

the class JwtTokenFactory method parseAccessJwtToken.

public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("JWT Token doesn't have any scopes");
    }
    SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
    securityUser.setEmail(subject);
    securityUser.setAuthority(Authority.parse(scopes.get(0)));
    securityUser.setFirstName(claims.get(FIRST_NAME, String.class));
    securityUser.setLastName(claims.get(LAST_NAME, String.class));
    securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    securityUser.setUserPrincipal(principal);
    String tenantId = claims.get(TENANT_ID, String.class);
    if (tenantId != null) {
        securityUser.setTenantId(new TenantId(UUID.fromString(tenantId)));
    }
    String customerId = claims.get(CUSTOMER_ID, String.class);
    if (customerId != null) {
        securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId)));
    }
    return securityUser;
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) Claims(io.jsonwebtoken.Claims) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserId(org.thingsboard.server.common.data.id.UserId) CustomerId(org.thingsboard.server.common.data.id.CustomerId) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 59 with CustomerId

use of org.thingsboard.server.common.data.id.CustomerId in project thingsboard by thingsboard.

the class BaseUserControllerTest method testFindCustomerUsersByEmail.

@Test
public void testFindCustomerUsersByEmail() throws Exception {
    loginSysAdmin();
    Tenant tenant = new Tenant();
    tenant.setTitle("My tenant");
    Tenant savedTenant = doPost("/api/tenant", tenant, Tenant.class);
    Assert.assertNotNull(savedTenant);
    TenantId tenantId = savedTenant.getId();
    User tenantAdmin = new User();
    tenantAdmin.setAuthority(Authority.TENANT_ADMIN);
    tenantAdmin.setTenantId(tenantId);
    tenantAdmin.setEmail("tenant2@thingsboard.org");
    tenantAdmin.setFirstName("Joe");
    tenantAdmin.setLastName("Downs");
    tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1");
    Customer customer = new Customer();
    customer.setTitle("My customer");
    Customer savedCustomer = doPost("/api/customer", customer, Customer.class);
    CustomerId customerId = savedCustomer.getId();
    String email1 = "testEmail1";
    List<User> customerUsersEmail1 = new ArrayList<>();
    for (int i = 0; i < 74; i++) {
        User user = new User();
        user.setAuthority(Authority.CUSTOMER_USER);
        user.setCustomerId(customerId);
        String suffix = RandomStringUtils.randomAlphanumeric((int) (5 + Math.random() * 10));
        String email = email1 + suffix + "@thingsboard.org";
        email = i % 2 == 0 ? email.toLowerCase() : email.toUpperCase();
        user.setEmail(email);
        customerUsersEmail1.add(doPost("/api/user", user, User.class));
    }
    String email2 = "testEmail2";
    List<User> customerUsersEmail2 = new ArrayList<>();
    for (int i = 0; i < 92; i++) {
        User user = new User();
        user.setAuthority(Authority.CUSTOMER_USER);
        user.setCustomerId(customerId);
        String suffix = RandomStringUtils.randomAlphanumeric((int) (5 + Math.random() * 10));
        String email = email2 + suffix + "@thingsboard.org";
        email = i % 2 == 0 ? email.toLowerCase() : email.toUpperCase();
        user.setEmail(email);
        customerUsersEmail2.add(doPost("/api/user", user, User.class));
    }
    List<User> loadedCustomerUsersEmail1 = new ArrayList<>();
    TextPageLink pageLink = new TextPageLink(33, email1);
    TextPageData<User> pageData = null;
    do {
        pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/users?", new TypeReference<TextPageData<User>>() {
        }, pageLink);
        loadedCustomerUsersEmail1.addAll(pageData.getData());
        if (pageData.hasNext()) {
            pageLink = pageData.getNextPageLink();
        }
    } while (pageData.hasNext());
    Collections.sort(customerUsersEmail1, idComparator);
    Collections.sort(loadedCustomerUsersEmail1, idComparator);
    Assert.assertEquals(customerUsersEmail1, loadedCustomerUsersEmail1);
    List<User> loadedCustomerUsersEmail2 = new ArrayList<>();
    pageLink = new TextPageLink(16, email2);
    do {
        pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/users?", new TypeReference<TextPageData<User>>() {
        }, pageLink);
        loadedCustomerUsersEmail2.addAll(pageData.getData());
        if (pageData.hasNext()) {
            pageLink = pageData.getNextPageLink();
        }
    } while (pageData.hasNext());
    Collections.sort(customerUsersEmail2, idComparator);
    Collections.sort(loadedCustomerUsersEmail2, idComparator);
    Assert.assertEquals(customerUsersEmail2, loadedCustomerUsersEmail2);
    for (User user : loadedCustomerUsersEmail1) {
        doDelete("/api/user/" + user.getId().getId().toString()).andExpect(status().isOk());
    }
    pageLink = new TextPageLink(4, email1);
    pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/users?", new TypeReference<TextPageData<User>>() {
    }, pageLink);
    Assert.assertFalse(pageData.hasNext());
    Assert.assertEquals(0, pageData.getData().size());
    for (User user : loadedCustomerUsersEmail2) {
        doDelete("/api/user/" + user.getId().getId().toString()).andExpect(status().isOk());
    }
    pageLink = new TextPageLink(4, email2);
    pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/users?", new TypeReference<TextPageData<User>>() {
    }, pageLink);
    Assert.assertFalse(pageData.hasNext());
    Assert.assertEquals(0, pageData.getData().size());
    doDelete("/api/customer/" + customerId.getId().toString()).andExpect(status().isOk());
    loginSysAdmin();
    doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk());
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) Tenant(org.thingsboard.server.common.data.Tenant) User(org.thingsboard.server.common.data.User) TextPageLink(org.thingsboard.server.common.data.page.TextPageLink) Customer(org.thingsboard.server.common.data.Customer) ArrayList(java.util.ArrayList) CustomerId(org.thingsboard.server.common.data.id.CustomerId) Matchers.containsString(org.hamcrest.Matchers.containsString) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.Test)

Aggregations

CustomerId (org.thingsboard.server.common.data.id.CustomerId)59 TenantId (org.thingsboard.server.common.data.id.TenantId)30 Customer (org.thingsboard.server.common.data.Customer)24 ArrayList (java.util.ArrayList)22 Test (org.junit.Test)22 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)21 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)18 ThingsboardException (org.thingsboard.server.exception.ThingsboardException)17 IncorrectParameterException (org.thingsboard.server.dao.exception.IncorrectParameterException)12 Asset (org.thingsboard.server.common.data.asset.Asset)11 User (org.thingsboard.server.common.data.User)10 TypeReference (com.fasterxml.jackson.core.type.TypeReference)9 UserId (org.thingsboard.server.common.data.id.UserId)9 Device (org.thingsboard.server.common.data.Device)8 Tenant (org.thingsboard.server.common.data.Tenant)7 DashboardId (org.thingsboard.server.common.data.id.DashboardId)6 TimePageLink (org.thingsboard.server.common.data.page.TimePageLink)6 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)6 List (java.util.List)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4