From 4590de6a76d60eb5d90e5ea5cdbca1dda23c0ace Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Wed, 4 Nov 2015 15:12:23 +0530 Subject: [PATCH 1/9] chenge the formatter --- .../backend-oauth-authenticator/pom.xml | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml index f626686a0d..cb64fb694d 100644 --- a/components/identity-extensions/backend-oauth-authenticator/pom.xml +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -26,46 +26,46 @@ 4.0.0 bundle - WSO2 Carbon - OAuth Back End Authenticator + WSO2 Carbon - OAuth Back End Authenticator org.wso2.carbon.identity.authenticator.backend.oauth org.wso2.carbon org.wso2.carbon.utils - + org.wso2.carbon.identity org.wso2.carbon.identity.base - + org.wso2.carbon.identity org.wso2.carbon.identity.core - + org.wso2.carbon org.wso2.carbon.core - + org.wso2.carbon org.wso2.carbon.logging - + org.wso2.carbon.identity org.wso2.carbon.identity.application.authentication.framework - + org.wso2.carbon org.wso2.carbon.core.services - + org.wso2.carbon.identity org.wso2.carbon.identity.oauth - + org.wso2.carbon.identity org.wso2.carbon.identity.application.common - + org.wso2.carbon.identity org.wso2.carbon.identity.oauth.stub @@ -89,14 +89,15 @@ ${pom.artifactId} ${carbon.device.mgt.version} Identity backend Bundle - org.wso2.carbon.identity.authenticator.backend.oauth.internal.OauthAuthenticatorServiceComponent + + org.wso2.carbon.identity.authenticator.backend.oauth.internal.OauthAuthenticatorServiceComponent + org.wso2.org.wso2.carbon.identity.authenticator.backend.oauth.internal org.wso2.carbon.identity.authenticator.backend.oauth.* - From d7c942f39526754b5901656ca6f1750e1c3d9da5 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Tue, 10 Nov 2015 14:51:10 +0530 Subject: [PATCH 2/9] Enable ownership editing on the policy --- .../carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 9cc11640d6..593c4a88fc 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -280,14 +280,15 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ?, OWNERSHIP_TYPE = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (Policy policy : policies) { stmt.setInt(1, policy.getPriorityId()); stmt.setInt(2, 1); - stmt.setInt(3, policy.getId()); - stmt.setInt(4, tenantId); + stmt.setString(3, policy.getOwnershipType()); + stmt.setInt(4, policy.getId()); + stmt.setInt(5, tenantId); stmt.addBatch(); } stmt.executeBatch(); From 4faa740c9d288894a758b5e4c58c18a2b170ab19 Mon Sep 17 00:00:00 2001 From: inosh-perera Date: Tue, 10 Nov 2015 17:36:30 +0530 Subject: [PATCH 3/9] Fixing JIRA EMM-947 - only the registered device types are returned to UI --- .../DeviceManagementPluginRepository.java | 4 ++ .../DeviceManagementProviderServiceImpl.java | 45 ++++++++++++------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index ae94f52811..58263e2b25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -65,6 +65,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis return providers.get(type); } + public Map getAllDeviceManagementServices() { + return providers; + } + @Override public void notifyObserver() { synchronized (providers) { 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 8eed2efc67..3caaf9585a 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 @@ -47,6 +47,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Map; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -635,21 +636,35 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return device; } - @Override - public List getAvailableDeviceTypes() throws DeviceManagementException { - List deviceTypes; - try { - DeviceManagementDAOFactory.openConnection(); - deviceTypes = deviceDAO.getDeviceTypes(); - } catch (DeviceManagementDAOException e) { - throw new DeviceManagementException("Error occurred while obtaining the device types.", e); - } catch (SQLException e) { - throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - return deviceTypes; - } + @Override + public List getAvailableDeviceTypes() throws DeviceManagementException { + List deviceTypesInDatabase; + List deviceTypesResponse = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + deviceTypesInDatabase = deviceDAO.getDeviceTypes(); + Map registeredTypes = pluginRepository.getAllDeviceManagementServices(); + DeviceType deviceType; + + if (registeredTypes != null && deviceTypesInDatabase != null) { + for (int x = 0; x < deviceTypesInDatabase.size(); x++) { + if (registeredTypes.get(deviceTypesInDatabase.get(x).getName()) != null) { + deviceType = new DeviceType(); + deviceType.setId(deviceTypesInDatabase.get(x).getId()); + deviceType.setName(deviceTypesInDatabase.get(x).getName()); + deviceTypesResponse.add(deviceType); + } + } + } + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the device types.", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return deviceTypesResponse; + } @Override public boolean updateDeviceInfo(DeviceIdentifier deviceId, Device device) throws DeviceManagementException { From 2fd0101ed30ca77b2817a97f753911d529c50dec Mon Sep 17 00:00:00 2001 From: geethkokila Date: Tue, 10 Nov 2015 18:08:57 +0530 Subject: [PATCH 4/9] Fixing the identity version and kernel version --- pom.xml | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 18edc0b79c..e52c77573e 100644 --- a/pom.xml +++ b/pom.xml @@ -501,6 +501,10 @@ org.wso2.carbon org.wso2.carbon.user.api + + xerces.wso2 + xercesImpl + @@ -597,6 +601,10 @@ commons-collections.wso2 commons-collections + + xerces.wso2 + xercesImpl + @@ -825,6 +833,10 @@ javax.servlet servlet-api + + xerces + xercesImpl + @@ -1427,7 +1439,7 @@ 6.1.1 - 4.4.1 + 4.4.2 1.5.4 1.3 @@ -1471,7 +1483,7 @@ 5.0.2 - 4.5.0-m1 + 4.5.0 4.4.8 From 026a7c187a7e49f8e52a7598b9244edf1f04f60f Mon Sep 17 00:00:00 2001 From: harshanl Date: Tue, 10 Nov 2015 18:17:34 +0530 Subject: [PATCH 5/9] Fixed EMM-945, EMM-910, EMM-911, EMM-870 --- .../DeviceAccessAuthorizationException.java | 61 ++ .../DeviceAccessAuthorizationService.java | 79 ++ .../DeviceAuthorizationResult.java | 58 ++ .../TenantConfigurationManagementService.java | 5 +- .../mgt/NotificationManagementService.java | 48 +- .../operation/mgt/OperationManager.java | 27 +- .../mgt/PermissionManagerService.java | 4 +- .../ApplicationManagementProviderService.java | 4 +- .../DeviceAccessAuthorizationServiceImpl.java | 262 +++++++ .../WebAppDeploymentLifecycleListener.java | 3 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 14 +- .../core/dao/DeviceManagementDAOFactory.java | 4 +- .../{EnrolmentDAO.java => EnrollmentDAO.java} | 11 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 36 +- ...entDAOImpl.java => EnrollmentDAOImpl.java} | 88 ++- .../dao/util/DeviceManagementDAOUtil.java | 197 +++-- .../internal/DeviceManagementDataHolder.java | 10 + .../DeviceManagementServiceComponent.java | 8 + .../operation/mgt/OperationManagerImpl.java | 699 ++++++++++-------- .../mgt/dao/impl/OperationDAOImpl.java | 2 +- .../DeviceManagementProviderService.java | 21 + .../DeviceManagementProviderServiceImpl.java | 115 ++- .../core/dao/EnrolmentPersistenceTests.java | 6 +- .../DynamicClientRegistrationServiceImpl.java | 6 +- ...ynamicClientWebAppRegistrationManager.java | 3 +- .../DynamicClientWebAppRegistrationUtil.java | 4 + .../PermissionBasedScopeValidator.java | 4 +- .../PolicyEnforcementDelegatorImpl.java | 1 + .../policy/mgt/core/PolicyDAOTestCase.java | 4 +- .../mgt/core/PolicyEvaluationTestCase.java | 10 +- .../framework/WebappAuthenticationValve.java | 38 +- .../authenticator/OAuthAuthenticator.java | 2 +- .../src/main/resources/dbscripts/cdm/h2.sql | 6 +- .../main/resources/dbscripts/cdm/mssql.sql | 6 +- .../main/resources/dbscripts/cdm/mysql.sql | 6 +- .../main/resources/dbscripts/cdm/oracle.sql | 6 +- .../resources/dbscripts/cdm/postgresql.sql | 6 +- 37 files changed, 1356 insertions(+), 508 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAuthorizationResult.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/{EnrolmentDAO.java => EnrollmentDAO.java} (75%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/{EnrolmentDAOImpl.java => EnrollmentDAOImpl.java} (72%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationException.java new file mode 100644 index 0000000000..93033d61ec --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationException.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2015, 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.common.authorization; + +/** + * Custom exception class which wraps exceptions occurred inside DeviceAccessAuthorization service. + */ +public class DeviceAccessAuthorizationException extends Exception { + + private static final long serialVersionUID = -3151279331929070297L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public DeviceAccessAuthorizationException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceAccessAuthorizationException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceAccessAuthorizationException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceAccessAuthorizationException() { + super(); + } + + public DeviceAccessAuthorizationException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java new file mode 100644 index 0000000000..5c6b9b4b4b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAccessAuthorizationService.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015, 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.common.authorization; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.util.List; + + +/** + * This represents the contract of DeviceAccessAuthorization service which will be used to check the authorization when + * accessing the device information and performing MDM operations on devices. + */ +public interface DeviceAccessAuthorizationService { + + /** + * This method will check whether the currently logged-in user has the access to the device identified by the given + * DeviceIdentifier. + * + * @param deviceIdentifier - DeviceIdentifier of the device to be checked. + * @return Boolean authorization result. + * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. + */ + boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException; + + /** + * This method will check whether the currently logged-in user has the access to the devices identified by the given + * DeviceIdentifier list. + * + * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. + * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & + * unauthorized devices. + * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. + */ + DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers) throws + DeviceAccessAuthorizationException; + + /** + * This method will check whether the given user has the access to the device identified by the given + * DeviceIdentifier. + * + * @param deviceIdentifier - DeviceIdentifier of the device to be checked. + * @param username - Username of the user to be checked for authorization. + * @return Boolean authorization result. + * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. + */ + boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) throws + DeviceAccessAuthorizationException; + + /** + * This method will check whether the given user has the access to the devices identified by the given + * DeviceIdentifier list. + * + * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. + * @param username - Username of the user to be checked for authorization. + * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & + * unauthorized devices. + * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. + */ + DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username) throws + DeviceAccessAuthorizationException; + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAuthorizationResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAuthorizationResult.java new file mode 100644 index 0000000000..18284a8592 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/authorization/DeviceAuthorizationResult.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, 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.common.authorization; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a DeviceAuthorizationResult including a list of authorized devices and a list of unauthorized devices. + */ +public class DeviceAuthorizationResult { + + private List authorizedDevices = new ArrayList<>(); + private List unauthorizedDevices = new ArrayList<>(); + + public List getAuthorizedDevices() { + return authorizedDevices; + } + + public void setAuthorizedDevices(List authorizedDevices) { + this.authorizedDevices = authorizedDevices; + } + + public void setUnauthorizedDevices( + List unauthorizedDevices) { + this.unauthorizedDevices = unauthorizedDevices; + } + + public void addAuthorizedDevice(DeviceIdentifier deviceIdentifier) { + authorizedDevices.add(deviceIdentifier); + } + + public List getUnauthorizedDevices() { + return unauthorizedDevices; + } + + public void addUnauthorizedDevice(DeviceIdentifier deviceIdentifier) { + unauthorizedDevices.add(deviceIdentifier); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java index 59b9e1c7ae..58e8d60be1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java @@ -31,7 +31,8 @@ public interface TenantConfigurationManagementService { * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the * configuration. */ - public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws ConfigurationManagementException; + boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws + ConfigurationManagementException; /** * Method to retrieve the list of general tenant configurations. @@ -40,6 +41,6 @@ public interface TenantConfigurationManagementService { * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the * operation list. */ - public TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException; + TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java index 730ce6a4de..7cd60536d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -25,12 +25,50 @@ import java.util.List; */ public interface NotificationManagementService { - public boolean addNotification(Notification notification) throws NotificationManagementException; - public boolean updateNotification(Notification notification) throws NotificationManagementException; - public boolean updateNotificationStatus(int notificationId, Notification.Status status) throws + /** + * Method to add a notification to the database. + * + * @param notification - Notification to be added to database. + * @return boolean status of the operation. + * @throws NotificationManagementException if something goes wrong while adding the Notification. + */ + boolean addNotification(Notification notification) throws NotificationManagementException; + + /** + * Method to update a notification in the database. + * + * @param notification - Notification to be updated in the database. + * @return boolean status of the operation. + * @throws NotificationManagementException if something goes wrong while updating the Notification. + */ + boolean updateNotification(Notification notification) throws NotificationManagementException; + + /** + * Method to update the notification status of a Notification in the database. + * + * @param notificationId - Notification id of the notification to be updated. + * @param status - New notification status. + * @return boolean status of the operation. + * @throws NotificationManagementException if something goes wrong while updating the Notification. + */ + boolean updateNotificationStatus(int notificationId, Notification.Status status) throws NotificationManagementException; - public List getAllNotifications() throws NotificationManagementException; - public List getNotificationsByStatus(Notification.Status status) throws + + /** + * Method to fetch all the notifications in the database. + * + * @return List of all Notifications in the database. + * @throws NotificationManagementException + */ + List getAllNotifications() throws NotificationManagementException; + + /** + * + * @param status - Status of the notifications to be fetched from database. + * @return A list of notifications matching the given status. + * @throws NotificationManagementException if something goes wrong while fetching the Notification. + */ + List getNotificationsByStatus(Notification.Status status) throws NotificationManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index e953e2f1bd..3a0916b49f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -34,41 +34,42 @@ public interface OperationManager { * @param operation Operation to be added * @param devices List of DeviceIdentifiers to execute the operation * @throws OperationManagementException If some unusual behaviour is observed while adding the - * operation + * operation */ - public int addOperation(Operation operation, List devices) throws OperationManagementException; + int addOperation(Operation operation, List devices) throws OperationManagementException; /** * Method to retrieve the list of all operations to a device. * * @param deviceId DeviceIdentifier of the device * @throws OperationManagementException If some unusual behaviour is observed while fetching the - * operation list. + * operation list. */ - public List getOperations(DeviceIdentifier deviceId) throws OperationManagementException; + List getOperations(DeviceIdentifier deviceId) throws OperationManagementException; /** * Method to retrieve the list of available operations to a device. * * @param deviceId DeviceIdentifier of the device * @throws OperationManagementException If some unusual behaviour is observed while fetching the - * operation list. + * operation list. */ - public List getPendingOperations( + List getPendingOperations( DeviceIdentifier deviceId) throws OperationManagementException; - public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException; + Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException; - public void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException; + void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException; - public void deleteOperation(int operationId) throws OperationManagementException; + void deleteOperation(int operationId) throws OperationManagementException; - public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) + Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) throws OperationManagementException; - public List getOperationsByDeviceAndStatus(DeviceIdentifier identifier, - Operation.Status status) throws OperationManagementException, DeviceManagementException; + List getOperationsByDeviceAndStatus(DeviceIdentifier identifier, + Operation.Status status) + throws OperationManagementException, DeviceManagementException; - public Operation getOperation(int operationId) throws OperationManagementException; + Operation getOperation(int operationId) throws OperationManagementException; } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java index f0d1519edd..30b771565d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java @@ -33,7 +33,7 @@ public interface PermissionManagerService { * @throws PermissionManagementException If some unusual behaviour is observed while adding the * permission. */ - public boolean addPermission(Permission permission) throws PermissionManagementException; + boolean addPermission(Permission permission) throws PermissionManagementException; /** * @@ -42,6 +42,6 @@ public interface PermissionManagerService { * @throws PermissionManagementException If some unusual behaviour is observed while fetching the * permission. */ - public Permission getPermission(Properties properties) throws PermissionManagementException; + Permission getPermission(Properties properties) throws PermissionManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderService.java index 085dadac47..e13f0cbfbf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderService.java @@ -24,10 +24,10 @@ import java.util.List; public interface ApplicationManagementProviderService extends ApplicationManager { - public void updateApplicationListInstalledInDevice(DeviceIdentifier deviceIdentifier, + void updateApplicationListInstalledInDevice(DeviceIdentifier deviceIdentifier, List applications) throws ApplicationManagementException; - public List getApplicationListForDevice(DeviceIdentifier deviceIdentifier) + List getApplicationListForDevice(DeviceIdentifier deviceIdentifier) throws ApplicationManagementException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java new file mode 100644 index 0000000000..1595873737 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2015, 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.authorization; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult; +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.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implementation of DeviceAccessAuthorization service. + */ +public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthorizationService { + + private final static String EMM_ADMIN_PERMISSION = "/device-mgt/admin-device-access"; + private static Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceImpl.class); + + public static final class PermissionMethod { + private PermissionMethod() { + throw new AssertionError(); + } + + public static final String READ = "read"; + public static final String WRITE = "write"; + public static final String DELETE = "delete"; + public static final String ACTION = "action"; + public static final String UI_EXECUTE = "ui.execute"; + } + + public DeviceAccessAuthorizationServiceImpl() { + try { + this.addAdminPermissionToRegistry(); + } catch (PermissionManagementException e) { + log.error("Unable to add the emm-admin permission to the registry.", e); + } + } + + @Override + public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException { + boolean status; + String username = this.getUserName(); + int tenantId = this.getTenantId(); + if (username == null || username.isEmpty()) { + return false; + } + try { + //Check for admin users. If the user is an admin user we authorize the access to that device. + status = isAdminUser(username, tenantId); + } catch (UserStoreException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + + deviceIdentifier.getId() + " for the user : " + username, e); + } + //Check for device ownership. If the user is the owner of the device we allow the access. + if (!status) { + try { + Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevice(deviceIdentifier); + EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) { + status = true; + } + } catch (DeviceManagementException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + + deviceIdentifier.getId() + " for the user : " + username, e); + } + } + return status; + } + + @Override + public DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers) throws + DeviceAccessAuthorizationException { + boolean status; + DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult(); + String username = this.getUserName(); + int tenantId = this.getTenantId(); + if (username == null || username.isEmpty()) { + return deviceAuthorizationResult; + } + try { + //Check for admin users. If the user is an admin user we authorize the access to that device. + status = isAdminUser(username, tenantId); + } catch (UserStoreException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " + + username, e); + } + //Check for device ownership. If the user is the owner of the device we allow the access. + if (!status) { + try { + //Get the list of devices of the user + List devicesOfUser = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevicesOfUser(username); + //Convert device-list to a Map + Map ownershipData = this.getOwnershipOfDevices(devicesOfUser); + for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { + if (ownershipData.containsKey(deviceIdentifier.getId())) { + deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier); + } else { + deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier); + } + } + } catch (DeviceManagementException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " + + username, e); + } + } else { + deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers); + } + return deviceAuthorizationResult; + } + + @Override + public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) + throws DeviceAccessAuthorizationException { + boolean status; + int tenantId = this.getTenantId(); + if (username == null || username.isEmpty()) { + return false; + } + try { + //Check for admin users. If the user is an admin user we authorize the access to that device. + status = isAdminUser(username, tenantId); + } catch (UserStoreException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + + deviceIdentifier.getId() + " for the user : " + username, e); + } + //Check for device ownership. If the user is the owner of the device we allow the access. + if (!status) { + try { + Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevice(deviceIdentifier); + EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) { + status = true; + } + } catch (DeviceManagementException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + + deviceIdentifier.getId() + " for the user : " + username, e); + } + } + return status; + } + + @Override + public DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username) + throws DeviceAccessAuthorizationException { + boolean status; + int tenantId = this.getTenantId(); + DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult(); + if (username == null || username.isEmpty()) { + return null; + } + try { + //Check for admin users. If the user is an admin user we authorize the access to that device. + status = isAdminUser(username, tenantId); + } catch (UserStoreException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " + + username, e); + } + //Check for device ownership. If the user is the owner of the device we allow the access. + if (!status) { + try { + Device device; + EnrolmentInfo enrolmentInfo; + for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + getDevice(deviceIdentifier); + enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) { + deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier); + } else { + deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier); + } + } + } catch (DeviceManagementException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " + + username, e); + } + } else { + deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers); + } + return deviceAuthorizationResult; + } + + private boolean isAdminUser(String username, int tenantId) throws UserStoreException { + UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + if (userRealm != null && userRealm.getAuthorizationManager() != null) { + return userRealm.getAuthorizationManager() + .isUserAuthorized(username, PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION), + PermissionMethod.UI_EXECUTE); + } + return false; + } + + private String getUserName() { + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + String tenantDomain = MultitenantUtils.getTenantDomain(username); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + private int getTenantId() { + return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + } + + private boolean addAdminPermissionToRegistry() throws PermissionManagementException { + Permission permission = new Permission(); + permission.setPath(PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION)); + return PermissionUtils.putPermission(permission); + } + + private Map getOwnershipOfDevices(List devices) { + Map ownershipData = new HashMap<>(); + EnrolmentInfo enrolmentInfo; + String owner; + for (Device device : devices) { + enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo != null) { + owner = enrolmentInfo.getOwner(); + if (owner != null && !owner.isEmpty()) { + ownershipData.put(device.getDeviceIdentifier(), owner); + } + } + } + return ownershipData; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java index 1d004f7e09..eacc7a84c8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java @@ -69,7 +69,8 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener { // update the permission path to absolute permission path permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath())); permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion, - permission.getUrl())); + permission.getUrl()).toLowerCase()); + permission.setMethod(permission.getMethod().toUpperCase()); PermissionManagerServiceImpl.getInstance().addPermission(permission); } } 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 f3d878393f..dceabe6825 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 @@ -76,7 +76,7 @@ public interface DeviceDAO { int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; /** - * This method is used to retrieve a device of a given device-identifier. + * This method is used to retrieve a device of a given device-identifier and tenant-id. * * @param deviceIdentifier device id. * @param tenantId tenant id. @@ -85,6 +85,18 @@ public interface DeviceDAO { */ Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve a device of a given device-identifier, enrollment status and tenant-id. + * + * @param deviceIdentifier device id. + * @param status enrollment status. + * @param tenantId tenant id. + * @return returns the device object. + * @throws DeviceManagementDAOException + */ + Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status,int tenantId) + throws DeviceManagementDAOException; + /** * * @param deviceIdentifier device id. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 173688058c..e72efc1d79 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -110,8 +110,8 @@ public class DeviceManagementDAOFactory { return new DeviceTypeDAOImpl(); } - public static EnrolmentDAO getEnrollmentDAO() { - return new EnrolmentDAOImpl(); + public static EnrollmentDAO getEnrollmentDAO() { + return new EnrollmentDAOImpl(); } public static ApplicationDAO getApplicationDAO() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java similarity index 75% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java index 1384d677d4..f5c21de39d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java @@ -21,13 +21,17 @@ package org.wso2.carbon.device.mgt.core.dao; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; -public interface EnrolmentDAO { +import java.util.List; + +public interface EnrollmentDAO { int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException; int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException; + int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException; + int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; boolean setStatus(int deviceId, String currentOwner, Status status, @@ -35,6 +39,9 @@ public interface EnrolmentDAO { Status getStatus(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; - EnrolmentInfo getEnrolment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; + EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; + + List getEnrollmentsOfUser(int deviceId, String user, 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 a2e4f4d12c..466b1210c6 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 @@ -122,7 +122,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setInt(4, tenantId); rs = stmt.executeQuery(); if (rs.next()) { - device = DeviceManagementDAOUtil.loadDevice(rs); + device = DeviceManagementDAOUtil.loadMatchingDevice(rs); } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while listing devices for type " + @@ -133,6 +133,40 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return device; } + @Override + public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) throws + DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Device device = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "t.NAME = ? AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? AND e.STATUS = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceIdentifier.getType()); + stmt.setString(2, deviceIdentifier.getId()); + stmt.setInt(3, tenantId); + stmt.setInt(4, tenantId); + stmt.setString(5, status.toString()); + rs = stmt.executeQuery(); + if (rs.next()) { + device = DeviceManagementDAOUtil.loadDevice(rs); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while listing devices for type " + + "'" + deviceIdentifier.getType() + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return device; + } + @Override public HashMap getDevice(DeviceIdentifier deviceIdentifier) throws DeviceManagementDAOException { Connection conn; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrolmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java similarity index 72% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrolmentDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index e4e4f79eec..0e4334b206 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrolmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -21,13 +21,15 @@ package org.wso2.carbon.device.mgt.core.dao.impl; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.EnrolmentDAO; +import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import java.sql.*; +import java.util.ArrayList; import java.util.Date; +import java.util.List; -public class EnrolmentDAOImpl implements EnrolmentDAO { +public class EnrollmentDAOImpl implements EnrollmentDAO { @Override public int addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, @@ -68,11 +70,12 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - int enrolmentId = -1; + int status = -1; try { conn = this.getConnection(); String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " + - "DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; + "DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?" + + " AND ID = ?"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, enrolmentInfo.getOwnership().toString()); stmt.setString(2, enrolmentInfo.getStatus().toString()); @@ -81,13 +84,44 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { stmt.setInt(5, deviceId); stmt.setString(6, enrolmentInfo.getOwner()); stmt.setInt(7, tenantId); + stmt.setInt(8, enrolmentInfo.getId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { - enrolmentId = rs.getInt(1); + status = 1; } - return enrolmentId; + return status; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + int status = -1; + try { + conn = this.getConnection(); + String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " + + "DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?"; + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, enrolmentInfo.getOwnership().toString()); + stmt.setString(2, enrolmentInfo.getStatus().toString()); + stmt.setTimestamp(3, new Timestamp(enrolmentInfo.getDateOfEnrolment())); + stmt.setTimestamp(4, new Timestamp(new Date().getTime())); + stmt.setInt(5, enrolmentInfo.getId()); + stmt.executeUpdate(); + + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + status = 1; + } + return status; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); } finally { @@ -95,13 +129,14 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { } } + @Override public int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - int enrolmentId = -1; + int status = -1; try { conn = this.getConnection(); String sql = "DELETE DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; @@ -113,9 +148,9 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { rs = stmt.getGeneratedKeys(); if (rs.next()) { - enrolmentId = rs.getInt(1); + status = 1; } - return enrolmentId; + return status; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while removing device enrolment", e); } finally { @@ -172,8 +207,8 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { } @Override - public EnrolmentInfo getEnrolment(int deviceId, String currentOwner, - int tenantId) throws DeviceManagementDAOException { + public EnrolmentInfo getEnrollment(int deviceId, String currentOwner, + int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -199,6 +234,36 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { } } + @Override + public List getEnrollmentsOfUser(int deviceId, String user, int tenantId) + throws DeviceManagementDAOException { + List enrolmentInfos = new ArrayList<>(); + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + EnrolmentInfo enrolmentInfo = null; + try { + conn = this.getConnection(); + String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setString(2, user); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + while (rs.next()) { + enrolmentInfo = this.loadEnrolment(rs); + enrolmentInfos.add(enrolmentInfo); + } + return enrolmentInfos; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " + + "information of user '" + user + "' upon device '" + deviceId + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } @@ -210,6 +275,7 @@ public class EnrolmentDAOImpl implements EnrolmentDAO { enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); + enrolmentInfo.setId(rs.getInt("ID")); return enrolmentInfo; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index c7bc50eb2b..de6b63168b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -35,35 +35,37 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.HashMap; import java.util.Hashtable; +import java.util.Map; public final class DeviceManagementDAOUtil { - private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.class); + private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.class); - public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing result set", e); - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing prepared statement", e); - } - } - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing database connection", e); - } - } - } + public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing database connection", e); + } + } + } public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { if (rs != null) { @@ -82,46 +84,46 @@ public final class DeviceManagementDAOUtil { } } - /** - * Get id of the current tenant. - * - * @return tenant id - * @throws DeviceManagementDAOException if an error is observed when getting tenant id - */ - public static int getTenantId() throws DeviceManagementDAOException { - CarbonContext context = CarbonContext.getThreadLocalCarbonContext(); - int tenantId = context.getTenantId(); - if (tenantId != MultitenantConstants.INVALID_TENANT_ID) { - return tenantId; - } - String tenantDomain = context.getTenantDomain(); - if (tenantDomain == null) { - String msg = "Tenant domain is not properly set and thus, is null"; - throw new DeviceManagementDAOException(msg); - } - TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); - try { - tenantId = tenantManager.getTenantId(tenantDomain); - } catch (UserStoreException e) { - String msg = - "Error occurred while retrieving id from the domain of tenant " + tenantDomain; - throw new DeviceManagementDAOException(msg); - } - return tenantId; - } + /** + * Get id of the current tenant. + * + * @return tenant id + * @throws DeviceManagementDAOException if an error is observed when getting tenant id + */ + public static int getTenantId() throws DeviceManagementDAOException { + CarbonContext context = CarbonContext.getThreadLocalCarbonContext(); + int tenantId = context.getTenantId(); + if (tenantId != MultitenantConstants.INVALID_TENANT_ID) { + return tenantId; + } + String tenantDomain = context.getTenantDomain(); + if (tenantDomain == null) { + String msg = "Tenant domain is not properly set and thus, is null"; + throw new DeviceManagementDAOException(msg); + } + TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); + try { + tenantId = tenantManager.getTenantId(tenantDomain); + } catch (UserStoreException e) { + String msg = + "Error occurred while retrieving id from the domain of tenant " + tenantDomain; + throw new DeviceManagementDAOException(msg); + } + return tenantId; + } - public static DataSource lookupDataSource(String dataSourceName, - final Hashtable jndiProperties) { - try { - if (jndiProperties == null || jndiProperties.isEmpty()) { - return (DataSource) InitialContext.doLookup(dataSourceName); - } - final InitialContext context = new InitialContext(jndiProperties); - return (DataSource) context.lookup(dataSourceName); - } catch (Exception e) { - throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); - } - } + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } /* public static Device loadDevice(ResultSet rs) throws SQLException { Device device = new Device(); @@ -144,21 +146,58 @@ public final class DeviceManagementDAOUtil { return enrolmentInfo; } - public static Device loadDevice(ResultSet rs) throws SQLException { - Device device = new Device(); - device.setId(rs.getInt("DEVICE_ID")); - device.setName(rs.getString("DEVICE_NAME")); - device.setDescription(rs.getString("DESCRIPTION")); - device.setType(rs.getString("DEVICE_TYPE")); - device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - device.setEnrolmentInfo(loadEnrolment(rs)); - return device; - } + public static Device loadDevice(ResultSet rs) throws SQLException { + Device device = new Device(); + device.setId(rs.getInt("DEVICE_ID")); + device.setName(rs.getString("DEVICE_NAME")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setType(rs.getString("DEVICE_TYPE")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + device.setEnrolmentInfo(loadEnrolment(rs)); + return device; + } + + //This method will retrieve most appropriate device information when there are multiple device enrollments for + //a single device. We'll give the highest priority to active devices. + public static Device loadMatchingDevice(ResultSet rs) throws SQLException { + Map deviceMap = new HashMap<>(); + Device device = loadDevice(rs); + if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { + return device; + } + while (rs.next()) { + device = loadDevice(rs); + if (EnrolmentInfo.Status.ACTIVE.equals(device.getEnrolmentInfo().getStatus())) { + return device; + } + if (device.getEnrolmentInfo() != null) { + deviceMap.put(device.getEnrolmentInfo().getStatus(), device); + } + } + if (deviceMap.containsKey(EnrolmentInfo.Status.INACTIVE)) { + return deviceMap.get(EnrolmentInfo.Status.INACTIVE); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.UNREACHABLE)) { + return deviceMap.get(EnrolmentInfo.Status.UNREACHABLE); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED)) { + return deviceMap.get(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.CREATED)) { + return deviceMap.get(EnrolmentInfo.Status.CREATED); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.REMOVED)) { + return deviceMap.get(EnrolmentInfo.Status.REMOVED); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.UNCLAIMED)) { + return deviceMap.get(EnrolmentInfo.Status.UNCLAIMED); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.SUSPENDED)) { + return deviceMap.get(EnrolmentInfo.Status.SUSPENDED); + } else if (deviceMap.containsKey(EnrolmentInfo.Status.BLOCKED)) { + return deviceMap.get(EnrolmentInfo.Status.BLOCKED); + } + return device; + } - public static DeviceType loadDeviceType(ResultSet rs) throws SQLException { - DeviceType deviceType = new DeviceType(); - deviceType.setId(rs.getInt("ID")); - deviceType.setName(rs.getString("NAME")); - return deviceType; - } + public static DeviceType loadDeviceType(ResultSet rs) throws SQLException { + DeviceType deviceType = new DeviceType(); + deviceType.setId(rs.getInt("ID")); + deviceType.setName(rs.getString("NAME")); + return deviceType; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index d59962a619..938389a580 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.internal; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; @@ -41,6 +42,7 @@ public class DeviceManagementDataHolder { private AppManagementConfig appManagerConfig; private OperationManager operationManager; private ConfigurationContextService configurationContextService; + private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder(); @@ -143,4 +145,12 @@ public class DeviceManagementDataHolder { this.configurationContextService = configurationContextService; } + public DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { + return deviceAccessAuthorizationService; + } + + public void setDeviceAccessAuthorizationService( + DeviceAccessAuthorizationService deviceAccessAuthorizationService) { + this.deviceAccessAuthorizationService = deviceAccessAuthorizationService; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index ff5723cc22..646ca8b796 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; @@ -36,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderServ import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfigurationManager; +import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; @@ -194,6 +196,12 @@ public class DeviceManagementServiceComponent { = PermissionManagerServiceImpl.getInstance(); bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null); + /* Registering DeviceAccessAuthorization Service */ + DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); + bundleContext.registerService(DeviceAccessAuthorizationService.class.getName(), + deviceAccessAuthorizationService, null); + /* Registering App Management service */ try { AppManagementConfigurationManager.getInstance().initConfig(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 9044720294..7e444c706b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -24,12 +24,14 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -76,44 +78,54 @@ public class OperationManagerImpl implements OperationManager { log.debug("operation:[" + operation.toString() + "]"); for (DeviceIdentifier deviceIdentifier : deviceIds) { log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" + - deviceIdentifier.getType() + "]"); + deviceIdentifier.getType() + "]"); } } try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - List enrolments; - try { - DeviceManagementDAOFactory.openConnection(); - enrolments = deviceDAO.getEnrolmentsByStatus(deviceIds, EnrolmentInfo.Status.ACTIVE, tenantId); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection the data " + - "source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.beginTransaction(); - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = - OperationDAOUtil.convertOperation(operation); - - int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); - - for (EnrolmentInfo enrolmentInfo : enrolments) { - operationMappingDAO.addOperationMapping(operationId, enrolmentInfo.getId()); + List authorizedDeviceList = DeviceManagementDataHolder.getInstance(). + getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds).getAuthorizedDevices(); + if (authorizedDeviceList.size() > 0) { + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + List enrolments; + try { + DeviceManagementDAOFactory.openConnection(); + enrolments = deviceDAO.getEnrolmentsByStatus(deviceIds, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening a connection the data " + + "source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + OperationManagementDAOFactory.beginTransaction(); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = + OperationDAOUtil.convertOperation(operation); + int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); + for (EnrolmentInfo enrolmentInfo : enrolments) { + operationMappingDAO.addOperationMapping(operationId, enrolmentInfo.getId()); + } + OperationManagementDAOFactory.commitTransaction(); + return operationId; + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException("Error occurred while adding operation", e); + } catch (DeviceManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException("Error occurred while retrieving device metadata", e); + } catch (TransactionManagementException e) { + throw new OperationManagementException("Error occurred while initiating the transaction", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to perform operations on given device-list."); } - OperationManagementDAOFactory.commitTransaction(); - return operationId; - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while adding operation", e); - } catch (DeviceManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while retrieving device metadata", e); - } catch (TransactionManagementException e) { - throw new OperationManagementException("Error occurred while initiating the transaction", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + + this.getUser(), e); } + return -1; } @Override @@ -121,45 +133,58 @@ public class OperationManagerImpl implements OperationManager { int enrolmentId; List operations = new ArrayList<>(); try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + deviceId.getType()); - } - List operationList = - operationDAO.getOperationsForDevice(enrolmentId); - - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { - Operation operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device " + + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); + } + List operationList = + operationDAO.getOperationsForDevice(enrolmentId); + + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { + Operation operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving metadata of '" + + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'"); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); } - return operations; - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + "' device '" + deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving metadata of '" + - deviceId.getType() + "' device carrying the identifier '" + deviceId.getId() + "'"); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + + this.getUser(), e); } - + return operations; } @Override - public List getPendingOperations( - DeviceIdentifier deviceId) throws OperationManagementException { + public List getPendingOperations(DeviceIdentifier deviceId) throws + OperationManagementException { if (log.isDebugEnabled()) { log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]"); } @@ -167,113 +192,130 @@ public class OperationManagerImpl implements OperationManager { List operations = new ArrayList<>(); List dtoOperationList = new ArrayList<>(); try { - - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for the given device Identifier:" + - deviceId.getId() + " and given type:" + deviceId.getType()); - } - - dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - Operation operation; - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { - operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for the given device Identifier:" + + deviceId.getId() + " and given type:" + + deviceId.getType()); + } + dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus( + enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + Operation operation; + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { + operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + Collections.sort(operations, new OperationCreateTimeComparator()); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "pending operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + + deviceId.getId()); } - Collections.sort(operations, new OperationCreateTimeComparator()); - return operations; - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "pending operations assigned for '" + deviceId.getType() + "' device '" + - deviceId.getId() + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + "' and device Id '" - + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + + this.getUser(), e); } + return operations; } @Override public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException { if (log.isDebugEnabled()) { - log.debug("device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() - + "]"); + log.debug("device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]"); } Operation operation = null; int enrolmentId; try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + deviceId.getType()); - } - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO - .getNextOperation(enrolmentId); - - if (dtoOperation != null) { - if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND - .equals(dtoOperation.getType())) { - org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO - .getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG - .equals(dtoOperation.getType())) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE - .equals(dtoOperation.getType())) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type - .POLICY.equals(dtoOperation.getType())) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device " + + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); + } + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. + getNextOperation(enrolmentId); + if (dtoOperation != null) { + if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND. + equals(dtoOperation.getType())) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + commandOperation = + (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + getOperation(dtoOperation.getId()); + dtoOperation.setEnabled(commandOperation.isEnabled()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG. + equals(dtoOperation.getType())) { + dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE. + equals(dtoOperation.getType())) { + dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY. + equals(dtoOperation.getType())) { + dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + } + operation = OperationDAOUtil.convertOperation(dtoOperation); + } + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving next pending operation", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId(), e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); } - operation = OperationDAOUtil.convertOperation(dtoOperation); + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + + deviceId.getId()); } - return operation; - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving next pending operation", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + "' and device Id '" + deviceId.getId(), e); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + + this.getUser(), e); } + return operation; } @Override @@ -284,39 +326,52 @@ public class OperationManagerImpl implements OperationManager { } int enrolmentId; try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the data source", e); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.beginTransaction(); - - if (operation.getStatus() != null) { - operationDAO.updateOperationStatus(enrolmentId, operationId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status - .valueOf(operation.getStatus().toString())); - } - if (operation.getOperationResponse() != null) { - operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening a connection to the" + + " data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + OperationManagementDAOFactory.beginTransaction(); + if (operation.getStatus() != null) { + operationDAO.updateOperationStatus(enrolmentId, operationId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status. + valueOf(operation.getStatus().toString())); + } + if (operation.getOperationResponse() != null) { + operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); + } + OperationManagementDAOFactory.commitTransaction(); + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException( + "Error occurred while updating the operation: " + operationId + " status:" + + operation.getStatus(), e); + } catch (DeviceManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException( + "Error occurred while fetching the device for device identifier: " + deviceId.getId() + + "type:" + deviceId.getType(), e); + } catch (TransactionManagementException e) { + throw new OperationManagementException("Error occurred while initiating a transaction", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to update operations on device : " + + deviceId.getId()); } - OperationManagementDAOFactory.commitTransaction(); - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while updating the operation: " + operationId + - " status:" + operation.getStatus(), e); - } catch (DeviceManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while fetching the device for device identifier: " + - deviceId.getId() + "type:" + deviceId.getType(), e); - } catch (TransactionManagementException e) { - throw new OperationManagementException("Error occurred while initiating a transaction", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + + this.getUser(), e); } } @@ -324,14 +379,12 @@ public class OperationManagerImpl implements OperationManager { public void deleteOperation(int operationId) throws OperationManagementException { try { OperationManagementDAOFactory.beginTransaction(); - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation = operationDAO.getOperation(operationId); if (operation == null) { - throw new OperationManagementException("Operation not found for operation id:" + operationId); + throw new OperationManagementException("Operation not found for operation id : " + operationId); } lookupOperationDAO(operation).deleteOperation(operationId); - OperationManagementDAOFactory.commitTransaction(); } catch (OperationManagementDAOException e) { OperationManagementDAOFactory.rollbackTransaction(); @@ -347,64 +400,75 @@ public class OperationManagerImpl implements OperationManager { public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) throws OperationManagementException { int enrolmentId; - Operation operation; + Operation operation = null; if (log.isDebugEnabled()) { - log.debug("Operation Id:" + operationId + " Device Type:" + deviceId.getType() + " Device Identifier:" + - deviceId.getId()); + log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " + + deviceId.getId()); } try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - - OperationManagementDAOFactory.openConnection(); - - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for given device identifier:" + - deviceId.getId() + " type:" + deviceId.getType()); - } - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO - .getOperationByDeviceAndId(enrolmentId, operationId); - - if (dtoOperation.getType() - .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { - org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (dtoOperation.getType() - .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals( - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals( - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); - } - - if (dtoOperation == null) { - throw new OperationManagementException("Operation not found for operation Id:" + operationId + - " device id:" + deviceId.getId()); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device identifier: " + + deviceId.getId() + " type: " + deviceId.getType()); + } + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. + getOperationByDeviceAndId(enrolmentId, operationId); + if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + commandOperation = + (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + getOperation(dtoOperation.getId()); + dtoOperation.setEnabled(commandOperation.isEnabled()); + } else if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { + dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals( + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { + dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals( + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { + dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + } + + if (dtoOperation == null) { + throw new OperationManagementException("Operation not found for operation Id:" + operationId + + " device id:" + deviceId.getId()); + } + operation = OperationDAOUtil.convertOperation(dtoOperation); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening connection to the data source", + e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + + deviceId.getId()); } - operation = OperationDAOUtil.convertOperation(dtoOperation); - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + "' device '" + deviceId.getId() - + "'", e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + "' and device Id '" + - deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + + this.getUser(), e); } return operation; } @@ -413,59 +477,69 @@ public class OperationManagerImpl implements OperationManager { public List getOperationsByDeviceAndStatus( DeviceIdentifier deviceId, Operation.Status status) throws OperationManagementException { List operations = new ArrayList<>(); - List dtoOperationList = - new ArrayList<>(); + List dtoOperationList = new ArrayList<>(); int enrolmentId; try { - try { - DeviceManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } - OperationManagementDAOFactory.openConnection(); - - if (enrolmentId < 0) { - throw new OperationManagementException("Device not found for device id:" + deviceId.getId() + " " + - "type:" + deviceId.getType()); - } - - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus = org.wso2.carbon.device - .mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString()); - dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus)); - - dtoOperationList.addAll( - configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - dtoOperationList.addAll( - profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - dtoOperationList.addAll( - policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - - Operation operation; - - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { - operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + OperationManagementDAOFactory.openConnection(); + + if (enrolmentId < 0) { + throw new OperationManagementException( + "Device not found for device id:" + deviceId.getId() + " " + "type:" + + deviceId.getType()); + } + + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status dtoOpStatus = + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString()); + dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus)); + dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + + Operation operation; + + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { + operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + + deviceId.getId() + "' and status:" + status.toString(), e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the device " + + "for device Identifier type -'" + deviceId.getType() + + "' and device Id '" + deviceId.getId(), e); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + + deviceId.getId()); } - return operations; - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + "' device '" + - deviceId.getId() + "' and status:" + status.toString(), e); - } catch (DeviceManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the device " + - "for device Identifier type -'" + deviceId.getType() + "' and device Id '" + deviceId.getId(), e); - } catch (SQLException e) { - throw new OperationManagementException("Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + + this.getUser(), e); } + return operations; } @Override @@ -473,35 +547,32 @@ public class OperationManagerImpl implements OperationManager { Operation operation; try { OperationManagementDAOFactory.getConnection(); - - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getOperation - (operationId); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. + getOperation(operationId); if (dtoOperation == null) { throw new OperationManagementException("Operation not found for given Id:" + operationId); } - if (dtoOperation.getType() - .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; commandOperation = (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); + getOperation(dtoOperation.getId()); dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (dtoOperation.getType() - .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { + } else if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type - .PROFILE)) { + } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + PROFILE)) { dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type - .POLICY)) { - + } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + POLICY)) { dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); } operation = OperationDAOUtil.convertOperation(dtoOperation); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" + - operationId, e); + operationId, e); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening a connection to the data source", e); } finally { @@ -538,4 +609,8 @@ public class OperationManagerImpl implements OperationManager { } } + private String getUser() { + return CarbonContext.getThreadLocalCarbonContext().getUsername(); + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java index 7908dc63a8..8a282c83f2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java @@ -110,7 +110,7 @@ public class OperationDAOImpl implements OperationDAO { ObjectOutputStream oos = null; try { Connection connection = OperationManagementDAOFactory.getConnection(); - stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,DEVICE_ID," + + stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,ENROLMENT_ID," + "OPERATION_RESPONSE) VALUES(?, ?, ?)"); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); 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 5f0677756a..5592be55b2 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 @@ -38,8 +38,27 @@ public interface DeviceManagementProviderService extends OperationManager { List getAllDevices() throws DeviceManagementException; + /** + * Method to retrieve all the devices with pagination support. + * + * @param deviceType Device platform + * @param index Starting row number + * @param limit No of rows to fetch + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ PaginationResult getAllDevices(String deviceType, int index, int limit) throws DeviceManagementException; + /** + * Method to retrieve all the devices with pagination support. + * + * @param index Starting row number + * @param limit No of rows to fetch + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ PaginationResult getAllDevices(int index, int limit) throws DeviceManagementException; void sendEnrolmentInvitation(EmailMessageProperties config) throws DeviceManagementException; @@ -129,6 +148,8 @@ public interface DeviceManagementProviderService extends OperationManager { Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException; + Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException; + List getAvailableDeviceTypes() throws DeviceManagementException; boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) 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 8eed2efc67..31d84beab5 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 @@ -53,7 +53,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private DeviceDAO deviceDAO; private DeviceTypeDAO deviceTypeDAO; - private EnrolmentDAO enrolmentDAO; + private EnrollmentDAO enrollmentDAO; private DeviceManagementPluginRepository pluginRepository; private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class); @@ -69,7 +69,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private void initDataAccessObjects() { this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); - this.enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); + this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); } @Override @@ -139,26 +139,41 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv EnrolmentInfo existingEnrolmentInfo = existingDevice.getEnrolmentInfo(); EnrolmentInfo newEnrolmentInfo = device.getEnrolmentInfo(); if (existingEnrolmentInfo != null && newEnrolmentInfo != null) { - if (existingEnrolmentInfo.equals(newEnrolmentInfo)) { - device.setId(existingDevice.getId()); - device.getEnrolmentInfo().setDateOfEnrolment(existingEnrolmentInfo.getDateOfEnrolment()); - this.modifyEnrollment(device); - status = true; - } else { - if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) { - this.setStatus(deviceIdentifier, existingEnrolmentInfo.getOwner(), EnrolmentInfo.Status.INACTIVE); + //Get all the enrollments of current user for the same device + List enrolmentInfos = this.getEnrollmentsOfUser(existingDevice.getId(), newEnrolmentInfo.getOwner()); + for (EnrolmentInfo enrolmentInfo : enrolmentInfos) { + //If the enrollments are same then we'll update the existing enrollment. + if (enrolmentInfo.equals(newEnrolmentInfo)) { + device.setId(existingDevice.getId()); + device.getEnrolmentInfo().setDateOfEnrolment(enrolmentInfo.getDateOfEnrolment()); + device.getEnrolmentInfo().setId(enrolmentInfo.getId()); + this.modifyEnrollment(device); + status = true; + break; } - int enrolmentId; + } + if (!status) { + int enrolmentId, updateStatus = 0; try { + //Remove the existing enrollment DeviceManagementDAOFactory.beginTransaction(); - enrolmentId = enrolmentDAO.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId); - DeviceManagementDAOFactory.commitTransaction(); - - if (log.isDebugEnabled()) { - log.debug("An enrolment is successfully updated with the id '" + enrolmentId + - "' associated with " + "the device identified by key '" + - device.getDeviceIdentifier() + "', which belongs to " + "platform '" + - device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'"); + if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) { + existingEnrolmentInfo.setStatus(EnrolmentInfo.Status.REMOVED); + updateStatus = enrollmentDAO.updateEnrollment(existingEnrolmentInfo); + } + if ((updateStatus > 0) || EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) { + enrolmentId = enrollmentDAO.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + if (log.isDebugEnabled()) { + log.debug("An enrolment is successfully added with the id '" + enrolmentId + + "' associated with " + "the device identified by key '" + + device.getDeviceIdentifier() + "', which belongs to " + "platform '" + + device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'"); + } + status = true; + } else { + log.warn("Unable to update device enrollment for device : " + device.getDeviceIdentifier() + + " belonging to user : " + device.getEnrolmentInfo().getOwner()); } } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); @@ -168,7 +183,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - status = true; } } } else { @@ -177,7 +191,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.beginTransaction(); DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); - enrolmentId = enrolmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); + enrolmentId = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); @@ -219,7 +233,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); deviceDAO.updateDevice(type.getId(), device, tenantId); - enrolmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); + enrollmentDAO.updateEnrollment(device.getEnrolmentInfo()); DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceManagementDAOException e) { @@ -234,6 +248,23 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return status; } + private List getEnrollmentsOfUser(int deviceId, String user) + throws DeviceManagementException { + List enrolmentInfos = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + enrolmentInfos = enrollmentDAO.getEnrollmentsOfUser(deviceId, user, this.getTenantId()); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the enrollment information device for id " + + "'" + deviceId + "' and user : " + user, e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return enrolmentInfos; + } + @Override public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); @@ -259,7 +290,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); - enrolmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); + enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); deviceDAO.updateDevice(deviceType.getId(), device, tenantId); DeviceManagementDAOFactory.commitTransaction(); @@ -635,7 +666,41 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return device; } - @Override + @Override + public Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException { + Device device; + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, status, this.getTenantId()); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the device for id " + + "'" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + if (device != null) { + // The changes made here to prevent unit tests getting failed. They failed because when running the unit + // tests there is no osgi services. So getDeviceManager() returns a null. + DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + + "Therefore, not attempting method 'getDevice'"); + } + return device; + } + Device pluginSpecificInfo = deviceManager.getDevice(deviceId); + if (pluginSpecificInfo != null) { + device.setFeatures(pluginSpecificInfo.getFeatures()); + device.setProperties(pluginSpecificInfo.getProperties()); + } + } + return device; + } + + @Override public List getAvailableDeviceTypes() throws DeviceManagementException { List deviceTypes; try { @@ -698,7 +763,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = this.getTenantId(); Device device = deviceDAO.getDevice(deviceId, tenantId); - boolean success = enrolmentDAO.setStatus(device.getId(), currentOwner, status, tenantId); + boolean success = enrollmentDAO.setStatus(device.getId(), currentOwner, status, tenantId); DeviceManagementDAOFactory.commitTransaction(); return success; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java index 35ca0e4d31..5ef0a23578 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java @@ -32,7 +32,7 @@ import java.sql.SQLException; public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { private static final Log log = LogFactory.getLog(EnrolmentPersistenceTests.class); - private EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); + private EnrollmentDAO enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); @Test public void testAddEnrolment() { @@ -47,7 +47,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { /* Adding dummy enrolment configuration to the device management metadata store */ try { DeviceManagementDAOFactory.openConnection(); - enrolmentDAO.addEnrollment(deviceId, source, TestDataHolder.SUPER_TENANT_ID); + enrollmentDAO.addEnrollment(deviceId, source, TestDataHolder.SUPER_TENANT_ID); } catch (DeviceManagementDAOException | SQLException e) { log.error("Error occurred while adding enrollment", e); } finally { @@ -71,7 +71,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { EnrolmentInfo enrolmentInfo = null; try { DeviceManagementDAOFactory.openConnection(); - enrolmentInfo = enrolmentDAO.getEnrolment(deviceId, currentOwner, tenantId); + enrolmentInfo = enrollmentDAO.getEnrollment(deviceId, currentOwner, tenantId); } catch (SQLException e) { log.error("Error occurred while retrieving enrolment corresponding to device id '" + deviceId + "'", e); } finally { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java index 859a0d8c55..a5640b97ea 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java @@ -142,7 +142,7 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist try { // Append the username before Application name to make application name unique across two users. - applicationName = userName + "_" + applicationName; + applicationName = replaceInvalidChars(userName) + "_" + applicationName; // Create the Service Provider ServiceProvider serviceProvider = new ServiceProvider(); @@ -368,4 +368,8 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist } } + private String replaceInvalidChars(String username) { + return username.replaceAll("@","_AT_"); + } + } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java index 14e2ca00b6..3d9e0083cd 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java @@ -131,7 +131,8 @@ public class DynamicClientWebAppRegistrationManager { while (enumeration.hasMoreElements()) { oAuthAppDetails = new OAuthAppDetails(); webAppName = (String) enumeration.nextElement(); - serviceProviderName = DynamicClientWebAppRegistrationUtil.getUserName() + "_" + webAppName; + serviceProviderName = DynamicClientWebAppRegistrationUtil.replaceInvalidChars(DynamicClientWebAppRegistrationUtil.getUserName()) + + "_" + webAppName; servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName); requiredDynamicClientRegistration = servletContext.getInitParameter( DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 034e1e3f8c..03550d9896 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -311,4 +311,8 @@ public class DynamicClientWebAppRegistrationUtil { } } } + + public static String replaceInvalidChars(String username) { + return username.replaceAll("@","_AT_"); + } } \ No newline at end of file diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index e8e27b1263..c741abc99a 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -72,8 +72,8 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { } Properties properties = new Properties(); - properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url); - properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method); + properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url.toLowerCase()); + properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method.toUpperCase()); PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance(). getPermissionManagerService(); try { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index 3e3b605c85..675c0a39c4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -97,6 +97,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato PolicyDelegationException { try { + //ToDo Need to fix this to fetch OSGi service OperationManager operationManager = new OperationManagerImpl(); operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers); } catch (OperationManagementException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index 931d0b4253..868931c422 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -77,7 +77,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { public void addDevice() throws DeviceManagementException, PolicyManagementException { DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); - EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); + EnrollmentDAO enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); DeviceType type = DeviceTypeCreator.getDeviceType(); devices = DeviceCreator.getDeviceList(type); @@ -91,7 +91,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { DeviceManagementDAOFactory.beginTransaction(); for (Device device : devices) { int id = deviceDAO.addDevice(type.getId(), device, -1234); - enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); + enrollmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); } } catch (TransactionManagementException e) { throw new PolicyManagementException("Error occurred while adding device enrolment", e); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java index a74e85bf3e..28732dad38 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -26,11 +26,12 @@ import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.ntask.common.TaskException; -import org.wso2.carbon.ntask.core.service.TaskService; -import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; @@ -48,7 +49,6 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { @BeforeClass @Override public void init() throws Exception { - PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest(); PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint); } @@ -126,8 +126,8 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { log.debug("Delegation methods calls started because tasks cannot be started due to osgi constraints.....!"); - DelegationTask delegationTask = new DelegationTask(); - delegationTask.execute(); + //DelegationTask delegationTask = new DelegationTask(); + //delegationTask.execute(); } public void sortPolicies(List policyList) { 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 bf9a80e5ca..d2be75ca18 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 @@ -103,28 +103,28 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { if(!uri.endsWith("/")) { uri = uri + "/"; } - String ctx = request.getContextPath(); - //Check the context in nonSecuredEndpoints. If so it means current context is a skippedContext. - if (nonSecuredEndpoints.containsKey(uri)) { - return true; - } - String param = request.getContext().findParameter("nonSecuredEndPoints"); - String skippedEndPoint; - if (param != null && !param.isEmpty()) { - //Add the nonSecured end-points to cache - StringTokenizer tokenizer = new StringTokenizer(param, ","); - while (tokenizer.hasMoreTokens()) { - skippedEndPoint = ctx + tokenizer.nextToken(); - skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim(); - if(!skippedEndPoint.endsWith("/")) { - skippedEndPoint = skippedEndPoint + "/"; + String contextPath = request.getContextPath(); + //Check the contextPath in nonSecuredEndpoints. If so it means cache is not populated for this web-app. + if (!nonSecuredEndpoints.containsKey(contextPath)) { + String param = request.getContext().findParameter("nonSecuredEndPoints"); + String skippedEndPoint; + if (param != null && !param.isEmpty()) { + //Add the nonSecured end-points to cache + StringTokenizer tokenizer = new StringTokenizer(param, ","); + nonSecuredEndpoints.put(contextPath, "true"); + while (tokenizer.hasMoreTokens()) { + skippedEndPoint = contextPath + tokenizer.nextToken(); + skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim(); + if(!skippedEndPoint.endsWith("/")) { + skippedEndPoint = skippedEndPoint + "/"; + } + nonSecuredEndpoints.put(skippedEndPoint, "true"); } - nonSecuredEndpoints.put(skippedEndPoint, "true"); - } - if (nonSecuredEndpoints.containsKey(uri)) { - return true; } } + if (nonSecuredEndpoints.containsKey(uri)) { + return true; + } return false; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 6064fe8c8f..72e6134fa6 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -43,7 +43,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { private static final String BEARER_TOKEN_TYPE = "bearer"; private static final String RESOURCE_KEY = "resource"; - private static APITokenAuthenticator authenticator = new APITokenAuthenticator(); + private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); @Override diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 31b46f345b..fb95df9ab0 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -87,12 +87,12 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index e78fb33827..f27b6e69b9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -87,12 +87,12 @@ CREATE TABLE DM_ENROLMENT_OP_MAPPING ( CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( ID INTEGER IDENTITY NOT NULL, - DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE VARBINARY(max) DEFAULT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 9ffb59b85e..cdb2d3c019 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -96,12 +96,12 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION )ENGINE = InnoDB; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 2af12dc572..d0791dc420 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -157,12 +157,12 @@ WHEN (NEW.ID IS NULL) CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( ID NUMBER(10) NOT NULL, - DEVICE_ID NUMBER(10) NOT NULL, + ENROLMENT_ID NUMBER(10) NOT NULL, OPERATION_ID NUMBER(10) NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, CONSTRAINT PK_DM_DEVICE_OP_RESPONSE PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_op_res_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID), + CONSTRAINT fk_dm_device_op_res_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID), CONSTRAINT fk_dm_device_op_res_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 4e8b752758..1740e5d551 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -82,11 +82,11 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BYTEA DEFAULT NULL, - CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); From 5d107b0d56a768cfb241c8b51d9b658ae077e1af Mon Sep 17 00:00:00 2001 From: harshanl Date: Tue, 10 Nov 2015 18:46:26 +0530 Subject: [PATCH 6/9] Merged changes --- .../DeviceManagementProviderServiceImpl.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) 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 51dbd8f7fe..6a49235aef 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 @@ -667,6 +667,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return device; } + @Override + public Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException { + Device device; + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, status, this.getTenantId()); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while obtaining the device for id " + + "'" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + if (device != null) { + // The changes made here to prevent unit tests getting failed. They failed because when running the unit + // tests there is no osgi services. So getDeviceManager() returns a null. + DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + + "Therefore, not attempting method 'getDevice'"); + } + return device; + } + Device pluginSpecificInfo = deviceManager.getDevice(deviceId); + if (pluginSpecificInfo != null) { + device.setFeatures(pluginSpecificInfo.getFeatures()); + device.setProperties(pluginSpecificInfo.getProperties()); + } + } + return device; + } + @Override public List getAvailableDeviceTypes() throws DeviceManagementException { List deviceTypesInDatabase; From 8953a61cc4e8a4b445a00f682d1ad24c32d728a1 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Tue, 10 Nov 2015 20:17:59 +0530 Subject: [PATCH 7/9] Enable Owneship type editing in policy --- .../policy/mgt/core/dao/impl/PolicyDAOImpl.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 593c4a88fc..33a56b6623 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -280,15 +280,14 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ?, OWNERSHIP_TYPE = ? WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (Policy policy : policies) { stmt.setInt(1, policy.getPriorityId()); stmt.setInt(2, 1); - stmt.setString(3, policy.getOwnershipType()); - stmt.setInt(4, policy.getId()); - stmt.setInt(5, tenantId); + stmt.setInt(3, policy.getId()); + stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); @@ -743,7 +742,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," + - " UPDATED = ?, DESCRIPTION = ? WHERE ID = ? AND TENANT_ID = ?"; + " UPDATED = ?, DESCRIPTION = ?, OWNERSHIP_TYPE = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, policy.getPolicyName()); stmt.setInt(2, policy.getProfile().getProfileId()); @@ -751,8 +750,9 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setString(4, policy.getCompliance()); stmt.setInt(5, 1); stmt.setString(6, policy.getDescription()); - stmt.setInt(7, policy.getId()); - stmt.setInt(8, tenantId); + stmt.setString(7, policy.getOwnershipType()); + stmt.setInt(8, policy.getId()); + stmt.setInt(9, tenantId); stmt.executeUpdate(); } catch (SQLException e) { From 5af6f314d0b7fb46e89f3075f8c6fad9b1267bf9 Mon Sep 17 00:00:00 2001 From: harshanl Date: Wed, 11 Nov 2015 20:58:47 +0530 Subject: [PATCH 8/9] Fixed EMM-939 --- .../extensions/validators/PermissionBasedScopeValidator.java | 3 ++- .../framework/authenticator/OAuthAuthenticator.java | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index c741abc99a..cb8d59fb5c 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -81,11 +81,12 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { User authzUser = accessTokenDO.getAuthzUser(); if ((permission != null) && (authzUser != null)) { String username = authzUser.getUserName(); + String userStore = authzUser.getUserStoreDomain(); int tenantId = OAuthExtUtils.getTenantId(authzUser.getTenantDomain()); UserRealm userRealm = OAuthExtensionsDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); if (userRealm != null && userRealm.getAuthorizationManager() != null) { status = userRealm.getAuthorizationManager() - .isUserAuthorized(username, permission.getPath(), + .isUserAuthorized(userStore +"/"+ username, permission.getPath(), PermissionMethod.UI_EXECUTE); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 72e6134fa6..adc31a9c14 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -111,6 +111,10 @@ public class OAuthAuthenticator implements WebappAuthenticator { AuthenticatorFrameworkDataHolder.getInstance().getoAuth2TokenValidationService().validate(dto); if (oAuth2TokenValidationResponseDTO.isValid()) { String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser(); + //Remove the userstore domain from username + if (username.contains("/")) { + username = username.substring(username.indexOf('/') + 1); + } authenticationInfo.setUsername(username); authenticationInfo.setTenantDomain(MultitenantUtils.getTenantDomain(username)); authenticationInfo.setTenantId(Utils.getTenantIdOFUser(username)); From 49cbac0a8ca51c69056d54ee30ba88ae85ae4d9e Mon Sep 17 00:00:00 2001 From: geethkokila Date: Fri, 13 Nov 2015 15:12:34 +0530 Subject: [PATCH 9/9] Changing the apim version --- pom.xml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e52c77573e..fd4032a8a6 100644 --- a/pom.xml +++ b/pom.xml @@ -1435,8 +1435,19 @@ false + + + + + + + + + + + 6.1.1 4.4.2 @@ -1506,7 +1517,7 @@ 2.6.0.wso2v1 - 4.3.0-SNAPSHOT + 4.3.0 2.7.16