From e111c1dda8c945ecd09bf505d6f217d4a397237f Mon Sep 17 00:00:00 2001 From: Kaveesha Date: Tue, 1 Jun 2021 10:49:33 +0530 Subject: [PATCH 1/4] Update DM_DEVICE_INFO table --- .../src/test/resources/sql/h2.sql | 2 +- .../src/test/resources/sql-files/h2.sql | 2 +- .../src/test/resources/sql/CreateH2TestDB.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/h2.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/mssql.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/mysql.sql | 4 ++-- .../src/main/resources/dbscripts/cdm/oracle.sql | 4 ++-- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index a380bf5204..63af00f07f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -398,7 +398,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sql-files/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sql-files/h2.sql index eedbcd875a..7d7c1ece9c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sql-files/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/sql-files/h2.sql @@ -400,7 +400,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index e53054a6a0..d830a6387e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -452,7 +452,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) @@ -607,4 +607,4 @@ DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID; --- END OF DASHBOARD RELATED VIEWS -- \ No newline at end of file +-- END OF DASHBOARD RELATED VIEWS -- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 0fb5fc7c42..bda86bc93b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -424,7 +424,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) @@ -722,4 +722,4 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( DM_DEVICE_EVENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); --- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- \ No newline at end of file +-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index c70277074a..247d796c52 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -474,7 +474,7 @@ CREATE TABLE DM_DEVICE_INFO ( DEVICE_ID INTEGER NULL, ENROLMENT_ID INTEGER NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC), INDEX DM_DEVICE_INFO_DEVICE_ENROLLMENT_idx (ENROLMENT_ID ASC), @@ -714,4 +714,4 @@ CREATE TABLE DM_GEOFENCE ( PRIMARY KEY (ID) ); --- END OF DM_GEOFENCE TABLE-- \ No newline at end of file +-- END OF DM_GEOFENCE TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index 6ba30303b8..cc9e8f1273 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -491,7 +491,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC), INDEX DM_DEVICE_INFO_DEVICE_ENROLLMENT_idx (ENROLMENT_ID ASC), @@ -786,4 +786,4 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( DM_DEVICE_EVENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB; --- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- \ No newline at end of file +-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index de19680e81..007a7008f0 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -779,7 +779,7 @@ CREATE TABLE DM_DEVICE_INFO ( DEVICE_ID NUMBER(10) NOT NULL, ENROLMENT_ID NUMBER(10) NOT NULL, KEY_FIELD VARCHAR2(45) NULL, - VALUE_FIELD VARCHAR2(1000) NULL, + VALUE_FIELD VARCHAR2(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) @@ -1083,4 +1083,4 @@ CREATE TABLE DM_GEOFENCE ( CONSTRAINT PK_DM_GEOFENCE PRIMARY KEY (ID) ); --- END OF DM_GEOFENCE TABLE-- \ No newline at end of file +-- END OF DM_GEOFENCE TABLE-- From d84f642b558f5c633807274ec85ec808c0560dab Mon Sep 17 00:00:00 2001 From: Kaveesha Date: Wed, 7 Jul 2021 00:55:27 +0530 Subject: [PATCH 2/4] Add API for get app subscribed device list from a subscription group --- .../common/services/SubscriptionManager.java | 12 ++ .../mgt/core/dao/SubscriptionDAO.java | 12 ++ .../GenericSubscriptionDAOImpl.java | 41 +++++ .../core/impl/SubscriptionManagerImpl.java | 46 ++++++ .../services/SubscriptionManagementAPI.java | 97 +++++++++++ .../impl/SubscriptionManagementAPIImpl.java | 69 ++++++++ .../carbon/device/mgt/core/dao/DeviceDAO.java | 23 +++ .../core/dao/impl/AbstractDeviceDAOImpl.java | 150 ++++++++++++++++++ .../dao/impl/device/OracleDeviceDAOImpl.java | 73 +++++++++ .../impl/device/SQLServerDeviceDAOImpl.java | 74 +++++++++ .../DeviceManagementProviderService.java | 10 ++ .../DeviceManagementProviderServiceImpl.java | 35 ++++ 12 files changed, 642 insertions(+) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java index a535ffd389..600da94b4f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java @@ -161,4 +161,16 @@ public interface SubscriptionManager { */ PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action) throws ApplicationManagementException; + + /*** + * This method is responsible to provide application subscription devices data for given application release UUID. + * @param request PaginationRequest object holding the data for pagination + * @param appUUID UUID of the application release. + * @param subType subscription type of the application(eg: GROUP, USER, ...) + * @param subTypeName subscription type name of the application (Name of the group, Name of the user, ...). + * @return {@link PaginationResult} pagination result of the category details. + * @throws {@link ApplicationManagementException} Exception of the application management + */ + PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType, + String subTypeName) throws ApplicationManagementException; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java index ce8780a6a2..3ff0d95945 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java @@ -228,4 +228,16 @@ public interface SubscriptionDAO { throws ApplicationManagementDAOException; int getSubscribedGroupCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException; + + /** + * This method is used to get the details of subscribed groups + * + * @param tenantId id of the current tenant + * @param appReleaseId id of the application release.. + * @param subtype application subscribed type. + * @return subscribedDevices - list of app subscribed devices under the subtype. + * @throws {@link ApplicationManagementDAOException} if connections establishment fails. + */ + List getAppSubscribedDevicesForGroups(int appReleaseId, String subtype, int tenantId) + throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java index c2fd7f240a..4e6c6623f1 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java @@ -1271,4 +1271,45 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc throw new ApplicationManagementDAOException(msg, e); } } + + @Override + public List getAppSubscribedDevicesForGroups(int appReleaseId, String subType, int tenantId) + throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to get already subscribed devices for " + + "given app release id."); + } + // retrieve all device list by action triggered type and app release id + try { + Connection conn = this.getDBConnection(); + List subscribedGroupDevices = new ArrayList<>(); + String sql = "SELECT " + + "AP_DEVICE_SUBSCRIPTION.DM_DEVICE_ID AS DEVICES " + + "FROM AP_DEVICE_SUBSCRIPTION " + + "WHERE " + + "AP_APP_RELEASE_ID = ? AND ACTION_TRIGGERED_FROM=? AND " + + "UNSUBSCRIBED=FALSE AND TENANT_ID = ?"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setInt(1, appReleaseId); + ps.setString(2, subType.toLowerCase());; + ps.setInt(3, tenantId); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + subscribedGroupDevices.add(rs.getInt("DEVICES")); + } + } + return subscribedGroupDevices; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to get already " + + "subscribed groups for given app release id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while getting subscribed devices for given " + + "app release id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index 5aa222ce13..8219dbb4e7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -1427,4 +1427,50 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ConnectionManagerUtil.closeDBConnection(); } } + + @Override + public PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType, + String subTypeName) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + DeviceManagementProviderService deviceManagementProviderService = HelperUtil + .getDeviceManagementProviderService(); + try { + ConnectionManagerUtil.openDBConnection(); + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(appUUID, tenantId); + int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId(); + List subscriptionDeviceList = new ArrayList<>(); + //todo update the API for other subscription types + if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { + subscriptionDeviceList = subscriptionDAO + .getAppSubscribedDevicesForGroups(applicationReleaseId, subType, tenantId); + } else { + String msg = "Found invalid sub type: " + subType; + log.error(msg); + throw new NotFoundException(msg); + } + if (subscriptionDeviceList.isEmpty()) { + PaginationResult paginationResult = new PaginationResult(); + paginationResult.setData(subscriptionDeviceList); + paginationResult.setRecordsFiltered(0); + paginationResult.setRecordsTotal(0); + return paginationResult; + } + return deviceManagementProviderService.getDevicesDetails(request, subscriptionDeviceList, subTypeName); + } catch (DeviceManagementException e) { + String msg = "service error occurred while getting device data from the device management service."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred when get application release devices data for application release UUID: " + + appUUID; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurred while getting category details that given application id"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java index be55b64639..2c8811358d 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java @@ -446,4 +446,101 @@ public interface SubscriptionManagementAPI { defaultValue = "5") @QueryParam("limit") int limit ); + + @GET + @Path("/{uuid}/{subType}/{subTypeName}/devices") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get device details in categories that have a given application install", + notes = "This will get the category's device details that have a given application install, if exists", + tags = "Subscription Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:subscription:uninstall") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved device details.", + response = List.class, + responseContainer = "List"), + @ApiResponse( + code = 404, + message = "Not Found. \n No Devices found which has application " + + "release of UUID.", + response = ErrorResponse.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n Found invalid payload with the request.", + response = List.class), + @ApiResponse( + code = 403, + message = "Forbidden. \n Don't have permission to get the details.", + response = List.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while getting data", + response = ErrorResponse.class) + }) + Response getAppInstalledDevicesOnCategories( + @ApiParam( + name="uuid", + value="uuid of the application release.", + required = true) + @PathParam("uuid") String uuid, + @ApiParam( + name="subType", + value="Subscription type of the application release.", + required = true) + @PathParam("subType") String subType, + @ApiParam( + name="subTypeName", + value="Subscription type name of the application release.", + required = true) + @PathParam("subTypeName") String subTypeName, + @ApiParam( + name = "offset", + value = "The starting pagination index for the complete list of qualified items.", + defaultValue = "0") + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Provide how many device details you require from the starting " + + "pagination index/offset.", + defaultValue = "5") + @QueryParam("limit") int limit, + @ApiParam( + name = "name", + value = "The device name. For example, Nexus devices can have names, such as shamu, bullhead or angler.", + required = false) + @Size(max = 45) + String name, + @ApiParam( + name = "user", + value = "The username of the owner of the device.", + required = false) + @QueryParam("user") + String user, + @ApiParam( + name = "ownership", + allowableValues = "BYOD, COPE", + value = "Provide the ownership status of the device. The following values can be assigned:\n" + + "- BYOD: Bring Your Own Device\n" + + "- COPE: Corporate-Owned, Personally-Enabled", + required = false) + @QueryParam("ownership") + @Size(max = 45) + String ownership, + @ApiParam( + name = "status", + value = "Provide the device status details, such as active or inactive.") + @QueryParam("status") List status + ); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java index acf9662cb9..a6324c8fdb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java @@ -400,4 +400,73 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } + + @GET + @Consumes("application/json") + @Produces("application/json") + @Path("/{uuid}/{subType}/{subTypeName}/devices") + public Response getAppInstalledDevicesOnCategories( + @PathParam("uuid") String uuid, + @PathParam("subType") String subType, + @PathParam("subTypeName") String subTypeName, + @DefaultValue("0") + @QueryParam("offset") int offset, + @DefaultValue("5") + @QueryParam("limit") int limit, + @QueryParam("name") String name, + @QueryParam("user") String user, + @QueryParam("ownership") String ownership, + @QueryParam("status") List status) { + try { + SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); + PaginationRequest request = new PaginationRequest(offset, limit); + + if (StringUtils.isNotBlank(name)) { + request.setDeviceName(name); + } + if (StringUtils.isNotBlank(user)) { + request.setOwner(user); + } + if (StringUtils.isNotBlank(ownership)) { + RequestValidationUtil.validateOwnershipType(ownership); + request.setOwnership(ownership); + } + if (status != null && !status.isEmpty()) { + boolean isStatusEmpty = true; + for (String statusString : status) { + if (StringUtils.isNotBlank(statusString)) { + isStatusEmpty = false; + break; + } + } + if (!isStatusEmpty) { + RequestValidationUtil.validateStatus(status); + request.setStatusList(status); + } + } + + //todo need to update the API for other subscription types + if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { + PaginationResult subscribedCategoryDetails = subscriptionManager + .getAppInstalledSubscribeDevices(request, uuid, subType, subTypeName); + DeviceList devices = new DeviceList(); + devices.setList((List) subscribedCategoryDetails.getData()); + devices.setCount(subscribedCategoryDetails.getRecordsTotal()); + return Response.status(Response.Status.OK).entity(devices).build(); + } else { + String msg = "Found invalid sub type: " + subType; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + } catch (NotFoundException e) { + String msg = "Application with application release UUID: " + uuid + " is not found"; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while getting application with the application " + + "release uuid: " + uuid; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 77b9d76c5c..9796dd40f4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -758,4 +758,27 @@ public interface DeviceDAO { String version) throws DeviceManagementDAOException; int getFunctioningDevicesInSystem() throws DeviceManagementDAOException; + + /** + * This method is used to get the details of devices when give deviceIDs list and group name. + * @param deviceIds device ids of the devices. + * @param tenantId Id of the current tenant. + * @param request paginated request object. + * @param groupName group name. + * @return devices - device details list + * @throws DeviceManagementDAOException if connections establishment fails. + */ + List getGroupedDevicesDetails(PaginationRequest request, List deviceIds, String groupName, + int tenantId) throws DeviceManagementDAOException; + + /** + * @param deviceIds device ids of the devices. + * @param tenantId tenant id + * @param request paginated request object. + * @param groupName group name. + * @return number of device count under the group name. + * @throws DeviceManagementDAOException if error occurred while processing the SQL statement. + */ + int getGroupedDevicesCount(PaginationRequest request, List deviceIds, String groupName, int tenantId) + throws DeviceManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index bf387744e2..dd175d493a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -3022,4 +3022,154 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { throw new DeviceManagementDAOException(msg, e); } } + + @Override + public List getGroupedDevicesDetails(PaginationRequest request, List deviceIds, String groupName, + int tenantId) throws DeviceManagementDAOException { + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + List status = request.getStatusList(); + String name = request.getDeviceName(); + String user = request.getOwner(); + String ownership = request.getOwnership(); + try { + List devices = new ArrayList<>(); + if (deviceIds.isEmpty()) { + return devices; + } + Connection conn = this.getConnection(); + int index = 1; + StringJoiner joiner = new StringJoiner(",", + "SELECT " + + "DM_DEVICE.ID AS DEVICE_ID, " + + "DM_DEVICE.NAME AS DEVICE_NAME, " + + "DM_DEVICE.DESCRIPTION AS DESCRIPTION, " + + "DM_DEVICE.DEVICE_TYPE_ID, " + + "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "device_types.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE_GROUP_MAP " + + "INNER JOIN DM_DEVICE ON " + + "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID " + + "INNER JOIN DM_GROUP ON " + + "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID " + + "INNER JOIN DM_ENROLMENT e ON " + + "DM_DEVICE.ID = e.DEVICE_ID AND " + + "DM_DEVICE.TENANT_ID = e.TENANT_ID " + + "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON " + + "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID " + + "WHERE DM_DEVICE.ID IN (", + ") AND DM_DEVICE.TENANT_ID = ?"); + + deviceIds.stream().map(ignored -> "?").forEach(joiner::add); + String query = joiner.toString(); + if (StringUtils.isNotBlank(groupName)) { + query += " AND DM_GROUP.GROUP_NAME = ?"; + } + if (StringUtils.isNotBlank(name)) { + query += " AND DM_DEVICE.NAME LIKE ?"; + } + if (StringUtils.isNotBlank(user)) { + query += " AND e.OWNER = ?"; + } + if (StringUtils.isNotBlank(ownership)) { + query += " AND e.OWNERSHIP = ?"; + } + if (status != null && !status.isEmpty()) { + query += buildStatusQuery(status); + } + + query += "LIMIT ? OFFSET ?"; + + try (PreparedStatement ps = conn.prepareStatement(query)) { + for (Integer deviceId : deviceIds) { + ps.setInt(index++, deviceId); + } + ps.setInt(index++, tenantId); + if (StringUtils.isNotBlank(groupName)) { + ps.setString(index++, groupName); + } + if (StringUtils.isNotBlank(name)) { + ps.setString(index++, name); + } + if (StringUtils.isNotBlank(user)) { + ps.setString(index++, user); + } + if (StringUtils.isNotBlank(ownership)) { + ps.setString(index++, ownership); + } + if (status != null && !status.isEmpty()) { + for (String deviceStatus : status) { + ps.setString(index++, deviceStatus); + } + } + ps.setInt(index++, limitValue); + ps.setInt(index, offsetValue); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDevice(rs)); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all registered devices " + + "according to device ids and the limit area."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public int getGroupedDevicesCount(PaginationRequest request, List deviceIds, String groupName, + int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + if (deviceIds.isEmpty()) { + return 0; + } + int index = 1; + StringJoiner joiner = new StringJoiner(",", + "SELECT " + + "COUNT(DM_DEVICE_GROUP_MAP.DEVICE_ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE_GROUP_MAP " + + "INNER JOIN DM_GROUP ON " + + "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID " + + "WHERE DM_DEVICE_GROUP_MAP.DEVICE_ID IN (", + ") AND DM_GROUP.TENANT_ID = ?"); + deviceIds.stream().map(ignored -> "?").forEach(joiner::add); + String query = joiner.toString(); + if (StringUtils.isNotBlank(groupName)) { + query += " AND DM_GROUP.GROUP_NAME = ?"; + } + + try (PreparedStatement ps = conn.prepareStatement(query)) { + for (Integer deviceId : deviceIds) { + ps.setInt(index++, deviceId); + } + ps.setInt(index++, tenantId); + if (StringUtils.isNotBlank(groupName)) { + ps.setString(index, groupName); + } + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return rs.getInt("DEVICE_COUNT"); + } + return 0; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all registered devices " + + "according to device ids and the limit area."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 4393a4546e..f2a91cae45 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -1194,6 +1194,79 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getGroupedDevicesDetails(PaginationRequest request, List deviceIds, String groupName, + int tenantId) throws DeviceManagementDAOException { + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + try { + List devices = new ArrayList<>(); + if (deviceIds.isEmpty()) { + return devices; + } + Connection conn = this.getConnection(); + int index = 1; + StringJoiner joiner = new StringJoiner(",", + "SELECT " + + "DM_DEVICE.ID AS DEVICE_ID, " + + "DM_DEVICE.NAME AS DEVICE_NAME, " + + "DM_DEVICE.DESCRIPTION AS DESCRIPTION, " + + "DM_DEVICE.DEVICE_TYPE_ID, " + + "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "device_types.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE_GROUP_MAP " + + "INNER JOIN DM_DEVICE ON " + + "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID " + + "INNER JOIN DM_GROUP ON " + + "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID " + + "INNER JOIN DM_ENROLMENT e ON " + + "DM_DEVICE.ID = e.DEVICE_ID AND " + + "DM_DEVICE.TENANT_ID = e.TENANT_ID " + + "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON " + + "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID " + + "WHERE DM_DEVICE.ID IN (", + ") AND DM_DEVICE.TENANT_ID = ?"); + + deviceIds.stream().map(ignored -> "?").forEach(joiner::add); + String query = joiner.toString(); + if (StringUtils.isNotBlank(groupName)) { + query += " AND DM_GROUP.GROUP_NAME = ?"; + } + query += " ORDER BY DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement ps = conn.prepareStatement(query)) { + for (Integer deviceId : deviceIds) { + ps.setInt(index++, deviceId); + } + ps.setInt(index++, tenantId); + if (StringUtils.isNotBlank(groupName)) { + ps.setString(index++, groupName); + } + ps.setInt(index++, offsetValue); + ps.setInt(index, limitValue); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDevice(rs)); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all registered devices " + + "according to device ids and the limit area."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 8911beca49..ae4b25b431 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Count; @@ -1132,6 +1133,79 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getGroupedDevicesDetails(PaginationRequest request, List deviceIds, String groupName, + int tenantId) throws DeviceManagementDAOException { + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + try { + List devices = new ArrayList<>(); + if (deviceIds.isEmpty()) { + return devices; + } + Connection conn = this.getConnection(); + int index = 1; + StringJoiner joiner = new StringJoiner(",", + "SELECT " + + "DM_DEVICE.ID AS DEVICE_ID, " + + "DM_DEVICE.NAME AS DEVICE_NAME, " + + "DM_DEVICE.DESCRIPTION AS DESCRIPTION, " + + "DM_DEVICE.DEVICE_TYPE_ID, " + + "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "device_types.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE_GROUP_MAP " + + "INNER JOIN DM_DEVICE ON " + + "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID " + + "INNER JOIN DM_GROUP ON " + + "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID " + + "INNER JOIN DM_ENROLMENT e ON " + + "DM_DEVICE.ID = e.DEVICE_ID AND " + + "DM_DEVICE.TENANT_ID = e.TENANT_ID " + + "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON " + + "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID " + + "WHERE DM_DEVICE.ID IN (", + ") AND DM_DEVICE.TENANT_ID = ?"); + + deviceIds.stream().map(ignored -> "?").forEach(joiner::add); + String query = joiner.toString(); + if (StringUtils.isNotBlank(groupName)) { + query += " AND DM_GROUP.GROUP_NAME = ?"; + } + query += " ORDER BY DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement ps = conn.prepareStatement(query)) { + for (Integer deviceId : deviceIds) { + ps.setInt(index++, deviceId); + } + ps.setInt(index++, tenantId); + if (StringUtils.isNotBlank(groupName)) { + ps.setString(index++, groupName); + } + ps.setInt(index++, offsetValue); + ps.setInt(index, limitValue); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDevice(rs)); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all registered devices " + + "according to device ids and the limit area."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + //TODO: Override for MSSQL /* @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 6ff661568c..6265384aad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -992,4 +992,14 @@ public interface DeviceManagementProviderService { License getLicenseConfig (String deviceTypeName) throws DeviceManagementException; + /** + * This method retrieves a list of devices details. + * @param request paginated request object. + * @param devicesIds devices ids list + * @param groupName name of the group + * @return {@link PaginationResult} + * @throws DeviceManagementException if any service level or DAO level error occurs. + */ + PaginationResult getDevicesDetails(PaginationRequest request, List devicesIds, String groupName) + throws DeviceManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 1f4bac57d1..70cbee4731 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -4429,4 +4429,39 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return deviceManagementService.getLicenseConfig(); } + @Override + public PaginationResult getDevicesDetails(PaginationRequest request, List devicesIds, + String groupName) throws DeviceManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + if (log.isDebugEnabled()) { + log.debug("Getting all devices details for device ids: " + devicesIds); + } + PaginationResult paginationResult = new PaginationResult(); + List subscribedDeviceDetails; + try { + DeviceManagementDAOFactory.openConnection(); + subscribedDeviceDetails = deviceDAO.getGroupedDevicesDetails(request, devicesIds, groupName, tenantId); + if (subscribedDeviceDetails.isEmpty()) { + paginationResult.setData(new ArrayList<>()); + paginationResult.setRecordsFiltered(0); + paginationResult.setRecordsTotal(0); + return paginationResult; + } + int count = deviceDAO.getGroupedDevicesCount(request, devicesIds, groupName, tenantId); + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving device list for device ids " + devicesIds; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails)); + return paginationResult; + } } From 510a90a59f5efbf3618d83a69d1b25c174462b92 Mon Sep 17 00:00:00 2001 From: Amalka Subasinghe Date: Fri, 9 Jul 2021 14:46:28 +0530 Subject: [PATCH 3/4] bug fixing authorize flow --- .../cache/APIResourcePermissionCacheKey.java | 64 -------------- ...APIResourcePermissionCacheManagerImpl.java | 84 ------------------- .../core/internal/UserRoleCreateObserver.java | 42 ++++++++-- .../mgt/APIResourcePermissions.java} | 23 +++-- .../mgt/PermissionManagerServiceImpl.java | 14 +--- .../mgt/core/util/DeviceManagerUtil.java | 16 ---- .../framework/WebappAuthenticationValve.java | 4 +- .../authorizer/PermissionAuthorizer.java | 4 + 8 files changed, 60 insertions(+), 191 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheKey.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/APIResourcePermissionCacheManagerImpl.java rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/{cache/APIResourcePermissionCacheManager.java => permission/mgt/APIResourcePermissions.java} (50%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheKey.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheKey.java deleted file mode 100644 index 2db061a6d0..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheKey.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.core.cache; - -import java.util.Objects; - -public class APIResourcePermissionCacheKey { - - private String context; - private volatile int hashCode; - - public APIResourcePermissionCacheKey(String context) { - this.context = context; - } - - - public String getContext() { - return context; - } - - public void setContext(String context) { - this.context = context; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!APIResourcePermissionCacheKey.class.isAssignableFrom(obj.getClass())) { - return false; - } - final APIResourcePermissionCacheKey other = (APIResourcePermissionCacheKey) obj; - String thisId = this.context; - String otherId = other.context; - if (!thisId.equals(otherId)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - if (hashCode == 0) { - hashCode = Objects.hash(context); - } - return hashCode; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/APIResourcePermissionCacheManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/APIResourcePermissionCacheManagerImpl.java deleted file mode 100644 index 3b08a8d8b2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/APIResourcePermissionCacheManagerImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.core.cache.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; -import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey; -import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheManager; -import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; - -import javax.cache.Cache; -import java.util.List; - -public class APIResourcePermissionCacheManagerImpl implements APIResourcePermissionCacheManager { - - - private static final Log log = LogFactory.getLog(APIResourcePermissionCacheManagerImpl.class); - - private static APIResourcePermissionCacheManagerImpl apiResourceCacgeManager; - - private APIResourcePermissionCacheManagerImpl() { - } - - public static APIResourcePermissionCacheManagerImpl getInstance() { - if (apiResourceCacgeManager == null) { - synchronized (APIResourcePermissionCacheManagerImpl.class) { - if (apiResourceCacgeManager == null) { - apiResourceCacgeManager = new APIResourcePermissionCacheManagerImpl(); - } - } - } - return apiResourceCacgeManager; - } - - - @Override - public void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List permissions) { - Cache> lCache = DeviceManagerUtil.getAPIResourcePermissionCache(); - if (lCache != null) { - if (lCache.containsKey(cacheKey)) { - this.updateAPIResourcePermissionInCache(cacheKey, permissions); - } else { - lCache.put(cacheKey, permissions); - } - } - } - - @Override - public void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List permissions) { - - Cache> lCache = DeviceManagerUtil.getAPIResourcePermissionCache(); - if (lCache != null) { - if (lCache.containsKey(cacheKey)) { - lCache.replace(cacheKey, permissions); - } - } - - } - - @Override - public List getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey) { - Cache> lCache = DeviceManagerUtil.getAPIResourcePermissionCache(); - if (lCache != null) { - return lCache.get(cacheKey); - } - return null; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/UserRoleCreateObserver.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/UserRoleCreateObserver.java index ce16866524..5fb9509629 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/UserRoleCreateObserver.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/UserRoleCreateObserver.java @@ -21,6 +21,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; @@ -35,20 +37,42 @@ public class UserRoleCreateObserver implements ServerStartupObserver { @Override public void completedServerStartup() { String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - String tenantAdminName = "admin"; try { UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager(); - userStoreManager.addRole( - DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, - new String[]{tenantAdminName}, - DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN); - userStoreManager.addRole( - DeviceManagementConstants.User.DEFAULT_DEVICE_USER, - new String[]{tenantAdminName}, - DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER); + String tenantAdminName = + DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( + MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminUserName(); + AuthorizationManager authorizationManager = DeviceManagementDataHolder.getInstance().getRealmService() + .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getAuthorizationManager(); + + if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN)) { + userStoreManager.addRole( + DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + null, + DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN); + } else { + for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN) { + authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + permission.getResourceId(), permission.getAction()); + } + } + if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER)) { + userStoreManager.addRole( + DeviceManagementConstants.User.DEFAULT_DEVICE_USER, + null, + DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER); + } else { + for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER) { + authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER, + permission.getResourceId(), permission.getAction()); + } + } + userStoreManager.updateRoleListOfUser(tenantAdminName, null, + new String[] {DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + DeviceManagementConstants.User.DEFAULT_DEVICE_USER}); if (log.isDebugEnabled()) { log.debug("Device management roles: " + DeviceManagementConstants.User.DEFAULT_DEVICE_USER + ", " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/APIResourcePermissions.java similarity index 50% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheManager.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/APIResourcePermissions.java index 4dac439cc4..703d9f6eda 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/APIResourcePermissionCacheManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/APIResourcePermissions.java @@ -4,9 +4,9 @@ * WSO2 Inc. licenses this file to you 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 + * you may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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 @@ -15,17 +15,26 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.core.cache; +package org.wso2.carbon.device.mgt.core.permission.mgt; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; +import java.util.HashMap; import java.util.List; +import java.util.Map; -public interface APIResourcePermissionCacheManager { +public class APIResourcePermissions { + private Map> apiResourcePermissions; - void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List permissions); + public APIResourcePermissions() { + apiResourcePermissions = new HashMap<>(); + } - void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List permissions); + public void addPermissionList(String context, List permissions){ + apiResourcePermissions.put(context, permissions); + } - List getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey); + public List getPermissions(String context) { + return apiResourcePermissions.get(context); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java index c2591a1df6..8a222ea3f1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java @@ -18,16 +18,11 @@ package org.wso2.carbon.device.mgt.core.permission.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; -import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey; -import org.wso2.carbon.device.mgt.core.cache.impl.APIResourcePermissionCacheManagerImpl; import java.util.List; -import java.util.Properties; /** * This class will add, update custom permissions defined in permission.xml in webapps and it will @@ -36,7 +31,7 @@ import java.util.Properties; public class PermissionManagerServiceImpl implements PermissionManagerService { private static PermissionManagerServiceImpl registryBasedPermissionManager; - + private static APIResourcePermissions apiResourcePermissions; private PermissionManagerServiceImpl() { } @@ -45,6 +40,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { synchronized (PermissionManagerServiceImpl.class) { if (registryBasedPermissionManager == null) { registryBasedPermissionManager = new PermissionManagerServiceImpl(); + apiResourcePermissions = new APIResourcePermissions(); } } } @@ -57,8 +53,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { for (Permission permission : permissions) { PermissionUtils.putPermission(permission); } - APIResourcePermissionCacheManagerImpl.getInstance().addAPIResourcePermissionToCache( - new APIResourcePermissionCacheKey(context), permissions); + apiResourcePermissions.addPermissionList(context, permissions); } catch (PermissionManagementException e) { return false; } @@ -67,7 +62,6 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { @Override public List getPermission(String context) throws PermissionManagementException { - return APIResourcePermissionCacheManagerImpl.getInstance().getAPIResourceRermissionFromCache( - new APIResourcePermissionCacheKey(context)); + return apiResourcePermissions.getPermissions(context); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index f83e19c62f..d13a0bebe0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -76,7 +76,6 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementExcept import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; @@ -724,21 +723,6 @@ public final class DeviceManagerUtil { return deviceCache; } - public static Cache> getAPIResourcePermissionCache() { - CacheManager manager = getCacheManager(); - Cache> apiResourcePermissionCache = null; - if(!isAPIResourcePermissionCacheInitialized) { - initializeAPIResourcePermissionCache(); - } - if (manager != null) { - apiResourcePermissionCache = manager.getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE); - } else { - apiResourcePermissionCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER) - .getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE); - } - return apiResourcePermissionCache; - } - /** * Get geofence cache object * @return {@link Cache} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 6547c48f35..9e73d08ffb 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -21,6 +21,7 @@ package org.wso2.carbon.webapp.authenticator.framework; import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.owasp.encoder.Encode; @@ -194,7 +195,8 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { ctx = tokenizer.nextToken(); } } - return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx)); + return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx) + || "oauth2".equalsIgnoreCase(ctx)); } private boolean isNonSecuredEndPoint(Request request) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index dd3e8cceff..eb09e815df 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -46,6 +46,10 @@ public class PermissionAuthorizer { return WebappAuthenticator.Status.CONTINUE; } + if (requestUri.endsWith("/")) { + requestUri = requestUri.substring(0, requestUri.length() - 1); + } + PermissionManagerService registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance(); List matchingPermissions = null; From fc9a9ca2107915a2bb2a6f2614d3f5ffa7c54f77 Mon Sep 17 00:00:00 2001 From: Amalka Subasinghe Date: Tue, 13 Jul 2021 09:28:30 +0530 Subject: [PATCH 4/4] fixed permission issues --- .../mgt/jaxrs/service/api/DeviceManagementService.java | 7 +++++++ .../carbon/device/mgt/core/DeviceManagementConstants.java | 1 + 2 files changed, 8 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index de81d28918..eb1d952491 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -180,6 +180,13 @@ import java.util.List; roles = {"Internal/devicemgt-user"}, permissions = {"/device-mgt/devices/change-status"} ), + @Scope( + name = "Enroll Device", + description = "Register a device", + key = "perm:device:enroll", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/devices/owning-device/add"} + ), } ) @Path("/devices") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 1d0f581451..e9cfa13398 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -167,6 +167,7 @@ public final class DeviceManagementConstants { new Permission("/permission/admin/device-mgt/devices/enroll", "ui.execute"), new Permission("/permission/admin/device-mgt/devices/disenroll", "ui.execute"), new Permission("/permission/admin/device-mgt/devices/owning-device/view", "ui.execute"), + new Permission("/permission/admin/device-mgt/metadata", "ui.execute"), new Permission("/permission/admin/manage/portal", "ui.execute") };