Add wipe API for Google enterprise

revert-dabc3590
shamalka 5 years ago
parent 70c980f46f
commit 7c69a296c5

@ -1322,24 +1322,22 @@ public interface AndroidEnterpriseAPI {
//###################################################################################################################### //######################################################################################################################
//###################################################################################################################### //######################################################################################################################
@PUT @GET
@Path("/unenroll") @Path("/wipe-device")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
consumes = MediaType.APPLICATION_JSON, httpMethod = "GET",
httpMethod = "PUT", value = "Getting managed configs",
value = "Unenroll an enterprise from EMM", notes = "Getting managed configs.",
notes = "Unenroll an enterprise from EMM.", tags = "Device Type Management Administrative Service",
tags = "Android Enterprise Service",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify")
}) })
} }
) )
@ApiResponses( @ApiResponses(value = {
value = { @ApiResponse(code = 200, message = "Created. \n Successfully fetched managed configs",
@ApiResponse(code = 201, message = "Created. \n Successfully removed",
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
name = "Content-Location", name = "Content-Location",
@ -1372,9 +1370,8 @@ public interface AndroidEnterpriseAPI {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + message = "Internal Server Error. \n " +
"Server error occurred while unenrolling.") "Server error occurred while getting managed configs.")
}) })
Response wipeEnterprise();
Response unenroll();
} }

@ -30,8 +30,16 @@ import org.wso2.carbon.device.application.mgt.common.dto.ApplicationPolicyDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
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.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.mobile.android.api.AndroidEnterpriseAPI; import org.wso2.carbon.device.mgt.mobile.android.api.AndroidEnterpriseAPI;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.GoogleAPIInvoker; import org.wso2.carbon.device.mgt.mobile.android.common.GoogleAPIInvoker;
@ -795,28 +803,75 @@ public class AndroidEnterpriseAPIImpl implements AndroidEnterpriseAPI {
} }
} }
@PUT
@Path("/{id}/unenroll")
@Override @Override
public Response unenroll() { @Produces(MediaType.APPLICATION_JSON)
@GET
@Path("/wipe-device")
public Response wipeEnterprise() {
log.warn("Wiping all devices!!!");
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try { try {
googleAPIInvoker.unenroll(enterpriseConfigs.getEnterpriseId()); // Take all enterprise devices in the DB.
} catch (IOException e) { List<AndroidEnterpriseUser> androidEnterpriseUsers = AndroidAPIUtils.getAndroidPluginService()
String errorMessage = "Could not unenroll the enterprise " + enterpriseConfigs.getEnterpriseId(); .getAllEnterpriseDevices(enterpriseConfigs.getEnterpriseId());
log.error(errorMessage);
throw new NotFoundException( // Extract the device identifiers of enterprise devices.
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.INTERNAL_SERVER_ERROR List<String> deviceID = new ArrayList<>();
.getStatusCode()).setMessage(errorMessage).build()); if (androidEnterpriseUsers != null && !androidEnterpriseUsers.isEmpty()) {
for (AndroidEnterpriseUser userDevice: androidEnterpriseUsers) {
deviceID.add(userDevice.getEmmDeviceId());
}
}
List<String> byodDevices = new ArrayList<>();
List<String> copeDevices = new ArrayList<>();
// Get all registered device
List<Device> devices = AndroidAPIUtils.getDeviceManagementService().
getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false);
for (Device device : devices) { // Go through all enrolled devices
if (deviceID.contains(device.getDeviceIdentifier())) { // Filter out only enterprise enrolled devices.
if (device.getEnrolmentInfo().getOwnership().equals(EnrolmentInfo.OwnerShip.BYOD)) {
byodDevices.add(device.getDeviceIdentifier());
} else {
copeDevices.add(device.getDeviceIdentifier());
}
}
}
CommandOperation operation = new CommandOperation();
operation.setType(Operation.Type.COMMAND);//TODO: Check if this should be profile
// type when implementing COPE/COSU
if (byodDevices != null && !byodDevices.isEmpty()) { // BYOD devices only needs a data wipe(work profile)
log.warn("Wiping " + byodDevices.size() + " BYOD devices");
operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE);
} else if (copeDevices != null && !copeDevices.isEmpty()) {
log.warn("Wiping " + copeDevices.size() + " COPE/COSU devices");
operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA);
}
AndroidDeviceUtils.getOperationResponse(deviceID, operation);
log.warn("Added wipe to all devices");
return Response.status(Response.Status.OK).build();
} catch (EnterpriseServiceException e) { } catch (EnterpriseServiceException e) {
String errorMessage = "Could not get client to call Google to unenroll enterprise " + enterpriseConfigs.getEnterpriseId(); return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build();
} catch (OperationManagementException e) {
String errorMessage = "Could not add wipe command to enterprise " + enterpriseConfigs.getEnterpriseId();
log.error(errorMessage); log.error(errorMessage);
throw new NotFoundException( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.INTERNAL_SERVER_ERROR new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
.getStatusCode()).setMessage(errorMessage).build()); } catch (DeviceManagementException e) {
String errorMessage = "Could not add wipe command to enterprise " + enterpriseConfigs.getEnterpriseId() +
" due to an error in device management";
log.error(errorMessage);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
} catch (InvalidDeviceException e) {
String errorMessage = "Could not add wipe command to enterprise due to invalid device ids";
log.error(errorMessage);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
} }
return Response.status(Response.Status.OK).build();
} }
} }

@ -39,4 +39,7 @@ public interface AndroidGoogleEnterpriseService {
boolean updateMobileDevice(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException; boolean updateMobileDevice(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException;
boolean deleteMobileDevice(String id) throws EnterpriseServiceException; boolean deleteMobileDevice(String id) throws EnterpriseServiceException;
List<AndroidEnterpriseUser> getAllEnterpriseDevices(String enterpriseId)
throws EnterpriseServiceException ;
} }

@ -50,4 +50,7 @@ public interface EnterpriseDAO {
boolean updateConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException; boolean updateConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException;
boolean deleteConfig(String id, int tenantId) throws EnterpriseManagementDAOException; boolean deleteConfig(String id, int tenantId) throws EnterpriseManagementDAOException;
List<AndroidEnterpriseUser> getAllEnterpriseDevices(int tenantId, String enterpriseId) throws
EnterpriseManagementDAOException;
} }

@ -286,4 +286,42 @@ public class EnterpriseDAOImpl implements EnterpriseDAO {
return status; return status;
} }
public List<AndroidEnterpriseUser> getAllEnterpriseDevices(int tenantId, String enterpriseId)
throws EnterpriseManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
List<AndroidEnterpriseUser> enterpriseUsers = new ArrayList<>();
ResultSet rs = null;
try {
conn = AndroidDAOFactory.getConnection();
String selectDBQuery =
"SELECT * FROM AD_ENTERPRISE_USER_DEVICE WHERE ENTERPRISE_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, enterpriseId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
AndroidEnterpriseUser enterpriseUser = new AndroidEnterpriseUser();
enterpriseUser.setEmmUsername(rs.getString("EMM_USERNAME"));
enterpriseUser.setTenantId(rs.getInt("TENANT_ID"));
enterpriseUser.setLastUpdatedTime(rs.getString("LAST_UPDATED_TIMESTAMP"));
enterpriseUser.setAndroidPlayDeviceId(rs.getString("ANDROID_PLAY_DEVICE_ID"));
enterpriseUser.setEnterpriseId(rs.getString("ENTERPRISE_ID"));
enterpriseUser.setGoogleUserId(rs.getString("GOOGLE_USER_ID"));
enterpriseUser.setEmmDeviceId(rs.getString("EMM_DEVICE_ID"));
enterpriseUsers.add(enterpriseUser);
}
} catch (SQLException e) {
String msg = "Error occurred while fetching user of enterprise: '" + enterpriseId + "'";
log.error(msg, e);
throw new EnterpriseManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
return enterpriseUsers;
}
} }

@ -216,4 +216,30 @@ public class AndroidGoogleEnterpriseServiceImpl implements AndroidGoogleEnterpri
} }
return status; return status;
} }
@Override
public List<AndroidEnterpriseUser> getAllEnterpriseDevices(String enterpriseId)
throws EnterpriseServiceException {
List<AndroidEnterpriseUser> androidEnterpriseUsers;
if (log.isDebugEnabled()) {
log.debug("Calling get enterprise device service by enterprise identifier: " + enterpriseId);
}
try {
AndroidDAOFactory.openConnection();
androidEnterpriseUsers = this.enterpriseDAO.getAllEnterpriseDevices(CarbonContext
.getThreadLocalCarbonContext()
.getTenantId(), enterpriseId);
} catch (EnterpriseManagementDAOException e) {
String msg = "Error occurred while adding the user "
+ CarbonContext.getThreadLocalCarbonContext().getUsername();
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
} finally {
AndroidDAOFactory.closeConnection();
}
return androidEnterpriseUsers;
}
} }

@ -323,6 +323,7 @@ public class AndroidDeviceUtils {
JsonArray appListArray = appListElement.getAsJsonArray(); JsonArray appListArray = appListElement.getAsJsonArray();
// Find if there are Apps with Work profile configurations // Find if there are Apps with Work profile configurations
boolean alreadySendToGoogle = false;
for (JsonElement appElement : appListArray) { for (JsonElement appElement : appListArray) {
JsonElement googlePolicyPayload = appElement.getAsJsonObject(). JsonElement googlePolicyPayload = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD); get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
@ -332,12 +333,16 @@ public class AndroidDeviceUtils {
containsGoogleAppPolicy = true;// breaking out of outer for loop containsGoogleAppPolicy = true;// breaking out of outer for loop
try { try {
uuid = uuid.replace("\"", ""); uuid = uuid.replace("\"", "");
sendPayloadToGoogle(uuid, payload, deviceIdentifier); if (alreadySendToGoogle) {
sendPayloadToGoogle(uuid, payload, deviceIdentifier, false);
} else {
sendPayloadToGoogle(uuid, payload, deviceIdentifier, true);
alreadySendToGoogle = true;
}
} catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) { } catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) {
String errorMessage = "App install failed for device " + deviceIdentifier.getId(); String errorMessage = "App install failed for device " + deviceIdentifier.getId();
log.error(errorMessage, e); log.error(errorMessage, e);
} }
break;
} }
} }
@ -352,8 +357,8 @@ public class AndroidDeviceUtils {
* @param payload policy profile * @param payload policy profile
* @param deviceIdentifier device to apply policy * @param deviceIdentifier device to apply policy
*/ */
private static void sendPayloadToGoogle(String uuid, String payload, DeviceIdentifier deviceIdentifier) private static void sendPayloadToGoogle(String uuid, String payload, DeviceIdentifier deviceIdentifier,
throws ApplicationManagementException { boolean requireSendingToGoogle) throws ApplicationManagementException {
try { try {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigsFromGoogle(); EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigsFromGoogle();
if (enterpriseConfigs.getErrorResponse() == null) { if (enterpriseConfigs.getErrorResponse() == null) {
@ -369,12 +374,12 @@ public class AndroidDeviceUtils {
for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) { for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) {
apps.add(enterpriseApp.getProductId()); apps.add(enterpriseApp.getProductId());
} }
googleAPIInvoker if (requireSendingToGoogle) {
.approveAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(), apps, googleAPIInvoker.approveAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail
enterpriseInstallPolicy.getProductSetBehavior()); .getGoogleUserId(), apps, enterpriseInstallPolicy.getProductSetBehavior());
googleAPIInvoker googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy)); AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy));
}
AndroidEnterpriseUtils.getAppSubscriptionService().performEntAppSubscription(uuid, AndroidEnterpriseUtils.getAppSubscriptionService().performEntAppSubscription(uuid,
Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()), Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()),
SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false); SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false);
@ -697,6 +702,10 @@ public class AndroidDeviceUtils {
StringEntity requestEntity = new StringEntity(payload.toString(), ContentType.APPLICATION_JSON); StringEntity requestEntity = new StringEntity(payload.toString(), ContentType.APPLICATION_JSON);
JsonArray appListArray = appListElement.getAsJsonArray(); JsonArray appListArray = appListElement.getAsJsonArray();
for (JsonElement appElement : appListArray) { for (JsonElement appElement : appListArray) {
JsonElement googlePolicyPayload = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
if (googlePolicyPayload == null) {
uuid = appElement.getAsJsonObject(). uuid = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString(); get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
@ -707,6 +716,8 @@ public class AndroidDeviceUtils {
postRequest.setEntity(requestEntity); postRequest.setEntity(requestEntity);
httpClient.execute(postRequest); httpClient.execute(postRequest);
} }
}
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error while accessing user store for user with Android device id: " + String msg = "Error while accessing user store for user with Android device id: " +

Loading…
Cancel
Save