Merge branch 'rest-api-improvements' of https://github.com/wso2/carbon-device-mgt into rest-api-improvements

merge-requests/7/head
mharindu 9 years ago
commit 63ea40eb27

@ -227,7 +227,8 @@ public interface CertificateManagementAdminService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE", httpMethod = "DELETE",
value = "Delete an SSL certificate", value = "Delete an SSL certificate",
notes = "Delete an SSL certificate that's on the client end") notes = "Delete an SSL certificate that's on the client end",
tags = "Certificate Management")
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,

@ -22,7 +22,7 @@ import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Path("/certificates") @Path("/admin/certificates")
public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService { public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService {
private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.class); private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.class);

@ -33,33 +33,33 @@
<Permission> <Permission>
<name>get certificate in the database</name> <name>get certificate in the database</name>
<path>/device-mgt/emm-admin/certificate/GetSignCSR</path> <path>/device-mgt/emm-admin/certificate/GetSignCSR</path>
<url>/certificates/signcsr</url> <url>/certificates/sign-csr</url>
<method>POST</method> <method>POST</method>
<scope>emm_admin</scope> <scope>emm_admin</scope>
</Permission> </Permission>
<!-- CertificateManagementAdminService related APIs --> <!-- CertificateManagementAdminService related APIs -->
<Permission> <Permission>
<name>Save certificate in the database</name> <name>Save certificate</name>
<path>/device-mgt/admin/certificate/save</path> <path>/device-mgt/admin/certificate/Save</path>
<url>/certificates</url> <url>/certificates</url>
<method>POST</method> <method>POST</method>
</Permission> </Permission>
<Permission> <Permission>
<name>get certificate in the database</name> <name>Get certificate</name>
<path>/device-mgt/admin/certificate/Get</path> <path>/device-mgt/admin/certificate/Get</path>
<url>/certificates/*</url> <url>/certificates/*</url>
<method>GET</method> <method>GET</method>
</Permission> </Permission>
<Permission> <Permission>
<name>get certificate in the database</name> <name>Get all certificates</name>
<path>/device-mgt/admin/certificate/GetAll</path> <path>/device-mgt/admin/certificate/GetAll</path>
<url>/certificates</url> <url>/certificates</url>
<method>GET</method> <method>GET</method>
</Permission> </Permission>
<Permission> <Permission>
<name>get certificate in the database</name> <name>Remove certificate</name>
<path>/device-mgt/admin/certificate/Get</path> <path>/device-mgt/admin/certificate/Remove</path>
<url>/certificates/*</url> <url>/certificates/*</url>
<method>DELETE</method> <method>DELETE</method>
</Permission> </Permission>

@ -21,34 +21,14 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "UserCredentialWrapper", description = "User credentials are included in this class.") @ApiModel(value = "OldPasswordResetWrapper", description = "User credentials are included in this class.")
public class UserCredentialWrapper { public class OldPasswordResetWrapper extends PasswordResetWrapper{
@ApiModelProperty(name = "username", value = "Username of the user.", required = true )
private String username;
/* /*
Base64 encoded password Base64 encoded password
*/ */
@ApiModelProperty(name = "oldPassword", value = "Old password of the user.", required = true ) @ApiModelProperty(name = "oldPassword", value = "Old password of the user.", required = true )
private String oldPassword; private String oldPassword;
@ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true )
private String newPassword;
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOldPassword() { public String getOldPassword() {
return oldPassword; return oldPassword;

@ -0,0 +1,41 @@
/*
* Copyright (c) 2016, 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.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "PasswordResetWrapper", description = "User credential is included in this class.")
public class PasswordResetWrapper {
/*
Base64 encoded password
*/
@ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true )
private String newPassword;
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}

@ -21,21 +21,20 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List; import java.util.List;
@ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy " @ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy "
+ "Wrappers") + "Wrappers")
public class PolicyWrapper { public class PolicyWrapper {
@ApiModelProperty(name = "id", value = "The policy ID", required = true)
private int id;
@ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the"
+ " policy", required = true)
private Profile profile;
@ApiModelProperty(name = "policyName", value = "The name of the policy", required = true) @ApiModelProperty(name = "policyName", value = "The name of the policy", required = true)
private String policyName; private String policyName;
@ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true) @ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true)
private String description; private String description;
@ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the" @ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the"
+ " following non-compliance rules:\n" + " following non-compliance rules:\n"
+ "Enforce - Forcefully enforce the policies on the devices\n" + "Enforce - Forcefully enforce the policies on the devices\n"
@ -44,8 +43,7 @@ public class PolicyWrapper {
+ "violation unknown to the user and the administrator can take the necessary actions with regard" + "violation unknown to the user and the administrator can take the necessary actions with regard"
+ " to the reported", required = true) + " to the reported", required = true)
private String compliance; private String compliance;
@ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true)
private List<String> roles;
@ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the " @ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the "
+ "following values:\n" + "following values:\n"
+ "ANY - The policy will be applied on the BYOD and COPE device types\n" + "ANY - The policy will be applied on the BYOD and COPE device types\n"
@ -53,26 +51,21 @@ public class PolicyWrapper {
+ "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE " + "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE "
+ "device type", required = true) + "device type", required = true)
private String ownershipType; private String ownershipType;
@ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on",
@ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the"
+ " policy", required = true)
private Profile profile;
@ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true)
private List<String> roles;
@ApiModelProperty(name = "deviceIdentifiers", value = "Lists out the devices the policy is enforced on",
required = true) required = true)
private List<Device> devices; private List<DeviceIdentifier> deviceIdentifiers;
@ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced", @ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced",
required = true) required = true)
private List<String> users; private List<String> users;
@ApiModelProperty(name = "tenantId", value = "The ID of the tenant that created the policy",
required = true)
private int tenantId;
@ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy",
required = true)
private int profileId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Profile getProfile() { public Profile getProfile() {
return profile; return profile;
@ -122,12 +115,12 @@ public class PolicyWrapper {
this.ownershipType = ownershipType; this.ownershipType = ownershipType;
} }
public List<Device> getDevices() { public List<DeviceIdentifier> getDeviceIdentifiers() {
return devices; return deviceIdentifiers;
} }
public void setDevices(List<Device> devices) { public void setDeviceIdentifier(List<DeviceIdentifier> deviceIdentifier) {
this.devices = devices; this.deviceIdentifiers = deviceIdentifiers;
} }
public List<String> getUsers() { public List<String> getUsers() {
@ -138,20 +131,4 @@ public class PolicyWrapper {
this.users = users; this.users = users;
} }
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public int getProfileId() {
return profileId;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
}
} }

@ -0,0 +1,56 @@
/*
* Copyright (c) 2016, 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.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
@ApiModel(value = "Role List")
public class RoleList extends BasePaginatedResult {
private List<String> roles;
@ApiModelProperty(value = "List of roles returned")
@JsonProperty("roles")
public List<String> getList() {
return roles;
}
public void setList(List<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" roles: [").append(roles).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, 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.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "List of users", description = "This contains a set of users that matches a given " +
"criteria as a collection")
public class UserList extends BasePaginatedResult {
private List<UserWrapper> users = new ArrayList<>();
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("users")
public List<UserWrapper> getList() {
return users;
}
public void setList(List<UserWrapper> users) {
this.users = users;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" users: [").append(users).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -258,6 +258,7 @@ public interface PolicyManagementService {
required = true) PolicyWrapper policy); required = true) PolicyWrapper policy);
@POST @POST
@Path("/remove-policy")
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,

@ -22,6 +22,8 @@ import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ -43,18 +45,15 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Get the list of roles.", value = "Get the list of roles.",
responseContainer = "List",
notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST API. All " + notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST API. All " +
"internal roles, roles created for Service-providers and application related roles are omitted.", "internal roles, roles created for Service-providers and application related roles are omitted.",
response = String.class,
tags = "Role Management") tags = "Role Management")
@ApiResponses( @ApiResponses(
value = { value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully fetched the requested list of roles.", message = "OK. \n Successfully fetched the requested list of roles.",
response = String.class, response = RoleList.class,
responseContainer = "List",
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
name = "Content-Type", name = "Content-Type",
@ -76,7 +75,8 @@ public interface RoleManagementService {
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-view", permissions = { @Permission(scope = "roles-view", permissions = {
"/permission/admin/device-mgt/admin/roles/list", "/permission/admin/device-mgt/admin/roles/list",
@ -155,7 +155,8 @@ public interface RoleManagementService {
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getPermissionsOfRole( Response getPermissionsOfRole(
@ -209,7 +210,8 @@ public interface RoleManagementService {
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the requested role.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching the requested role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"})
Response getRole( Response getRole(
@ -260,14 +262,16 @@ public interface RoleManagementService {
description = "The Source URL of the document.")}), description = "The Source URL of the document.")}),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error."), message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 415, code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."), message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while adding a new role.") "Server error occurred while adding a new role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"})
Response addRole( Response addRole(
@ -307,7 +311,8 @@ public interface RoleManagementService {
"Used by caches, or in conditional requests.")}), "Used by caches, or in conditional requests.")}),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error."), message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Resource to be deleted does not exist."), message = "Not Found. \n Resource to be deleted does not exist."),
@ -317,7 +322,8 @@ public interface RoleManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the role.") "Server error occurred while updating the role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateRole( Response updateRole(
@ -349,7 +355,8 @@ public interface RoleManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while removing the role.") "Server error occurred while removing the role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"})
Response deleteRole( Response deleteRole(
@ -395,7 +402,8 @@ public interface RoleManagementService {
"Used by caches, or in conditional requests.")}), "Used by caches, or in conditional requests.")}),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error."), message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Resource to be deleted does not exist."), message = "Not Found. \n Resource to be deleted does not exist."),
@ -405,7 +413,8 @@ public interface RoleManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the user list of the role.") "Server error occurred while updating the user list of the role.",
response = ErrorResponse.class)
}) })
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
Response updateUsersOfRole( Response updateUsersOfRole(

@ -21,13 +21,13 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserList;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date;
@API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"}) @API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"})
@ -280,14 +280,14 @@ public interface UserManagementService {
value = "Get user list", value = "Get user list",
notes = "If you wish to get the details of all the users registered with EMM, you can do so " notes = "If you wish to get the details of all the users registered with EMM, you can do so "
+ "using the REST API", + "using the REST API",
response = UserWrapper.class, response = UserList.class,
responseContainer = "List", responseContainer = "List",
tags = "User Management") tags = "User Management")
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully fetched the requested role.", message = "OK. \n Successfully fetched the requested role.",
response = UserWrapper.class, response = UserList.class,
responseContainer = "List", responseContainer = "List",
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
@ -304,7 +304,7 @@ public interface UserManagementService {
}), }),
@ApiResponse( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@ApiResponse( @ApiResponse(
code = 406, code = 406,
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
@ -317,7 +317,7 @@ public interface UserManagementService {
@ApiParam( @ApiParam(
name = "filter", name = "filter",
value = "Username of the user details to be fetched.", value = "Username of the user details to be fetched.",
required = true) required = false)
@QueryParam("filter") String filter, @QueryParam("filter") String filter,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
@ -406,7 +406,7 @@ public interface UserManagementService {
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "POST", httpMethod = "PUT",
value = "Changing the user password.", value = "Changing the user password.",
notes = "A user is able to change the password to secure their EMM profile via this REST API.", notes = "A user is able to change the password to secure their EMM profile via this REST API.",
tags = "User Management") tags = "User Management")
@ -438,6 +438,6 @@ public interface UserManagementService {
@ApiParam( @ApiParam(
name = "credentials", name = "credentials",
value = "Credential.", value = "Credential.",
required = true) UserCredentialWrapper credentials); required = true) OldPasswordResetWrapper credentials);
} }

@ -27,73 +27,73 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date; import java.util.Date;
@Path("/admin/groups") //@Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) //@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) //@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + //@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " +
"'internal' components to log in as an admin user and do a selected number of operations. " + // "'internal' components to log in as an admin user and do a selected number of operations. " +
"Further, this is strictly restricted to admin users only ") // "Further, this is strictly restricted to admin users only ")
public interface GroupManagementAdminService { public interface GroupManagementAdminService {
@GET // @GET
@ApiOperation( // @ApiOperation(
produces = MediaType.APPLICATION_JSON, // produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", // httpMethod = "GET",
value = "Get groups by the name.", // value = "Get groups by the name.",
notes = "Get devices the name of device and tenant.", // notes = "Get devices the name of device and tenant.",
response = DeviceGroupWrapper.class, // response = DeviceGroupWrapper.class,
responseContainer = "List", // responseContainer = "List",
tags = "Group Management Administrative Service") // tags = "Group Management Administrative Service")
@ApiResponses(value = { // @ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", // @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.",
response = DeviceGroupWrapper.class, // response = DeviceGroupWrapper.class,
responseContainer = "List", // responseContainer = "List",
responseHeaders = { // responseHeaders = {
@ResponseHeader( // @ResponseHeader(
name = "Content-Type", // name = "Content-Type",
description = "The content type of the body"), // description = "The content type of the body"),
@ResponseHeader( // @ResponseHeader(
name = "ETag", // name = "ETag",
description = "Entity Tag of the response resource.\n" + // description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), // "Used by caches, or in conditional requests."),
@ResponseHeader( // @ResponseHeader(
name = "Last-Modified", // name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" + // description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."), // "Used by caches, or in conditional requests."),
}), // }),
@ApiResponse( // @ApiResponse(
code = 304, // code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), // message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse( // @ApiResponse(
code = 406, // code = 406,
message = "Not Acceptable.\n The requested media type is not supported"), // message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse( // @ApiResponse(
code = 500, // code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") // message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.")
}) // })
@Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) // @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"})
Response getGroupsOfUser( // Response getGroupsOfUser(
@ApiParam( // @ApiParam(
name = "username", // name = "username",
value = "Username of the user.", // value = "Username of the user.",
required = true) // required = true)
@QueryParam("username") String username, // @QueryParam("username") String username,
@ApiParam( // @ApiParam(
name = "If-Modified-Since", // name = "If-Modified-Since",
value = "Timestamp of the last modified date", // value = "Timestamp of the last modified date",
required = false) // required = false)
@HeaderParam("If-Modified-Since") String timestamp, // @HeaderParam("If-Modified-Since") String timestamp,
@ApiParam( // @ApiParam(
name = "offset", // name = "offset",
value = "Starting point within the complete list of items qualified.", // value = "Starting point within the complete list of items qualified.",
required = false) // required = false)
@QueryParam("offset") int offset, // @QueryParam("offset") int offset,
@ApiParam( // @ApiParam(
name = "limit", // name = "limit",
value = "Maximum size of resource array to return.", // value = "Maximum size of resource array to return.",
required = false) // required = false)
@QueryParam("limit") int limit); // @QueryParam("limit") int limit);
//
} }

@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -62,7 +62,7 @@ public interface UserManagementAdminService {
"Server error occurred while updating credentials of the user.") "Server error occurred while updating credentials of the user.")
}) })
@Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) @Permission(scope = "user-modify", permissions = {"/permission/admin/login"})
Response resetPassword( Response resetUserPassword(
@ApiParam( @ApiParam(
name = "username", name = "username",
value = "Username of the user.", value = "Username of the user.",
@ -71,6 +71,6 @@ public interface UserManagementAdminService {
@ApiParam( @ApiParam(
name = "credentials", name = "credentials",
value = "Credential.", value = "Credential.",
required = true) UserCredentialWrapper credentials); required = true) PasswordResetWrapper credentials);
} }

@ -23,11 +23,13 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; 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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; 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.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.PolicyFilteringUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
@ -51,49 +53,62 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
@Override @Override
public Response addPolicy(PolicyWrapper policyWrapper) { public Response addPolicy(PolicyWrapper policyWrapper) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy = this.getPolicyFromWrapper(policyWrapper); try {
Policy policy = this.getPolicyFromWrapper(policyWrapper);
List<Device> devices = policy.getDevices(); List<Device> devices = policy.getDevices();
if (devices != null && devices.size() == 1) { if (devices != null && devices.size() == 1) {
DeviceAccessAuthorizationService deviceAccessAuthorizationService = DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(); DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(), DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(),
devices.get(0).getType()); devices.get(0).getType());
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername(); String username = threadLocalCarbonContext.getUsername();
try { try {
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) { if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) {
return Response.status(Response.Status.UNAUTHORIZED).entity("Current logged in user is " + return Response.status(Response.Status.UNAUTHORIZED).entity("Current logged in user is " +
"not authorized to add policies").build(); "not authorized to add policies").build();
}
} catch (DeviceAccessAuthorizationException e) {
String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy";
log.error(msg, e);
return javax.ws.rs.core.Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} catch (DeviceAccessAuthorizationException e) {
String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy";
log.error(msg, e);
return javax.ws.rs.core.Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
}
try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.addPolicy(policy); pap.addPolicy(policy);
return Response.status(Response.Status.OK).entity("Policy has been added successfully").build(); return Response.status(Response.Status.CREATED).entity("Policy has been added successfully").build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while adding policy"; String msg = "ErrorResponse occurred while adding policy";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while retrieving device list.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) { private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) throws DeviceManagementException {
Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); Policy policy = new Policy();
policy.setPolicyName(policyWrapper.getPolicyName()); policy.setPolicyName(policyWrapper.getPolicyName());
policy.setProfileId(policyWrapper.getProfileId());
policy.setDescription(policyWrapper.getDescription()); policy.setDescription(policyWrapper.getDescription());
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
policy.setOwnershipType(policyWrapper.getOwnershipType()); policy.setOwnershipType(policyWrapper.getOwnershipType());
policy.setRoles(policyWrapper.getRoles()); policy.setRoles(policyWrapper.getRoles());
policy.setUsers(policyWrapper.getUsers()); policy.setUsers(policyWrapper.getUsers());
policy.setTenantId(policyWrapper.getTenantId());
policy.setCompliance(policyWrapper.getCompliance()); policy.setCompliance(policyWrapper.getCompliance());
//TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here.
List<Device> devices = null;
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();
if (deviceIdentifiers != null) {
for (DeviceIdentifier id : deviceIdentifiers) {
devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id));
}
}
policy.setDevices(devices);
policy.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
return policy; return policy;
} }
@ -116,7 +131,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity(policies).build(); return Response.status(Response.Status.OK).entity(PolicyFilteringUtil.getPolicies(policies, offset, limit))
.build();
} }
@GET @GET
@ -144,19 +160,29 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
@Override @Override
public Response updatePolicy(@PathParam("id") int id, PolicyWrapper policyWrapper) { public Response updatePolicy(@PathParam("id") int id, PolicyWrapper policyWrapper) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy = this.getPolicyFromWrapper(policyWrapper);
try { try {
Policy policy = this.getPolicyFromWrapper(policyWrapper);
policy.setId(id);
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
Policy exisitingPolicy = pap.getPolicy(id);
if (exisitingPolicy == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Policy not found.").build();
}
pap.updatePolicy(policy); pap.updatePolicy(policy);
return Response.status(Response.Status.OK).entity("Policy has successfully been updated").build(); return Response.status(Response.Status.OK).entity("Policy has successfully been updated").build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while updating the policy"; String msg = "ErrorResponse occurred while updating the policy";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while retrieving the device list.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@POST @POST
@Path("/remove-policy")
@Override @Override
public Response removePolicies(List<Integer> policyIds) { public Response removePolicies(List<Integer> policyIds) {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
@ -164,8 +190,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) { for (int i : policyIds) {
org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i); Policy policy = pap.getPolicy(i);
if (!pap.deletePolicy(policy)) { if (policy == null || !pap.deletePolicy(policy)) {
policyDeleted = false; policyDeleted = false;
} }
} }
@ -182,41 +208,62 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
} }
} }
@POST @PUT
@Path("/activate-policy") @Path("/activate-policy")
@Override @Override
public Response activatePolicies(List<Integer> policyIds) { public Response activatePolicies(List<Integer> policyIds) {
boolean isPolicyActivated = false;
try { try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) { for (int i : policyIds) {
pap.activatePolicy(i); Policy policy = pap.getPolicy(i);
if (policy != null) {
pap.activatePolicy(i);
isPolicyActivated = true;
}
} }
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "ErrorResponse occurred while activating policies"; String msg = "ErrorResponse occurred while activating policies";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated").build(); if (isPolicyActivated) {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated")
.build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Selected policies have not been activated")
.build();
}
} }
@POST @PUT
@Path("/deactivate-policy") @Path("/deactivate-policy")
@Override @Override
public Response deactivatePolicies(List<Integer> policyIds) { public Response deactivatePolicies(List<Integer> policyIds) {
boolean isPolicyDeActivated = false;
try { try {
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
for (int i : policyIds) { for (int i : policyIds) {
pap.inactivatePolicy(i); Policy policy = pap.getPolicy(i);
if (policy != null) {
pap.inactivatePolicy(i);
isPolicyDeActivated = true;
}
} }
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "Exception in inactivating policies."; String msg = "Exception in inactivating policies.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity("Selected policies have been successfully " + if (isPolicyDeActivated) {
"deactivated").build(); return Response.status(Response.Status.OK).entity("Selected policies have been successfully " +
"deactivated").build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Selected policies have not been deactivated")
.build();
}
} }
} }

@ -22,7 +22,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
@ -54,17 +57,22 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@HeaderParam("If-Modified-Since") String ifModifiedSince, @HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) { @QueryParam("offset") int offset, @QueryParam("limit") int limit) {
List<String> filteredRoles; List<String> filteredRoles;
RoleList targetRoles;
try { try {
filteredRoles = getRolesFromUserStore(); filteredRoles = getRolesFromUserStore();
if (filteredRoles == null || filteredRoles.size() == 0) { if (filteredRoles == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build(); return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build();
} }
targetRoles = new RoleList();
targetRoles.setCount(filteredRoles.size());
targetRoles.setList(filteredRoles);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving roles from the underlying user stores"; String msg = "Error occurred while retrieving roles from the underlying user stores";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).entity(filteredRoles).build(); return Response.status(Response.Status.OK).entity(targetRoles).build();
} }
@GET @GET
@ -88,14 +96,16 @@ public class RoleManagementServiceImpl implements RoleManagementService {
} }
return Response.status(Response.Status.OK).entity(rolePermissions).build(); return Response.status(Response.Status.OK).entity(rolePermissions).build();
} catch (UserAdminException e) { } catch (UserAdminException e) {
String msg = "ErrorResponse occurred while retrieving the permissions of role '" + roleName + "'"; String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the underlying user realm attached to the " + String msg = "Error occurred while retrieving the underlying user realm attached to the " +
"current logged in user"; "current logged in user";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -150,9 +160,10 @@ public class RoleManagementServiceImpl implements RoleManagementService {
roleWrapper.setPermissions(permList.toArray(permListAr)); roleWrapper.setPermissions(permList.toArray(permListAr));
} }
} catch (UserStoreException | UserAdminException e) { } catch (UserStoreException | UserAdminException e) {
String msg = "ErrorResponse occurred while retrieving the user role '" + roleName + "'"; String msg = "Error occurred while retrieving the user role '" + roleName + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).entity(roleWrapper).build(); return Response.status(Response.Status.OK).entity(roleWrapper).build();
} }
@ -190,11 +201,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
} }
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while adding role '" + roleWrapper.getRoleName() + "'"; String msg = "Error occurred while adding role '" + roleWrapper.getRoleName() + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been added").build();
} }
@PUT @PUT
@ -236,11 +249,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
} }
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating role '" + roleName + "'"; String msg = "Error occurred while updating role '" + roleName + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been updated").build();
} }
@DELETE @DELETE
@ -257,11 +272,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
// Delete all authorizations for the current role before deleting // Delete all authorizations for the current role before deleting
authorizationManager.clearRoleAuthorization(roleName); authorizationManager.clearRoleAuthorization(roleName);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while deleting the role '" + roleName + "'"; String msg = "Error occurred while deleting the role '" + roleName + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been deleted").build();
} }
@PUT @PUT
@ -287,11 +304,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating the users of the role '" + roleName + "'"; String msg = "Error occurred while updating the users of the role '" + roleName + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been updated with the user list").build();
} }
private List<String> getRolesFromUserStore() throws UserStoreException { private List<String> getRolesFromUserStore() throws UserStoreException {

@ -26,9 +26,12 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserList;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
@ -85,11 +88,13 @@ public class UserManagementServiceImpl implements UserManagementService {
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Exception in trying to add user '" + userWrapper.getUsername() + "' to the user store"; String msg = "Exception in trying to add user '" + userWrapper.getUsername() + "' to the user store";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while inviting user to enroll the device"; String msg = "ErrorResponse occurred while inviting user to enroll the device";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -142,10 +147,10 @@ public class UserManagementServiceImpl implements UserManagementService {
Properties props = new Properties(); Properties props = new Properties();
props.setProperty("username", usernameBits[1]); props.setProperty("username", usernameBits[1]);
props.setProperty("domain-name", tenantDomain); props.setProperty("domain-name", tenantDomain);
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); props.setProperty("first-name", getClaimValue(usernameBits[1], Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("password", password); props.setProperty("password", password);
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); String recipient = getClaimValue(usernameBits[1], Constants.USER_CLAIM_EMAIL_ADDRESS);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
@ -187,7 +192,8 @@ public class UserManagementServiceImpl implements UserManagementService {
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'"; String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -203,9 +209,8 @@ public class UserManagementServiceImpl implements UserManagementService {
userWrapper.getEmailAddress()); userWrapper.getEmailAddress());
if (StringUtils.isNotEmpty(userWrapper.getPassword())) { if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
// Decoding Base64 encoded password // Decoding Base64 encoded password
byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
new String(decodedBytes, "UTF-8")); userWrapper.getPassword());
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
} }
List<String> currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername()); List<String> currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername());
@ -242,10 +247,11 @@ public class UserManagementServiceImpl implements UserManagementService {
userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was " + userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was " +
"refused.").build(); "refused.").build();
} }
} catch (UserStoreException | UnsupportedEncodingException e) { } catch (UserStoreException e) {
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -293,11 +299,12 @@ public class UserManagementServiceImpl implements UserManagementService {
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Exception in trying to remove user by username: " + username; String msg = "Exception in trying to remove user by username: " + username;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@POST @GET
@Path("/{username}/roles") @Path("/{username}/roles")
@Override @Override
public Response getRolesOfUser(@PathParam("username") String username) { public Response getRolesOfUser(@PathParam("username") String username) {
@ -317,7 +324,8 @@ public class UserManagementServiceImpl implements UserManagementService {
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Exception in trying to retrieve roles for user by username: " + username; String msg = "Exception in trying to retrieve roles for user by username: " + username;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -329,10 +337,15 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information"); log.debug("Getting the list of users with all user-related information");
} }
List<UserWrapper> userList; List<UserWrapper> userList, offsetList;
String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter);
int appliedLimit = (limit <= 0) ? -1 : (limit + offset);
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*", -1);
//As the listUsers function accepts limit only to accommodate offset we are passing offset + limit
String[] users = userStoreManager.listUsers(appliedFilter, appliedLimit);
userList = new ArrayList<>(users.length); userList = new ArrayList<>(users.length);
UserWrapper user; UserWrapper user;
for (String username : users) { for (String username : users) {
@ -343,14 +356,27 @@ public class UserManagementServiceImpl implements UserManagementService {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
if (userList.size() <= 0) {
return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build(); if (offset <= userList.size()) {
offsetList = userList.subList(offset, userList.size());
} else {
offsetList = new ArrayList<>();
} }
return Response.status(Response.Status.OK).entity(userList).build();
// if (offsetList.size() <= 0) {
// return Response.status(Response.Status.NOT_FOUND).entity("No users available for retrieval").build();
// }
UserList result = new UserList();
result.setList(offsetList);
result.setCount(offsetList.size());
return Response.status(Response.Status.OK).entity(result).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the list of users"; String msg = "ErrorResponse occurred while retrieving the list of users.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -376,22 +402,23 @@ public class UserManagementServiceImpl implements UserManagementService {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
if (userList.size() <= 0) { // if (userList.size() <= 0) {
return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build(); // return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build();
} // }
return Response.status(Response.Status.OK).entity(userList).build(); return Response.status(Response.Status.OK).entity(userList).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the list of users using the filter : " + filter; String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@PUT @PUT
@Path("/{username}/credentials") @Path("/{username}/credentials")
@Override @Override
public Response resetPassword(@PathParam("username") String username, UserCredentialWrapper credentials) { public Response resetPassword(@PathParam("username") String username, OldPasswordResetWrapper credentials) {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); return CredentialManagementResponseBuilder.buildChangePasswordResponse(username, credentials);
} }
} }

@ -59,8 +59,10 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
} }
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain));
List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name); List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().
getDevicesByNameAndType(name, type, offset, limit);
if (devices == null) { if (devices == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" +
name + "', is currently enrolled in the system").build(); name + "', is currently enrolled in the system").build();

@ -31,32 +31,32 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date; import java.util.Date;
@Path("/admin/groups") //@Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) //@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) //@Consumes(MediaType.APPLICATION_JSON)
public class GroupManagementAdminServiceImpl implements GroupManagementAdminService { public class GroupManagementAdminServiceImpl implements GroupManagementAdminService {
//
private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); // private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class);
//
@Override // @Override
public Response getGroupsOfUser( // public Response getGroupsOfUser(
@QueryParam("username") String username, // @QueryParam("username") String username,
@HeaderParam("If-Modified-Since") String timestamp, // @HeaderParam("If-Modified-Since") String timestamp,
@QueryParam("offset") int offset, // @QueryParam("offset") int offset,
@QueryParam("limit") int limit) { // @QueryParam("limit") int limit) {
try { // try {
PaginationResult result = // PaginationResult result =
DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); // DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit);
if (result != null && result.getRecordsTotal() > 0) { // if (result != null && result.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(result).build(); // return Response.status(Response.Status.OK).entity(result).build();
} else { // } else {
return Response.status(Response.Status.NOT_FOUND).build(); // return Response.status(Response.Status.NOT_FOUND).build();
} // }
} catch (GroupManagementException e) { // } catch (GroupManagementException e) {
String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; // String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'";
log.error(msg, e); // log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} // }
} // }
} }

@ -18,7 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.UserManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.UserManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder;
@ -34,8 +34,8 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
@POST @POST
@Path("/{username}/credentials") @Path("/{username}/credentials")
@Override @Override
public Response resetPassword(@PathParam("username") String user, UserCredentialWrapper credentials) { public Response resetUserPassword(@PathParam("username") String user, PasswordResetWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials);
} }
} }

@ -0,0 +1,41 @@
/*
* Copyright (c) 2016, 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.jaxrs.service.impl.util;
import org.wso2.carbon.policy.mgt.common.Policy;
import java.util.Collections;
import java.util.List;
/**
* This is used instead of filtering from cache.
* Todo : need to implement proper pagination support on retrieving policies.
*/
public class PolicyFilteringUtil {
/**
* This is used to filter from the cached policies.
*/
public static List<Policy> getPolicies(List<Policy> sourceList, int offset, int limit) {
if(sourceList == null || sourceList.size() < offset){
return Collections.emptyList();
}
return sourceList.subList(offset, Math.min(offset + limit, sourceList.size()));
}
}

@ -21,7 +21,9 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -245,4 +247,12 @@ public class RequestValidationUtil {
} }
} }
public static void validateCredentials(OldPasswordResetWrapper credentials) {
if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Old or New password " +
"fields cannot be empty").build());
}
}
} }

@ -18,15 +18,20 @@
package org.wso2.carbon.device.mgt.jaxrs.util; package org.wso2.carbon.device.mgt.jaxrs.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
/** /**
* This class builds Credential modification related Responses * This class builds Credential modification related Responses
@ -34,55 +39,101 @@ import java.io.UnsupportedEncodingException;
public class CredentialManagementResponseBuilder { public class CredentialManagementResponseBuilder {
private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class); private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class);
private static String PASSWORD_VALIDATION_REGEX_TAG = "PasswordJavaRegEx";
private static String PASSWORD_VALIDATION_ERROR_MSG_TAG = "PasswordJavaRegExViolationErrorMsg";
/** /**
* Builds the response to change the password of a user * Builds the response to change the password of a user
* @param username - Username of the user.
* @param credentials - User credentials * @param credentials - User credentials
* @return Response Object * @return Response Object
*/ */
public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) { public static Response buildChangePasswordResponse(String username, OldPasswordResetWrapper credentials) {
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); if (!userStoreManager.isExistingUser(username)) {
byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword()); throw new InputValidationException(
userStoreManager.updateCredential(credentials.getUsername(), new String( new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username "
decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8")); + username).build());
}
RequestValidationUtil.validateCredentials(credentials);
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build());
}
userStoreManager.updateCredential(username, credentials.getNewPassword(),
credentials.getOldPassword());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " + return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
credentials.getUsername() + " was successfully changed.").build(); username + " was successfully changed.").build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.BAD_REQUEST).entity("Old password does not match.").build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(e.getMessage()).build());
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + String msg = "Could not change the password of the user: " + username +
". The Character Encoding is not supported."; ". The Character Encoding is not supported.";
log.error(errorMsg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
/** /**
* Builds the response to reset the password of a user * Builds the response to reset the password of a user
* @param username - Username of the user.
* @param credentials - User credentials * @param credentials - User credentials
* @return Response Object * @return Response Object
*/ */
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) { public static Response buildResetPasswordResponse(String username, PasswordResetWrapper credentials) {
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); if (!userStoreManager.isExistingUser(username)) {
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( throw new InputValidationException(
decodedNewPassword, "UTF-8")); new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username "
return Response.status(Response.Status.CREATED).entity("UserImpl password by username: " + + username).build());
credentials.getUsername() + " was successfully changed.").build(); }
if (credentials == null || credentials.getNewPassword() == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Password cannot be empty."
+ username).build());
}
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build());
}
userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
username + " was successfully changed.").build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "ErrorResponse occurred while updating the credentials of user '" + credentials.getUsername() + "'"; String msg = "ErrorResponse occurred while updating the credentials of user '" + username + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
String msg = "Could not change the password of the user: " + credentials.getUsername() + String msg = "Could not change the password of the user: " + username +
". The Character Encoding is not supported."; ". The Character Encoding is not supported.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
private static boolean validateCredential(String password)
throws UserStoreException, UnsupportedEncodingException {
String passwordValidationRegex = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_REGEX_TAG);
if (passwordValidationRegex != null) {
Pattern pattern = Pattern.compile(passwordValidationRegex);
if (pattern.matcher(password).matches()) {
return true;
}
} }
return false;
} }
} }

@ -20,14 +20,13 @@ package org.wso2.carbon.device.mgt.jaxrs.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@ -131,6 +130,18 @@ public class DeviceMgtAPIUtils {
return userStoreManager; return userStoreManager;
} }
public static RealmService getRealmService() throws UserStoreException {
RealmService realmService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return realmService;
}
/** /**
* Getting the current tenant's user realm * Getting the current tenant's user realm
*/ */
@ -237,4 +248,17 @@ public class DeviceMgtAPIUtils {
return gadgetDataService; return gadgetDataService;
} }
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
RealmService realmService =
(RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
if (realmService == null) {
throw new IllegalStateException("");
}
try {
return realmService.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new DeviceManagementException("");
}
}
} }

@ -728,7 +728,7 @@
<Permission> <Permission>
<name>Remove policy</name> <name>Remove policy</name>
<path>/device-mgt/admin/policies/remove</path> <path>/device-mgt/admin/policies/remove</path>
<url>/policies/bulk-remove</url> <url>/policies/remove-policy</url>
<method>POST</method> <method>POST</method>
</Permission> </Permission>

@ -259,7 +259,7 @@ public interface DeviceDAO {
* @return returns list of devices. * @return returns list of devices.
* @throws DeviceManagementDAOException * @throws DeviceManagementDAOException
*/ */
List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve devices of a given device name as a paginated result. * This method is used to retrieve devices of a given device name as a paginated result.

@ -628,7 +628,18 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
* @throws DeviceManagementDAOException * @throws DeviceManagementDAOException
*/ */
@Override @Override
public List<Device> getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException { public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
@ -638,13 +649,26 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + 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, " + "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.NAME, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " +
"d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString +
"WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; ") d1 WHERE d1.ID = e.DEVICE_ID LIMIT ?, ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceName + "%"); stmt.setInt(1, tenantId);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId); int i = 1;
if (deviceName != null && !deviceName.isEmpty()) {
stmt.setString(++i, deviceName + "%");
}
if (type != null && !type.isEmpty()) {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
while (rs.next()) { while (rs.next()) {

@ -139,7 +139,7 @@ public interface DeviceManagementProviderService {
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the * @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* device list * device list
*/ */
List<Device> getDevicesByName(String deviceName) throws DeviceManagementException; List<Device> getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException;
/** /**
* This method is used to retrieve list of devices that matches with the given device name with paging information. * This method is used to retrieve list of devices that matches with the given device name with paging information.

@ -31,11 +31,7 @@ import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.*;
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.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
@ -50,13 +46,7 @@ import org.wso2.carbon.email.sender.core.TypedValue;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService,
PluginInitializationListener { PluginInitializationListener {
@ -1062,12 +1052,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public List<Device> getDevicesByName(String deviceName) throws DeviceManagementException { public List<Device> getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
List<Device> allDevices; List<Device> allDevices;
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesByName(deviceName, this.getTenantId()); allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '" throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '"
+ deviceName + "'", e); + deviceName + "'", e);
@ -1240,7 +1230,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return CarbonContext.getThreadLocalCarbonContext().getTenantId(); return CarbonContext.getThreadLocalCarbonContext().getTenantId();
} }
// private int getTenantId(String tenantDomain) throws DeviceManagementException {
// RealmService realmService =
// (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
// if (realmService == null) {
// throw new IllegalStateException("");
// }
// try {
// return realmService.getTenantManager().getTenantId(tenantDomain);
// } catch (UserStoreException e) {
// throw new DeviceManagementException("");
// }
// }
private DeviceManager getDeviceManager(String deviceType) { private DeviceManager getDeviceManager(String deviceType) {
DeviceManagementService deviceManagementService = DeviceManagementService deviceManagementService =
pluginRepository.getDeviceManagementService(deviceType, this.getTenantId()); pluginRepository.getDeviceManagementService(deviceType, this.getTenantId());
if (deviceManagementService == null) { if (deviceManagementService == null) {

Loading…
Cancel
Save