Improving UserManagement and RoleManagement API implementations to return proper error codes when no role/user exists, etc

revert-70aa11f8
prabathabey 9 years ago
parent 0c54753b34
commit 4236744d39

@ -22,9 +22,9 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ApiModel(value = "RoleWrapper", description = "Role details including permission and the users in the roles are " +
@ApiModel(value = "RoleInfo", description = "Role details including permission and the users in the roles are " +
"wrapped here.")
public class RoleWrapper {
public class RoleInfo {
@ApiModelProperty(name = "roleName", value = "The name of the role.", required = true)
private String roleName;

@ -603,7 +603,4 @@ public interface DeviceManagementService {
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
@GET
@Path("/types")
Response getDeviceTypes();
}

@ -21,10 +21,9 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
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.RoleInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import javax.ws.rs.*;
@ -70,16 +69,12 @@ public interface RoleManagementService {
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.",
message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-view", permissions = {
@ -157,11 +152,12 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
message = "Not Found. \n Role does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.",
@ -187,14 +183,14 @@ public interface RoleManagementService {
httpMethod = "GET",
value = "Get details of a role.",
notes = "If you wish to get the details of a role in EMM, you can do so using this REST API.",
response = RoleWrapper.class,
response = RoleInfo.class,
tags = "Role Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = RoleWrapper.class,
response = RoleInfo.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
@ -218,14 +214,15 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
message = "Not Found. \n Role does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the " +
message = "Internal Server Error. \n Server error occurred while fetching the " +
"requested role.",
response = ErrorResponse.class)
})
@ -282,11 +279,11 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while adding a new role.",
message = "Internal Server Error. \n Server error occurred while adding a new role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"})
@ -294,7 +291,7 @@ public interface RoleManagementService {
@ApiParam(
name = "role",
value = "Details about the role to be added.",
required = true) RoleWrapper role);
required = true) RoleInfo role);
@PUT
@Path("/{roleName}")
@ -331,14 +328,15 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Role to be deleted does not exist.",
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while updating the role.",
message = "Internal Server Error. \n Server error occurred while updating the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"})
@ -351,7 +349,7 @@ public interface RoleManagementService {
@ApiParam(
name = "role",
value = "Details about the role to be added.",
required = true) RoleWrapper role);
required = true) RoleInfo role);
@DELETE
@Path("/{roleName}")
@ -371,11 +369,11 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Role to be deleted does not exist.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while removing the role.",
message = "Internal Server Error. \n Server error occurred while removing the role.",
response = ErrorResponse.class)
})
@Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"})
@ -426,13 +424,16 @@ public interface RoleManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
message = "Internal Server Error. \n " +
"Server error occurred while updating the user list of the role.",
response = ErrorResponse.class)
})

@ -64,34 +64,29 @@ public interface UserManagementService {
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n Source can be retrieved from the URL specified at the Location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 409,
message = "Conflict. \n User already exist.",
message = "Conflict. \n User already exists.",
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while adding a new user.",
message = "Internal Server Error. \n Server error occurred while adding a new user.",
response = ErrorResponse.class)
})
@Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"})
Response addUser(
@ApiParam(
name = "user",
value = "User related details.",
value = "Information of the user to be added",
required = true) UserInfo user);
@GET
@ -131,7 +126,8 @@ public interface UserManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while" +
@ -182,14 +178,16 @@ public interface UserManagementService {
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource does not exist.",
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
@ -272,7 +270,8 @@ public interface UserManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the role list" +
@ -296,7 +295,7 @@ public interface UserManagementService {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the requested role.",
response = UserInfoList.class,
response = BasicUserInfoList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
@ -315,7 +314,8 @@ public interface UserManagementService {
message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.",
@ -380,7 +380,8 @@ public interface UserManagementService {
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
message = "Not Acceptable.\n The requested media type is not supported",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the username " +
@ -429,10 +430,12 @@ public interface UserManagementService {
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
message = "Not Found. \n Resource to be deleted does not exist.",
response = ErrorResponse.class),
@ApiResponse(
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.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +

@ -314,18 +314,4 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
}
@Override
public Response getDeviceTypes() {
List<DeviceType> deviceTypes;
try {
deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().
setCode(500l).setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity(deviceTypes).build();
}
}

@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo;
import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException;
@ -30,7 +31,6 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
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.beans.RoleWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.mgt.UserRealmProxy;
@ -40,6 +40,8 @@ import org.wso2.carbon.user.mgt.common.UserAdminException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -49,6 +51,7 @@ import java.util.List;
@Consumes(MediaType.APPLICATION_JSON)
public class RoleManagementServiceImpl implements RoleManagementService {
private static final String API_BASE_PATH = "/roles";
private static final Log log = LogFactory.getLog(RoleManagementServiceImpl.class);
@GET
@ -61,18 +64,14 @@ public class RoleManagementServiceImpl implements RoleManagementService {
List<String> filteredRoles;
RoleList targetRoles = new RoleList();
try {
//Get the total role count that matches the given filter
filteredRoles = getRolesFromUserStore(filter);
if (filteredRoles == null || filteredRoles.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found.").build());
}
targetRoles.setCount(filteredRoles.size());
filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(filter), offset, limit);
if (filteredRoles.size() == 0) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found").build());
}
targetRoles.setList(filteredRoles);
Response.ok().entity(targetRoles).build();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving roles from the underlying user stores";
log.error(msg, e);
@ -91,17 +90,16 @@ public class RoleManagementServiceImpl implements RoleManagementService {
RequestValidationUtil.validateRoleName(roleName);
try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
final UIPermissionNode rolePermissions;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
if (!userRealm.getUserStoreManager().isExistingRole(roleName)) {
throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage(
"No role exists with the name '" + roleName + "'").build());
}
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
rolePermissions = this.getUIPermissionNode(roleName, userRealmProxy);
final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm);
if (rolePermissions == null) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No permissions found" +
" for the role '" + roleName + "'").build());
if (log.isDebugEnabled()) {
log.debug("No permissions found for the role '" + roleName + "'");
}
}
return Response.status(Response.Status.OK).entity(rolePermissions).build();
} catch (UserAdminException e) {
@ -118,8 +116,13 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
}
private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy)
private UIPermissionNode getUIPermissionNode(String roleName, UserRealm userRealm)
throws UserAdminException {
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
}
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
final UIPermissionNode rolePermissions =
userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2];
@ -144,42 +147,35 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@Override
public Response getRole(@PathParam("roleName") String roleName,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
RequestValidationUtil.validateRoleName(roleName);
RoleWrapper roleWrapper = new RoleWrapper();
RoleInfo roleInfo = new RoleInfo();
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
}
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
if (userStoreManager.isExistingRole(roleName)) {
roleWrapper.setRoleName(roleName);
roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName));
// Get the permission nodes and hand picking only device management and login perms
final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
List<String> permList = new ArrayList<>();
this.iteratePermissions(rolePermissions, permList);
roleWrapper.setPermissionList(rolePermissions);
String[] permListAr = new String[permList.size()];
roleWrapper.setPermissions(permList.toArray(permListAr));
} else {
if (!userStoreManager.isExistingRole(roleName)) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Role name doesn't exist.")
.build());
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build());
}
roleInfo.setRoleName(roleName);
roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName));
// Get the permission nodes and hand picking only device management and login perms
final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm);
List<String> permList = new ArrayList<>();
this.iteratePermissions(rolePermissions, permList);
roleInfo.setPermissionList(rolePermissions);
String[] permListAr = new String[permList.size()];
roleInfo.setPermissions(permList.toArray(permListAr));
} catch (UserStoreException | UserAdminException e) {
String msg = "Error occurred while retrieving the user role '" + roleName + "'";
log.error(msg, e);
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(roleInfo).build();
}
private List<String> iteratePermissions(UIPermissionNode uiPermissionNode, List<String> list) {
@ -194,78 +190,94 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@POST
@Override
public Response addRole(RoleWrapper roleWrapper) {
RequestValidationUtil.validateRoleDetails(roleWrapper);
RequestValidationUtil.validateRoleName(roleWrapper.getRoleName());
public Response addRole(RoleInfo roleInfo) {
RequestValidationUtil.validateRoleDetails(roleInfo);
RequestValidationUtil.validateRoleName(roleInfo.getRoleName());
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Persisting the role to user store");
log.debug("Persisting the role in the underlying user store");
}
Permission[] permissions = null;
if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) {
permissions = new Permission[roleWrapper.getPermissions().length];
if (roleInfo.getPermissions() != null && roleInfo.getPermissions().length > 0) {
permissions = new Permission[roleInfo.getPermissions().length];
for (int i = 0; i < permissions.length; i++) {
String permission = roleWrapper.getPermissions()[i];
String permission = roleInfo.getPermissions()[i];
permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION);
}
}
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions);
//TODO fix what's returned in the entity
return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity(
"Role '" + roleInfo.getRoleName() + "' has " +
"successfully been added").build();
} catch (UserStoreException e) {
String msg = "Error occurred while adding role '" + roleWrapper.getRoleName() + "'";
String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
} catch (URISyntaxException e) {
String msg = "Error occurred while composing the URI at which the information of the newly created role " +
"can be retrieved";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been added").build();
}
@PUT
@Path("/{roleName}")
@Override
public Response updateRole(@PathParam("roleName") String roleName, RoleWrapper roleWrapper) {
public Response updateRole(@PathParam("roleName") String roleName, RoleInfo roleInfo) {
RequestValidationUtil.validateRoleName(roleName);
RequestValidationUtil.validateRoleDetails(roleWrapper);
String newRoleName = roleWrapper.getRoleName();
RequestValidationUtil.validateRoleDetails(roleInfo);
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build());
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();
if (log.isDebugEnabled()) {
log.debug("Updating the role to user store");
}
String newRoleName = roleInfo.getRoleName();
if (newRoleName != null && !roleName.equals(newRoleName)) {
userStoreManager.updateRoleName(roleName, newRoleName);
}
if (roleWrapper.getUsers() != null) {
if (roleInfo.getUsers() != null) {
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)),
Arrays.asList(roleWrapper.getUsers()));
Arrays.asList(roleInfo.getUsers()));
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
.getObjectsToAdd().size()]);
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
.getObjectsToRemove().size()]);
userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd);
}
if (roleWrapper.getPermissions() != null) {
if (roleInfo.getPermissions() != null) {
// Delete all authorizations for the current role before authorizing the permission tree
authorizationManager.clearRoleAuthorization(roleName);
if (roleWrapper.getPermissions().length > 0) {
for (int i = 0; i < roleWrapper.getPermissions().length; i++) {
String permission = roleWrapper.getPermissions()[i];
if (roleInfo.getPermissions().length > 0) {
for (int i = 0; i < roleInfo.getPermissions().length; i++) {
String permission = roleInfo.getPermissions()[i];
authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION);
}
}
}
//TODO: Need to send the updated role information in the entity back to the client
return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " +
"successfully been updated").build();
} catch (UserStoreException e) {
String msg = "Error occurred while updating role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " +
"successfully been updated").build();
}
@DELETE
@ -274,8 +286,15 @@ public class RoleManagementServiceImpl implements RoleManagementService {
public Response deleteRole(@PathParam("roleName") String roleName) {
RequestValidationUtil.validateRoleName(roleName);
try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build());
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();
if (log.isDebugEnabled()) {
log.debug("Deleting the role in user store");
}
@ -285,11 +304,9 @@ public class RoleManagementServiceImpl implements RoleManagementService {
} catch (UserStoreException e) {
String msg = "Error occurred while deleting the role '" + roleName + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been deleted").build();
return Response.status(Response.Status.OK).build();
}
@PUT
@ -325,7 +342,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
private List<String> getRolesFromUserStore(String filter) throws UserStoreException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] roles;
boolean filterRolesByName = ((filter == null) || filter.isEmpty() ? false : true);
boolean filterRolesByName = (!((filter == null) || filter.isEmpty()));
if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles");
}
@ -334,10 +351,10 @@ public class RoleManagementServiceImpl implements RoleManagementService {
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith("Application/"))) {
if(!filterRolesByName) {
if (!filterRolesByName) {
filteredRoles.add(role);
} else{
if(role.contains(filter)){
} else {
if (role.contains(filter)) {
filteredRoles.add(role);
}
}

@ -39,6 +39,8 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
@Path("/users")
@ -47,117 +49,58 @@ import java.util.*;
public class UserManagementServiceImpl implements UserManagementService {
private static final String ROLE_EVERYONE = "Internal/everyone";
private static final String API_BASE_PATH = "/users";
private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class);
@POST
@Override
public Response addUser(UserInfo userWrapper) {
public Response addUser(UserInfo userInfo) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
if (userStoreManager.isExistingUser(userInfo.getUsername())) {
// if user already exists
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
log.debug("User by username: " + userInfo.getUsername() +
" already exists. Therefore, request made to add user was refused.");
}
// returning response with bad request state
throw new ConflictException(
new ErrorResponse.ErrorResponseBuilder().setCode(409l).setMessage("User by username: " +
userWrapper.getUsername() + " already exists. Therefore, request made to add user " +
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
userInfo.getUsername() + " already exists. Therefore, request made to add user " +
"was refused.").build());
} else {
String initialUserPassword = this.generateInitialUserPassword();
Map<String, String> defaultUserClaims =
this.buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
userWrapper.getEmailAddress());
// calling addUser method of carbon user api
userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword,
userWrapper.getRoles(), defaultUserClaims, null);
// invite newly added user to enroll device
this.inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User '" + userWrapper.getUsername() + "' has successfully been added.");
}
// returning response with success state
return Response.status(Response.Status.CREATED).entity("User by username: " + userWrapper.getUsername() +
" was successfully added.").build();
}
} catch (UserStoreException e) {
String msg = "Exception in trying to add user '" + userWrapper.getUsername() + "' to the user store";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while inviting user to enroll the device";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
private Map<String, String> buildDefaultUserClaims(String firstname, String lastname, String emailAddress) {
Map<String, String> defaultUserClaims = new HashMap<>();
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname);
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname);
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
if (log.isDebugEnabled()) {
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
}
return defaultUserClaims;
}
String initialUserPassword = this.generateInitialUserPassword();
Map<String, String> defaultUserClaims =
this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(),
userInfo.getEmailAddress());
// calling addUser method of carbon user api
userStoreManager.addUser(userInfo.getUsername(), initialUserPassword,
userInfo.getRoles(), defaultUserClaims, null);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User '" + userInfo.getUsername() + "' has successfully been added.");
}
private String generateInitialUserPassword() {
int passwordLength = 6;
//defining the pool of characters to be used for initial password generation
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numericCharset = "0123456789";
Random randomGenerator = new Random();
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
int totalCharsetLength = totalCharset.length();
StringBuilder initialUserPassword = new StringBuilder();
for (int i = 0; i < passwordLength; i++) {
initialUserPassword
.append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
}
if (log.isDebugEnabled()) {
log.debug("Initial user password is created for new user: " + initialUserPassword);
}
return initialUserPassword.toString();
}
BasicUserInfo createdUserInfo = this.getBasicUserInfo(userInfo.getUsername());
// Outputting debug message upon successful retrieval of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userInfo.getUsername() + " was found.");
}
return Response.created(new URI(API_BASE_PATH + "/" + userInfo.getUsername())).entity(
createdUserInfo).build();
private void inviteNewlyAddedUserToEnrollDevice(String username,
String password) throws DeviceManagementException, UserStoreException {
if (log.isDebugEnabled()) {
log.debug("Sending invitation mail to user by username: " + username);
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
tenantDomain = "";
}
if (!username.contains("/")) {
username = "/" + username;
} catch (UserStoreException e) {
String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " +
"underlying user management system";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
} catch (URISyntaxException e) {
String msg = "Error occurred while composing the location URI, which represents information of the " +
"newly created user '" + userInfo.getUsername() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
String[] usernameBits = username.split("/");
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
Properties props = new Properties();
props.setProperty("username", usernameBits[1]);
props.setProperty("domain-name", tenantDomain);
props.setProperty("first-name", getClaimValue(usernameBits[1], Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("password", password);
String recipient = getClaimValue(usernameBits[1], Constants.USER_CLAIM_EMAIL_ADDRESS);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceManagementProviderService.sendRegistrationEmail(metaInfo);
}
private String getClaimValue(String username, String claimUri) throws UserStoreException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
return userStoreManager.getUserClaimValue(username, claimUri, null);
}
@GET
@ -167,91 +110,77 @@ public class UserManagementServiceImpl implements UserManagementService {
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
BasicUserInfo user = new BasicUserInfo();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
// Outputting debug message upon successful retrieval of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was found.");
}
return Response.status(Response.Status.OK).entity(user).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (!userStoreManager.isExistingUser(username)) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
// returning response with bad request state
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User doesn't exist.")
.build());
throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage(
"User doesn't exist.").build());
}
BasicUserInfo user = this.getBasicUserInfo(username);
return Response.status(Response.Status.OK).entity(user).build();
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'";
String msg = "Error occurred while retrieving information of the user '" + username + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@PUT
@Path("/{username}")
@Override
public Response updateUser(@PathParam("username") String username, UserInfo userWrapper) {
public Response updateUser(@PathParam("username") String username, UserInfo userInfo) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
Map<String, String> defaultUserClaims =
this.buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
userWrapper.getEmailAddress());
if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
// Decoding Base64 encoded password
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
userWrapper.getPassword());
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
}
List<String> currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername());
List<String> newRoles = Arrays.asList(userWrapper.getRoles());
List<String> rolesToAdd = new ArrayList<>(newRoles);
List<String> rolesToDelete = new ArrayList<>();
for (String role : currentRoles) {
if (newRoles.contains(role)) {
rolesToAdd.remove(role);
} else {
rolesToDelete.add(role);
}
}
rolesToDelete.remove(ROLE_EVERYONE);
userStoreManager.updateRoleListOfUser(userWrapper.getUsername(),
rolesToDelete.toArray(new String[rolesToDelete.size()]),
rolesToAdd.toArray(new String[rolesToAdd.size()]));
userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
}
// returning response with success state
return Response.status(Response.Status.CREATED).entity("User by username '" + userWrapper.getUsername() +
"' was successfully updated.").build();
} else {
if (!userStoreManager.isExistingUser(userInfo.getUsername())) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
log.debug("User by username: " + userInfo.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
}
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " +
userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user" +
" was refused.").build());
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
userInfo.getUsername() + " doesn't exist.").build());
}
Map<String, String> defaultUserClaims =
this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(),
userInfo.getEmailAddress());
if (StringUtils.isNotEmpty(userInfo.getPassword())) {
// Decoding Base64 encoded password
userStoreManager.updateCredentialByAdmin(userInfo.getUsername(),
userInfo.getPassword());
log.debug("User credential of username: " + userInfo.getUsername() + " has been changed");
}
List<String> currentRoles = this.getFilteredRoles(userStoreManager, userInfo.getUsername());
List<String> newRoles = Arrays.asList(userInfo.getRoles());
List<String> rolesToAdd = new ArrayList<>(newRoles);
List<String> rolesToDelete = new ArrayList<>();
for (String role : currentRoles) {
if (newRoles.contains(role)) {
rolesToAdd.remove(role);
} else {
rolesToDelete.add(role);
}
}
rolesToDelete.remove(ROLE_EVERYONE);
userStoreManager.updateRoleListOfUser(userInfo.getUsername(),
rolesToDelete.toArray(new String[rolesToDelete.size()]),
rolesToAdd.toArray(new String[rolesToAdd.size()]));
userStoreManager.setUserClaimValues(userInfo.getUsername(), defaultUserClaims, null);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userInfo.getUsername() + " was successfully updated.");
}
BasicUserInfo updatedUserInfo = this.getBasicUserInfo(username);
return Response.ok().entity(updatedUserInfo).build();
} catch (UserStoreException e) {
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
String msg = "Error occurred while trying to update user '" + userInfo.getUsername() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@ -277,31 +206,25 @@ public class UserManagementServiceImpl implements UserManagementService {
public Response removeUser(@PathParam("username") String username) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
// if user already exists, trying to remove user
userStoreManager.deleteUser(username);
// Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
// returning response with success state
return Response.status(Response.Status.OK).entity("User by username: " + username +
" was successfully removed.").build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (!userStoreManager.isExistingUser(username)) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
}
// returning response with bad request state
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " +
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
username + " does not exist for removal.").build());
}
userStoreManager.deleteUser(username);
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
return Response.status(Response.Status.OK).build();
} catch (UserStoreException e) {
String msg = "Exception in trying to remove user by username: " + username;
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@ -311,24 +234,22 @@ public class UserManagementServiceImpl implements UserManagementService {
public Response getRolesOfUser(@PathParam("username") String username) {
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) {
RoleList result = new RoleList();
result.setList(getFilteredRoles(userStoreManager, username));
return Response.status(Response.Status.OK).entity(result).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (!userStoreManager.isExistingUser(username)) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " + username +
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username +
" does not exist for role retrieval.").build());
}
RoleList result = new RoleList();
result.setList(getFilteredRoles(userStoreManager, username));
return Response.status(Response.Status.OK).entity(result).build();
} catch (UserStoreException e) {
String msg = "Exception in trying to retrieve roles for user by username: " + username;
String msg = "Error occurred while trying to retrieve roles of the user '" + username + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@ -342,7 +263,7 @@ public class UserManagementServiceImpl implements UserManagementService {
}
List<BasicUserInfo> userList, offsetList;
String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter);
int appliedLimit = (limit <= 0) ? -1 : (limit + offset);
int appliedLimit = (limit <= 0) ? -1 : (limit + offset);
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
@ -371,10 +292,9 @@ public class UserManagementServiceImpl implements UserManagementService {
return Response.status(Response.Status.OK).entity(result).build();
} catch (UserStoreException e) {
String msg = "ErrorResponse occurred while retrieving the list of users.";
String msg = "Error occurred while retrieving the list of users.";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@ -407,8 +327,7 @@ public class UserManagementServiceImpl implements UserManagementService {
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build());
}
}
@ -419,4 +338,49 @@ public class UserManagementServiceImpl implements UserManagementService {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(username, credentials);
}
private Map<String, String> buildDefaultUserClaims(String firstName, String lastName, String emailAddress) {
Map<String, String> defaultUserClaims = new HashMap<>();
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstName);
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastName);
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
if (log.isDebugEnabled()) {
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
}
return defaultUserClaims;
}
private String generateInitialUserPassword() {
int passwordLength = 6;
//defining the pool of characters to be used for initial password generation
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numericCharset = "0123456789";
Random randomGenerator = new Random();
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
int totalCharsetLength = totalCharset.length();
StringBuilder initialUserPassword = new StringBuilder();
for (int i = 0; i < passwordLength; i++) {
initialUserPassword.append(
totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
}
if (log.isDebugEnabled()) {
log.debug("Initial user password is created for new user: " + initialUserPassword);
}
return initialUserPassword.toString();
}
private BasicUserInfo getBasicUserInfo(String username) throws UserStoreException {
BasicUserInfo userInfo = new BasicUserInfo();
userInfo.setUsername(username);
userInfo.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
userInfo.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
userInfo.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
return userInfo;
}
private String getClaimValue(String username, String claimUri) throws UserStoreException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
return userStoreManager.getUserClaimValue(username, claimUri, null);
}
}

@ -304,8 +304,8 @@ public class RequestValidationUtil {
}
}
public static void validateRoleDetails(RoleWrapper roleWrapper) {
if (roleWrapper == null) {
public static void validateRoleDetails(RoleInfo roleInfo) {
if (roleInfo == null) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request body is incorrect or" +
" empty").build());

@ -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.swagger.extension;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.jaxrs.Reader;
import io.swagger.jaxrs.config.ReaderListener;
import io.swagger.models.Swagger;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import java.util.HashMap;
import java.util.Map;
@SwaggerDefinition(
basePath = "/api/device-mgt/v1.0",
host = "localhost:9443"
)
public class SecurityDefinitionConfigurator implements ReaderListener {
public static final String TOKEN_AUTH_SCHEME = "tokenAuthScheme";
@Override
public void beforeScan(Reader reader, Swagger swagger) {
}
@Override
public void afterScan(Reader reader, Swagger swagger) {
OAuth2Definition tokenScheme = new OAuth2Definition();
tokenScheme.setType("oauth2");
tokenScheme.setFlow("password");
tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth/token");
tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth/authorize");
Map<String, SecuritySchemeDefinition> schemes = new HashMap<>();
schemes.put(TOKEN_AUTH_SCHEME, tokenScheme);
swagger.setSecurityDefinitions(schemes);
}
}
Loading…
Cancel
Save