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

revert-70aa11f8
dilanua 9 years ago
commit 4a74ea8100

@ -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);

@ -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;
}
}

@ -0,0 +1,106 @@
/*
* 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 {
private int count;
private String next;
private String previous;
private List<UserWrapper> users = new ArrayList<>();
/**
* Number of Devices returned.
*/
@ApiModelProperty(value = "Number of users returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
/**
**/
@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(count).append(",\n");
sb.append(" next: ").append(next).append(",\n");
sb.append(" previous: ").append(previous).append(",\n");
sb.append(" users: [").append(users).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -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"),
@ -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;
@ -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);
} }

@ -26,7 +26,8 @@ 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.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.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
@ -142,10 +143,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);
@ -329,10 +330,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,12 +349,24 @@ 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(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
@ -390,8 +408,8 @@ public class UserManagementServiceImpl implements UserManagementService {
@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);
} }
} }

@ -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 resetPassword(@PathParam("username") String user, PasswordResetWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials);
} }
} }

@ -18,15 +18,16 @@
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.PasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
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,26 +35,40 @@ 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()); return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username "
userStoreManager.updateCredential(credentials.getUsername(), new String( + username).build();
decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8")); }
if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.")
.build();
}
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
return Response.status(Response.Status.BAD_REQUEST).entity(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(); return Response.status(Response.Status.BAD_REQUEST).entity("Old password does not match.").build();
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + String errorMsg = "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(errorMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
@ -62,27 +77,52 @@ public class CredentialManagementResponseBuilder {
/** /**
* 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( return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username "
decodedNewPassword, "UTF-8")); + username).build();
return Response.status(Response.Status.CREATED).entity("UserImpl password by username: " + }
credentials.getUsername() + " was successfully changed.").build(); if (credentials == null || credentials.getNewPassword() == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.")
.build();
}
if (!validateCredential(credentials.getNewPassword())) {
String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration()
.getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG);
return Response.status(Response.Status.BAD_REQUEST).entity(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(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(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(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(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;
}
} }

@ -130,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
*/ */

Loading…
Cancel
Save