Merge branch 'kernel-4.6.2' into 'kernel-4.6.x'

bug fixing authorize flow

See merge request entgra/carbon-device-mgt!783
kernel-4.6.x
Charitha Goonetilleke 3 years ago
commit 62b7479653

@ -161,4 +161,16 @@ public interface SubscriptionManager {
*/
PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action)
throws ApplicationManagementException;
/***
* This method is responsible to provide application subscription devices data for given application release UUID.
* @param request PaginationRequest object holding the data for pagination
* @param appUUID UUID of the application release.
* @param subType subscription type of the application(eg: GROUP, USER, ...)
* @param subTypeName subscription type name of the application (Name of the group, Name of the user, ...).
* @return {@link PaginationResult} pagination result of the category details.
* @throws {@link ApplicationManagementException} Exception of the application management
*/
PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType,
String subTypeName) throws ApplicationManagementException;
}

@ -228,4 +228,16 @@ public interface SubscriptionDAO {
throws ApplicationManagementDAOException;
int getSubscribedGroupCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the details of subscribed groups
*
* @param tenantId id of the current tenant
* @param appReleaseId id of the application release..
* @param subtype application subscribed type.
* @return subscribedDevices - list of app subscribed devices under the subtype.
* @throws {@link ApplicationManagementDAOException} if connections establishment fails.
*/
List<Integer> getAppSubscribedDevicesForGroups(int appReleaseId, String subtype, int tenantId)
throws ApplicationManagementDAOException;
}

@ -1271,4 +1271,45 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getAppSubscribedDevicesForGroups(int appReleaseId, String subType, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get already subscribed devices for " +
"given app release id.");
}
// retrieve all device list by action triggered type and app release id
try {
Connection conn = this.getDBConnection();
List<Integer> subscribedGroupDevices = new ArrayList<>();
String sql = "SELECT "
+ "AP_DEVICE_SUBSCRIPTION.DM_DEVICE_ID AS DEVICES "
+ "FROM AP_DEVICE_SUBSCRIPTION "
+ "WHERE "
+ "AP_APP_RELEASE_ID = ? AND ACTION_TRIGGERED_FROM=? AND "
+ "UNSUBSCRIBED=FALSE AND TENANT_ID = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setString(2, subType.toLowerCase());;
ps.setInt(3, tenantId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
subscribedGroupDevices.add(rs.getInt("DEVICES"));
}
}
return subscribedGroupDevices;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get already " +
"subscribed groups for given app release id.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting subscribed devices for given " +
"app release id.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -1427,4 +1427,50 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType,
String subTypeName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(appUUID, tenantId);
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<Integer> subscriptionDeviceList = new ArrayList<>();
//todo update the API for other subscription types
if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) {
subscriptionDeviceList = subscriptionDAO
.getAppSubscribedDevicesForGroups(applicationReleaseId, subType, tenantId);
} else {
String msg = "Found invalid sub type: " + subType;
log.error(msg);
throw new NotFoundException(msg);
}
if (subscriptionDeviceList.isEmpty()) {
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(subscriptionDeviceList);
paginationResult.setRecordsFiltered(0);
paginationResult.setRecordsTotal(0);
return paginationResult;
}
return deviceManagementProviderService.getDevicesDetails(request, subscriptionDeviceList, subTypeName);
} catch (DeviceManagementException e) {
String msg = "service error occurred while getting device data from the device management service.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when get application release devices data for application release UUID: "
+ appUUID;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "DB Connection error occurred while getting category details that given application id";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -449,4 +449,101 @@ public interface SubscriptionManagementAPI {
defaultValue = "5")
@QueryParam("limit") int limit
);
@GET
@Path("/{uuid}/{subType}/{subTypeName}/devices")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get device details in categories that have a given application install",
notes = "This will get the category's device details that have a given application install, if exists",
tags = "Subscription Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:subscription:uninstall")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved device details.",
response = List.class,
responseContainer = "List"),
@ApiResponse(
code = 404,
message = "Not Found. \n No Devices found which has application " +
"release of UUID.",
response = ErrorResponse.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Found invalid payload with the request.",
response = List.class),
@ApiResponse(
code = 403,
message = "Forbidden. \n Don't have permission to get the details.",
response = List.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting data",
response = ErrorResponse.class)
})
Response getAppInstalledDevicesOnCategories(
@ApiParam(
name="uuid",
value="uuid of the application release.",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name="subType",
value="Subscription type of the application release.",
required = true)
@PathParam("subType") String subType,
@ApiParam(
name="subTypeName",
value="Subscription type name of the application release.",
required = true)
@PathParam("subTypeName") String subTypeName,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting " +
"pagination index/offset.",
defaultValue = "5")
@QueryParam("limit") int limit,
@ApiParam(
name = "name",
value = "The device name. For example, Nexus devices can have names, such as shamu, bullhead or angler.",
required = false)
@Size(max = 45)
String name,
@ApiParam(
name = "user",
value = "The username of the owner of the device.",
required = false)
@QueryParam("user")
String user,
@ApiParam(
name = "ownership",
allowableValues = "BYOD, COPE",
value = "Provide the ownership status of the device. The following values can be assigned:\n" +
"- BYOD: Bring Your Own Device\n" +
"- COPE: Corporate-Owned, Personally-Enabled",
required = false)
@QueryParam("ownership")
@Size(max = 45)
String ownership,
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.")
@QueryParam("status") List<String> status
);
}

@ -400,4 +400,73 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Consumes("application/json")
@Produces("application/json")
@Path("/{uuid}/{subType}/{subTypeName}/devices")
public Response getAppInstalledDevicesOnCategories(
@PathParam("uuid") String uuid,
@PathParam("subType") String subType,
@PathParam("subTypeName") String subTypeName,
@DefaultValue("0")
@QueryParam("offset") int offset,
@DefaultValue("5")
@QueryParam("limit") int limit,
@QueryParam("name") String name,
@QueryParam("user") String user,
@QueryParam("ownership") String ownership,
@QueryParam("status") List<String> status) {
try {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationRequest request = new PaginationRequest(offset, limit);
if (StringUtils.isNotBlank(name)) {
request.setDeviceName(name);
}
if (StringUtils.isNotBlank(user)) {
request.setOwner(user);
}
if (StringUtils.isNotBlank(ownership)) {
RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
//todo need to update the API for other subscription types
if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) {
PaginationResult subscribedCategoryDetails = subscriptionManager
.getAppInstalledSubscribeDevices(request, uuid, subType, subTypeName);
DeviceList devices = new DeviceList();
devices.setList((List<Device>) subscribedCategoryDetails.getData());
devices.setCount(subscribedCategoryDetails.getRecordsTotal());
return Response.status(Response.Status.OK).entity(devices).build();
} else {
String msg = "Found invalid sub type: " + subType;
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (NotFoundException e) {
String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting application with the application " +
"release uuid: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -180,6 +180,13 @@ import java.util.List;
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/change-status"}
),
@Scope(
name = "Enroll Device",
description = "Register a device",
key = "perm:device:enroll",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/owning-device/add"}
),
}
)
@Path("/devices")

@ -167,6 +167,7 @@ public final class DeviceManagementConstants {
new Permission("/permission/admin/device-mgt/devices/enroll", "ui.execute"),
new Permission("/permission/admin/device-mgt/devices/disenroll", "ui.execute"),
new Permission("/permission/admin/device-mgt/devices/owning-device/view", "ui.execute"),
new Permission("/permission/admin/device-mgt/metadata", "ui.execute"),
new Permission("/permission/admin/manage/portal", "ui.execute")
};

@ -1,64 +0,0 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.cache;
import java.util.Objects;
public class APIResourcePermissionCacheKey {
private String context;
private volatile int hashCode;
public APIResourcePermissionCacheKey(String context) {
this.context = context;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!APIResourcePermissionCacheKey.class.isAssignableFrom(obj.getClass())) {
return false;
}
final APIResourcePermissionCacheKey other = (APIResourcePermissionCacheKey) obj;
String thisId = this.context;
String otherId = other.context;
if (!thisId.equals(otherId)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(context);
}
return hashCode;
}
}

@ -1,84 +0,0 @@
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.cache.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.cache.Cache;
import java.util.List;
public class APIResourcePermissionCacheManagerImpl implements APIResourcePermissionCacheManager {
private static final Log log = LogFactory.getLog(APIResourcePermissionCacheManagerImpl.class);
private static APIResourcePermissionCacheManagerImpl apiResourceCacgeManager;
private APIResourcePermissionCacheManagerImpl() {
}
public static APIResourcePermissionCacheManagerImpl getInstance() {
if (apiResourceCacgeManager == null) {
synchronized (APIResourcePermissionCacheManagerImpl.class) {
if (apiResourceCacgeManager == null) {
apiResourceCacgeManager = new APIResourcePermissionCacheManagerImpl();
}
}
}
return apiResourceCacgeManager;
}
@Override
public void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
if (lCache.containsKey(cacheKey)) {
this.updateAPIResourcePermissionInCache(cacheKey, permissions);
} else {
lCache.put(cacheKey, permissions);
}
}
}
@Override
public void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
if (lCache.containsKey(cacheKey)) {
lCache.replace(cacheKey, permissions);
}
}
}
@Override
public List<Permission> getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey) {
Cache<APIResourcePermissionCacheKey, List<Permission>> lCache = DeviceManagerUtil.getAPIResourcePermissionCache();
if (lCache != null) {
return lCache.get(cacheKey);
}
return null;
}
}

@ -758,4 +758,27 @@ public interface DeviceDAO {
String version) throws DeviceManagementDAOException;
int getFunctioningDevicesInSystem() throws DeviceManagementDAOException;
/**
* This method is used to get the details of devices when give deviceIDs list and group name.
* @param deviceIds device ids of the devices.
* @param tenantId Id of the current tenant.
* @param request paginated request object.
* @param groupName group name.
* @return devices - device details list
* @throws DeviceManagementDAOException if connections establishment fails.
*/
List<Device> getGroupedDevicesDetails(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException;
/**
* @param deviceIds device ids of the devices.
* @param tenantId tenant id
* @param request paginated request object.
* @param groupName group name.
* @return number of device count under the group name.
* @throws DeviceManagementDAOException if error occurred while processing the SQL statement.
*/
int getGroupedDevicesCount(PaginationRequest request, List<Integer> deviceIds, String groupName, int tenantId)
throws DeviceManagementDAOException;
}

@ -3022,4 +3022,154 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Device> getGroupedDevicesDetails(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
return devices;
}
Connection conn = this.getConnection();
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
+ "DM_DEVICE.NAME AS DEVICE_NAME, "
+ "DM_DEVICE.DESCRIPTION AS DESCRIPTION, "
+ "DM_DEVICE.DEVICE_TYPE_ID, "
+ "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, "
+ "e.ID AS ENROLMENT_ID, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE_GROUP_MAP "
+ "INNER JOIN DM_DEVICE ON "
+ "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID "
+ "INNER JOIN DM_GROUP ON "
+ "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID "
+ "INNER JOIN DM_ENROLMENT e ON "
+ "DM_DEVICE.ID = e.DEVICE_ID AND "
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID "
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (StringUtils.isNotBlank(groupName)) {
query += " AND DM_GROUP.GROUP_NAME = ?";
}
if (StringUtils.isNotBlank(name)) {
query += " AND DM_DEVICE.NAME LIKE ?";
}
if (StringUtils.isNotBlank(user)) {
query += " AND e.OWNER = ?";
}
if (StringUtils.isNotBlank(ownership)) {
query += " AND e.OWNERSHIP = ?";
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
}
query += "LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setInt(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (StringUtils.isNotBlank(groupName)) {
ps.setString(index++, groupName);
}
if (StringUtils.isNotBlank(name)) {
ps.setString(index++, name);
}
if (StringUtils.isNotBlank(user)) {
ps.setString(index++, user);
}
if (StringUtils.isNotBlank(ownership)) {
ps.setString(index++, ownership);
}
if (status != null && !status.isEmpty()) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);
}
}
ps.setInt(index++, limitValue);
ps.setInt(index, offsetValue);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDevice(rs));
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public int getGroupedDevicesCount(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
if (deviceIds.isEmpty()) {
return 0;
}
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "COUNT(DM_DEVICE_GROUP_MAP.DEVICE_ID) AS DEVICE_COUNT "
+ "FROM DM_DEVICE_GROUP_MAP "
+ "INNER JOIN DM_GROUP ON "
+ "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID "
+ "WHERE DM_DEVICE_GROUP_MAP.DEVICE_ID IN (",
") AND DM_GROUP.TENANT_ID = ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (StringUtils.isNotBlank(groupName)) {
query += " AND DM_GROUP.GROUP_NAME = ?";
}
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setInt(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (StringUtils.isNotBlank(groupName)) {
ps.setString(index, groupName);
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("DEVICE_COUNT");
}
return 0;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -1194,6 +1194,79 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
@Override
public List<Device> getGroupedDevicesDetails(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
return devices;
}
Connection conn = this.getConnection();
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
+ "DM_DEVICE.NAME AS DEVICE_NAME, "
+ "DM_DEVICE.DESCRIPTION AS DESCRIPTION, "
+ "DM_DEVICE.DEVICE_TYPE_ID, "
+ "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, "
+ "e.ID AS ENROLMENT_ID, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE_GROUP_MAP "
+ "INNER JOIN DM_DEVICE ON "
+ "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID "
+ "INNER JOIN DM_GROUP ON "
+ "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID "
+ "INNER JOIN DM_ENROLMENT e ON "
+ "DM_DEVICE.ID = e.DEVICE_ID AND "
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID "
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (StringUtils.isNotBlank(groupName)) {
query += " AND DM_GROUP.GROUP_NAME = ?";
}
query += " ORDER BY DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setInt(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (StringUtils.isNotBlank(groupName)) {
ps.setString(index++, groupName);
}
ps.setInt(index++, offsetValue);
ps.setInt(index, limitValue);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDevice(rs));
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Count;
@ -1132,6 +1133,79 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
@Override
public List<Device> getGroupedDevicesDetails(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
return devices;
}
Connection conn = this.getConnection();
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
+ "DM_DEVICE.NAME AS DEVICE_NAME, "
+ "DM_DEVICE.DESCRIPTION AS DESCRIPTION, "
+ "DM_DEVICE.DEVICE_TYPE_ID, "
+ "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, "
+ "e.ID AS ENROLMENT_ID, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "FROM DM_DEVICE_GROUP_MAP "
+ "INNER JOIN DM_DEVICE ON "
+ "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID "
+ "INNER JOIN DM_GROUP ON "
+ "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID "
+ "INNER JOIN DM_ENROLMENT e ON "
+ "DM_DEVICE.ID = e.DEVICE_ID AND "
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID "
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (StringUtils.isNotBlank(groupName)) {
query += " AND DM_GROUP.GROUP_NAME = ?";
}
query += " ORDER BY DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setInt(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (StringUtils.isNotBlank(groupName)) {
ps.setString(index++, groupName);
}
ps.setInt(index++, offsetValue);
ps.setInt(index, limitValue);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDevice(rs));
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
//TODO: Override for MSSQL
/*
@Override

@ -21,6 +21,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
@ -35,20 +37,42 @@ public class UserRoleCreateObserver implements ServerStartupObserver {
@Override
public void completedServerStartup() {
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
String tenantAdminName = "admin";
try {
UserStoreManager userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
userStoreManager.addRole(
DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN,
new String[]{tenantAdminName},
DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN);
userStoreManager.addRole(
DeviceManagementConstants.User.DEFAULT_DEVICE_USER,
new String[]{tenantAdminName},
DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER);
String tenantAdminName =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminUserName();
AuthorizationManager authorizationManager = DeviceManagementDataHolder.getInstance().getRealmService()
.getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getAuthorizationManager();
if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN)) {
userStoreManager.addRole(
DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN,
null,
DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN);
} else {
for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN) {
authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN,
permission.getResourceId(), permission.getAction());
}
}
if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER)) {
userStoreManager.addRole(
DeviceManagementConstants.User.DEFAULT_DEVICE_USER,
null,
DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER);
} else {
for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER) {
authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER,
permission.getResourceId(), permission.getAction());
}
}
userStoreManager.updateRoleListOfUser(tenantAdminName, null,
new String[] {DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN,
DeviceManagementConstants.User.DEFAULT_DEVICE_USER});
if (log.isDebugEnabled()) {
log.debug("Device management roles: " + DeviceManagementConstants.User.DEFAULT_DEVICE_USER + ", " +

@ -4,9 +4,9 @@
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@ -15,17 +15,26 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.cache;
package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface APIResourcePermissionCacheManager {
public class APIResourcePermissions {
private Map<String, List<Permission>> apiResourcePermissions;
void addAPIResourcePermissionToCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions);
public APIResourcePermissions() {
apiResourcePermissions = new HashMap<>();
}
void updateAPIResourcePermissionInCache(APIResourcePermissionCacheKey cacheKey, List<Permission> permissions);
public void addPermissionList(String context, List<Permission> permissions){
apiResourcePermissions.put(context, permissions);
}
List<Permission> getAPIResourceRermissionFromCache(APIResourcePermissionCacheKey cacheKey);
public List<Permission> getPermissions(String context) {
return apiResourcePermissions.get(context);
}
}

@ -18,16 +18,11 @@
package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.impl.APIResourcePermissionCacheManagerImpl;
import java.util.List;
import java.util.Properties;
/**
* This class will add, update custom permissions defined in permission.xml in webapps and it will
@ -36,7 +31,7 @@ import java.util.Properties;
public class PermissionManagerServiceImpl implements PermissionManagerService {
private static PermissionManagerServiceImpl registryBasedPermissionManager;
private static APIResourcePermissions apiResourcePermissions;
private PermissionManagerServiceImpl() {
}
@ -45,6 +40,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
synchronized (PermissionManagerServiceImpl.class) {
if (registryBasedPermissionManager == null) {
registryBasedPermissionManager = new PermissionManagerServiceImpl();
apiResourcePermissions = new APIResourcePermissions();
}
}
}
@ -57,8 +53,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
for (Permission permission : permissions) {
PermissionUtils.putPermission(permission);
}
APIResourcePermissionCacheManagerImpl.getInstance().addAPIResourcePermissionToCache(
new APIResourcePermissionCacheKey(context), permissions);
apiResourcePermissions.addPermissionList(context, permissions);
} catch (PermissionManagementException e) {
return false;
}
@ -67,7 +62,6 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
@Override
public List<Permission> getPermission(String context) throws PermissionManagementException {
return APIResourcePermissionCacheManagerImpl.getInstance().getAPIResourceRermissionFromCache(
new APIResourcePermissionCacheKey(context));
return apiResourcePermissions.getPermissions(context);
}
}

@ -992,4 +992,14 @@ public interface DeviceManagementProviderService {
License getLicenseConfig (String deviceTypeName) throws DeviceManagementException;
/**
* This method retrieves a list of devices details.
* @param request paginated request object.
* @param devicesIds devices ids list
* @param groupName name of the group
* @return {@link PaginationResult}
* @throws DeviceManagementException if any service level or DAO level error occurs.
*/
PaginationResult getDevicesDetails(PaginationRequest request, List<Integer> devicesIds, String groupName)
throws DeviceManagementException;
}

@ -4434,4 +4434,39 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return deviceManagementService.getLicenseConfig();
}
@Override
public PaginationResult getDevicesDetails(PaginationRequest request, List<Integer> devicesIds,
String groupName) throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (log.isDebugEnabled()) {
log.debug("Getting all devices details for device ids: " + devicesIds);
}
PaginationResult paginationResult = new PaginationResult();
List<Device> subscribedDeviceDetails;
try {
DeviceManagementDAOFactory.openConnection();
subscribedDeviceDetails = deviceDAO.getGroupedDevicesDetails(request, devicesIds, groupName, tenantId);
if (subscribedDeviceDetails.isEmpty()) {
paginationResult.setData(new ArrayList<>());
paginationResult.setRecordsFiltered(0);
paginationResult.setRecordsTotal(0);
return paginationResult;
}
int count = deviceDAO.getGroupedDevicesCount(request, devicesIds, groupName, tenantId);
paginationResult.setRecordsFiltered(count);
paginationResult.setRecordsTotal(count);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device list for device ids " + devicesIds;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails));
return paginationResult;
}
}

@ -76,7 +76,6 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementExcept
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.cache.APIResourcePermissionCacheKey;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@ -724,21 +723,6 @@ public final class DeviceManagerUtil {
return deviceCache;
}
public static Cache<APIResourcePermissionCacheKey, List<Permission>> getAPIResourcePermissionCache() {
CacheManager manager = getCacheManager();
Cache<APIResourcePermissionCacheKey, List<Permission>> apiResourcePermissionCache = null;
if(!isAPIResourcePermissionCacheInitialized) {
initializeAPIResourcePermissionCache();
}
if (manager != null) {
apiResourcePermissionCache = manager.getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
} else {
apiResourcePermissionCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER)
.getCache(DeviceManagementConstants.API_RESOURCE_PERMISSION_CACHE);
}
return apiResourcePermissionCache;
}
/**
* Get geofence cache object
* @return {@link Cache<GeoCacheKey, GeofenceData>}

@ -398,7 +398,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
DEVICE_ID INT NULL,
ENROLMENT_ID INT NOT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)

@ -400,7 +400,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)

@ -452,7 +452,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
DEVICE_ID INT NULL,
ENROLMENT_ID INT NOT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)

@ -21,6 +21,7 @@ package org.wso2.carbon.webapp.authenticator.framework;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.owasp.encoder.Encode;
@ -194,7 +195,8 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
ctx = tokenizer.nextToken();
}
}
return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx));
return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx)
|| "oauth2".equalsIgnoreCase(ctx));
}
private boolean isNonSecuredEndPoint(Request request) {

@ -46,6 +46,10 @@ public class PermissionAuthorizer {
return WebappAuthenticator.Status.CONTINUE;
}
if (requestUri.endsWith("/")) {
requestUri = requestUri.substring(0, requestUri.length() - 1);
}
PermissionManagerService registryBasedPermissionManager =
PermissionManagerServiceImpl.getInstance();
List<Permission> matchingPermissions = null;

@ -424,7 +424,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
DEVICE_ID INT NULL,
ENROLMENT_ID INT NOT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)

@ -474,7 +474,7 @@ CREATE TABLE DM_DEVICE_INFO (
DEVICE_ID INTEGER NULL,
ENROLMENT_ID INTEGER NOT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC),
INDEX DM_DEVICE_INFO_DEVICE_ENROLLMENT_idx (ENROLMENT_ID ASC),

@ -491,7 +491,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
DEVICE_ID INT NULL,
ENROLMENT_ID INT NOT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(1000) NULL,
VALUE_FIELD VARCHAR(1500) NULL,
PRIMARY KEY (ID),
INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC),
INDEX DM_DEVICE_INFO_DEVICE_ENROLLMENT_idx (ENROLMENT_ID ASC),

@ -779,7 +779,7 @@ CREATE TABLE DM_DEVICE_INFO (
DEVICE_ID NUMBER(10) NOT NULL,
ENROLMENT_ID NUMBER(10) NOT NULL,
KEY_FIELD VARCHAR2(45) NULL,
VALUE_FIELD VARCHAR2(1000) NULL,
VALUE_FIELD VARCHAR2(1500) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)

Loading…
Cancel
Save