Search in sources :

Example 51 with User

use of org.gluu.oxtrust.model.scim2.User in project oxTrust by GluuFederation.

the class BulkWebService method processBulkOperations.

@POST
@Consumes({ Constants.MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ Constants.MEDIA_TYPE_SCIM_JSON + "; charset=utf-8", MediaType.APPLICATION_JSON + "; charset=utf-8" })
@HeaderParam("Accept")
@DefaultValue(Constants.MEDIA_TYPE_SCIM_JSON)
@ApiOperation(value = "Bulk Operations", notes = "Bulk Operations (https://tools.ietf.org/html/rfc7644#section-3.7)", response = BulkResponse.class)
public Response processBulkOperations(// @Context HttpServletResponse response,
@HeaderParam("Authorization") String authorization, @HeaderParam("Content-Length") int contentLength, @QueryParam(OxTrustConstants.QUERY_PARAMETER_TEST_MODE_OAUTH2_TOKEN) final String token, @ApiParam(value = "BulkRequest", required = true) BulkRequest bulkRequest) throws Exception {
    Response authorizationResponse;
    if (jsonConfigurationService.getOxTrustappConfiguration().isScimTestMode()) {
        log.info(" ##### SCIM Test Mode is ACTIVE");
        authorizationResponse = processTestModeAuthorization(token);
    } else {
        authorizationResponse = processAuthorization(authorization);
    }
    if (authorizationResponse != null) {
        return authorizationResponse;
    }
    try {
        /*
			 * J2EContext context = new J2EContext(request, response); int
			 * removePathLength = "/Bulk".length(); String domain =
			 * context.getFullRequestURL(); if (domain.endsWith("/")) {
			 * removePathLength++; } domain = domain.substring(0,
			 * domain.length() - removePathLength);
			 */
        log.info("##### Operation count = " + bulkRequest.getOperations().size());
        log.info("##### Content-Length = " + contentLength);
        if (bulkRequest.getOperations().size() > MAX_BULK_OPERATIONS || contentLength > MAX_BULK_PAYLOAD_SIZE) {
            StringBuilder message = new StringBuilder("The size of the bulk operation exceeds the ");
            if (bulkRequest.getOperations().size() > MAX_BULK_OPERATIONS && contentLength <= MAX_BULK_PAYLOAD_SIZE) {
                message.append("maxOperations (").append(MAX_BULK_OPERATIONS).append(")");
            } else if (bulkRequest.getOperations().size() <= MAX_BULK_OPERATIONS && contentLength > MAX_BULK_PAYLOAD_SIZE) {
                message.append("maxPayloadSize (").append(MAX_BULK_PAYLOAD_SIZE).append(")");
            } else if (bulkRequest.getOperations().size() > MAX_BULK_OPERATIONS && contentLength > MAX_BULK_PAYLOAD_SIZE) {
                message.append("maxOperations (").append(MAX_BULK_OPERATIONS).append(") ");
                message.append("and ");
                message.append("maxPayloadSize (").append(MAX_BULK_PAYLOAD_SIZE).append(")");
            }
            log.info("Payload Too Large: " + message.toString());
            return getErrorResponse(413, message.toString());
        }
        int failOnErrorsLimit = (bulkRequest.getFailOnErrors() != null) ? bulkRequest.getFailOnErrors() : 0;
        int failOnErrorsCount = 0;
        List<BulkOperation> bulkOperations = bulkRequest.getOperations();
        BulkResponse bulkResponse = new BulkResponse();
        Map<String, String> processedBulkIds = new LinkedHashMap<String, String>();
        operationsLoop: for (BulkOperation operation : bulkOperations) {
            log.info(" Checking operations... ");
            if (operation.getPath().startsWith("/Users")) {
                // operation = processUserOperation(operation, domain);
                operation = processUserOperation(operation, processedBulkIds);
            } else if (operation.getPath().startsWith("/Groups")) {
                // operation = processGroupOperation(operation, domain);
                operation = processGroupOperation(operation, processedBulkIds);
            }
            bulkResponse.getOperations().add(operation);
            // Error handling
            String okCode = String.valueOf(Response.Status.OK.getStatusCode());
            String createdCode = String.valueOf(Response.Status.CREATED.getStatusCode());
            if (!operation.getStatus().equalsIgnoreCase(okCode) && !operation.getStatus().equalsIgnoreCase(createdCode)) {
                failOnErrorsCount++;
                if ((failOnErrorsLimit > 0) && (failOnErrorsCount >= failOnErrorsLimit)) {
                    break operationsLoop;
                }
            }
        }
        URI location = new URI(appConfiguration.getBaseEndpoint() + "/scim/v2/Bulk");
        // Serialize to JSON
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
        SimpleModule customBulkOperationsModule = new SimpleModule("CustomBulkOperationsModule", new Version(1, 0, 0, ""));
        // Custom serializers for both User and Group
        ListResponseUserSerializer userSerializer = new ListResponseUserSerializer();
        ListResponseGroupSerializer groupSerializer = new ListResponseGroupSerializer();
        customBulkOperationsModule.addSerializer(User.class, userSerializer);
        customBulkOperationsModule.addSerializer(Group.class, groupSerializer);
        mapper.registerModule(customBulkOperationsModule);
        String json = mapper.writeValueAsString(bulkResponse);
        return Response.ok(json).location(location).build();
    } catch (Exception ex) {
        log.error("Error in processBulkOperations", ex);
        ex.printStackTrace();
        return getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR_MESSAGE);
    }
}
Also used : ListResponseUserSerializer(org.gluu.oxtrust.service.antlr.scimFilter.util.ListResponseUserSerializer) BulkOperation(org.gluu.oxtrust.model.scim2.BulkOperation) BulkResponse(org.gluu.oxtrust.model.scim2.BulkResponse) URI(java.net.URI) PersonRequiredFieldsException(org.gluu.oxtrust.exception.PersonRequiredFieldsException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) DuplicateEntryException(org.gluu.site.ldap.exception.DuplicateEntryException) LinkedHashMap(java.util.LinkedHashMap) Response(javax.ws.rs.core.Response) BulkResponse(org.gluu.oxtrust.model.scim2.BulkResponse) ErrorResponse(org.gluu.oxtrust.model.scim2.ErrorResponse) Version(org.codehaus.jackson.Version) ListResponseGroupSerializer(org.gluu.oxtrust.service.antlr.scimFilter.util.ListResponseGroupSerializer) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) SimpleModule(org.codehaus.jackson.map.module.SimpleModule) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(com.wordnik.swagger.annotations.ApiOperation)

Example 52 with User

use of org.gluu.oxtrust.model.scim2.User in project oxTrust by GluuFederation.

the class BaseScimWebService method processAuthorization.

protected Response processAuthorization(String authorization) throws Exception {
    boolean authorized = getAuthorizedUser();
    if (!authorized) {
        if (!scimUmaProtectionService.isEnabled()) {
            log.info("UMA authentication is disabled");
            return getErrorResponse(Response.Status.FORBIDDEN, "User isn't authorized");
        }
        Token patToken = scimUmaProtectionService.getPatToken();
        Pair<Boolean, Response> rptTokenValidationResult = umaPermissionService.validateRptToken(patToken, authorization, scimUmaProtectionService.getUmaResourceId(), scimUmaProtectionService.getUmaScope());
        if (rptTokenValidationResult.getFirst()) {
            if (rptTokenValidationResult.getSecond() != null) {
                return rptTokenValidationResult.getSecond();
            }
        } else {
            return getErrorResponse(Response.Status.FORBIDDEN, "User isn't authorized");
        }
    }
    return null;
}
Also used : VirtualListViewResponse(org.xdi.ldap.model.VirtualListViewResponse) Response(javax.ws.rs.core.Response) ErrorResponse(org.gluu.oxtrust.model.scim2.ErrorResponse) Token(org.xdi.oxauth.model.uma.wrapper.Token) GluuBoolean(org.xdi.ldap.model.GluuBoolean)

Example 53 with User

use of org.gluu.oxtrust.model.scim2.User in project oxTrust by GluuFederation.

the class Scim2UserService method transferAttributesToUserResource.

public void transferAttributesToUserResource(GluuCustomPerson person, UserResource res, String url) {
    log.debug("transferAttributesToUserResource");
    res.setId(person.getInum());
    res.setExternalId(person.getAttribute("oxTrustExternalId"));
    Meta meta = new Meta();
    meta.setResourceType(ScimResourceUtil.getType(res.getClass()));
    meta.setCreated(person.getAttribute("oxTrustMetaCreated"));
    if (meta.getCreated() == null) {
        Date tmpDate = person.getCreationDate();
        meta.setCreated(tmpDate == null ? null : ISODateTimeFormat.dateTime().withZoneUTC().print(tmpDate.getTime()));
    }
    meta.setLastModified(person.getAttribute("oxTrustMetaLastModified"));
    if (meta.getLastModified() == null) {
        Date tmpDate = person.getUpdatedAt();
        meta.setLastModified(tmpDate == null ? null : ISODateTimeFormat.dateTime().withZoneUTC().print(tmpDate.getTime()));
    }
    meta.setLocation(person.getAttribute("oxTrustMetaLocation"));
    if (meta.getLocation() == null)
        meta.setLocation(url + "/" + person.getInum());
    res.setMeta(meta);
    // Set values in order of appearance in UserResource class
    res.setUserName(person.getUid());
    Name name = new Name();
    name.setGivenName(person.getGivenName());
    name.setFamilyName(person.getSurname());
    name.setMiddleName(person.getAttribute("middleName"));
    name.setHonorificPrefix(person.getAttribute("oxTrusthonorificPrefix"));
    name.setHonorificSuffix(person.getAttribute("oxTrusthonorificSuffix"));
    String formatted = person.getAttribute("oxTrustNameFormatted");
    if (// recomputes the formatted name if absent in LDAP
    formatted == null)
        name.computeFormattedName();
    else
        name.setFormatted(formatted);
    res.setName(name);
    res.setDisplayName(person.getDisplayName());
    res.setNickName(person.getAttribute("nickname"));
    res.setProfileUrl(person.getAttribute("oxTrustProfileURL"));
    res.setTitle(person.getAttribute("oxTrustTitle"));
    res.setUserType(person.getAttribute("oxTrustUserType"));
    res.setPreferredLanguage(person.getPreferredLanguage());
    res.setLocale(person.getAttribute("locale"));
    res.setTimezone(person.getTimezone());
    res.setActive(Boolean.valueOf(person.getAttribute("oxTrustActive")) || GluuBoolean.getByValue(person.getAttribute("gluuStatus")).isBooleanValue());
    res.setPassword(person.getUserPassword());
    res.setEmails(getAttributeListValue(person, Email.class, "oxTrustEmail"));
    res.setPhoneNumbers(getAttributeListValue(person, PhoneNumber.class, "oxTrustPhoneValue"));
    res.setIms(getAttributeListValue(person, InstantMessagingAddress.class, "oxTrustImsValue"));
    res.setPhotos(getAttributeListValue(person, Photo.class, "oxTrustPhotos"));
    res.setAddresses(getAttributeListValue(person, Address.class, "oxTrustAddresses"));
    List<String> listOfGroups = person.getMemberOf();
    if (listOfGroups != null && listOfGroups.size() > 0) {
        List<Group> groupList = new ArrayList<Group>();
        for (String groupDN : listOfGroups) {
            try {
                GluuGroup gluuGroup = groupService.getGroupByDn(groupDN);
                Group group = new Group();
                group.setValue(gluuGroup.getInum());
                String reference = groupWS.getEndpointUrl() + "/" + gluuGroup.getInum();
                group.setRef(reference);
                group.setDisplay(gluuGroup.getDisplayName());
                // Only support direct membership: see section 4.1.2 of RFC 7644
                group.setType(Group.Type.DIRECT);
                groupList.add(group);
            } catch (Exception e) {
                log.warn("transferAttributesToUserResource. Group with dn {} could not be added to User Resource. {}", groupDN, person.getUid());
                log.error(e.getMessage(), e);
            }
        }
        if (groupList.size() > 0)
            res.setGroups(groupList);
    }
    res.setEntitlements(getAttributeListValue(person, Entitlement.class, "oxTrustEntitlements"));
    res.setRoles(getAttributeListValue(person, Role.class, "oxTrustRole"));
    res.setX509Certificates(getAttributeListValue(person, X509Certificate.class, "oxTrustx509Certificate"));
    res.setPairwiseIdentitifers(person.getOxPPID());
    transferExtendedAttributesToResource(person, res);
}
Also used : Meta(org.gluu.oxtrust.model.scim2.Meta) GluuGroup(org.gluu.oxtrust.model.GluuGroup) Group(org.gluu.oxtrust.model.scim2.user.Group) Email(org.gluu.oxtrust.model.scim2.user.Email) Address(org.gluu.oxtrust.model.scim2.user.Address) InstantMessagingAddress(org.gluu.oxtrust.model.scim2.user.InstantMessagingAddress) ArrayList(java.util.ArrayList) Photo(org.gluu.oxtrust.model.scim2.user.Photo) GluuGroup(org.gluu.oxtrust.model.GluuGroup) Date(java.util.Date) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) WebApplicationException(javax.ws.rs.WebApplicationException) X509Certificate(org.gluu.oxtrust.model.scim2.user.X509Certificate) Name(org.gluu.oxtrust.model.scim2.user.Name) Role(org.gluu.oxtrust.model.scim2.user.Role) PhoneNumber(org.gluu.oxtrust.model.scim2.user.PhoneNumber) Entitlement(org.gluu.oxtrust.model.scim2.user.Entitlement) InstantMessagingAddress(org.gluu.oxtrust.model.scim2.user.InstantMessagingAddress)

Example 54 with User

use of org.gluu.oxtrust.model.scim2.User in project oxTrust by GluuFederation.

the class BaseScimWebService method assignMetaInformation.

protected void assignMetaInformation(BaseScimResource resource) {
    // Generate some meta information (this replaces the info client passed in the request)
    long now = new Date().getTime();
    String val = ISODateTimeFormat.dateTime().withZoneUTC().print(now);
    Meta meta = new Meta();
    meta.setResourceType(ScimResourceUtil.getType(resource.getClass()));
    meta.setCreated(val);
    meta.setLastModified(val);
    // For version attritute: Service provider support for this attribute is optional and subject to the service provider's support for versioning
    // For location attribute: this will be set after current user creation in LDAP
    resource.setMeta(meta);
}
Also used : Meta(org.gluu.oxtrust.model.scim2.Meta) Date(java.util.Date)

Example 55 with User

use of org.gluu.oxtrust.model.scim2.User in project oxTrust by GluuFederation.

the class BulkWebService method execute.

private Pair<Response, String> execute(Verb verb, BaseScimWebService ws, String data, String fragment) {
    Response response = null;
    String idCreated = null;
    try {
        if (ws == userWS)
            switch(verb) {
                case PUT:
                    UserResource user = mapper.readValue(data, UserResource.class);
                    response = userWS.updateUser(user, fragment, "id", null);
                    break;
                case DELETE:
                    response = userWS.deleteUser(fragment);
                    break;
                case PATCH:
                    PatchRequest pr = mapper.readValue(data, PatchRequest.class);
                    response = userWS.patchUser(pr, fragment, "id", null);
                    break;
                case POST:
                    user = mapper.readValue(data, UserResource.class);
                    response = userWS.createUser(user, "id", null);
                    if (CREATED.getStatusCode() == response.getStatus()) {
                        user = mapper.readValue(response.getEntity().toString(), UserResource.class);
                        idCreated = user.getId();
                    }
                    break;
            }
        else if (ws == groupWS)
            switch(verb) {
                case PUT:
                    GroupResource group = mapper.readValue(data, GroupResource.class);
                    response = groupWS.updateGroup(group, fragment, "id", null);
                    break;
                case DELETE:
                    response = groupWS.deleteGroup(fragment);
                    break;
                case PATCH:
                    PatchRequest pr = mapper.readValue(data, PatchRequest.class);
                    response = groupWS.patchGroup(pr, fragment, "id", null);
                    break;
                case POST:
                    group = mapper.readValue(data, GroupResource.class);
                    response = groupWS.createGroup(group, "id", null);
                    if (CREATED.getStatusCode() == response.getStatus()) {
                        group = mapper.readValue(response.getEntity().toString(), GroupResource.class);
                        idCreated = group.getId();
                    }
                    break;
            }
        else if (ws == fidoDeviceWS)
            switch(verb) {
                case PUT:
                    FidoDeviceResource dev = mapper.readValue(data, FidoDeviceResource.class);
                    response = fidoDeviceWS.updateDevice(dev, fragment, "id", null);
                    break;
                case DELETE:
                    response = fidoDeviceWS.deleteDevice(fragment);
                    break;
                case PATCH:
                    PatchRequest pr = mapper.readValue(data, PatchRequest.class);
                    response = fidoDeviceWS.patchDevice(pr, fragment, "id", null);
                    break;
                case POST:
                    response = fidoDeviceWS.createDevice();
                    break;
            }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
    }
    return new Pair<Response, String>(response, idCreated);
}
Also used : Response(javax.ws.rs.core.Response) BulkResponse(org.gluu.oxtrust.model.scim2.bulk.BulkResponse) FidoDeviceResource(org.gluu.oxtrust.model.scim2.fido.FidoDeviceResource) UserResource(org.gluu.oxtrust.model.scim2.user.UserResource) PatchRequest(org.gluu.oxtrust.model.scim2.patch.PatchRequest) GroupResource(org.gluu.oxtrust.model.scim2.group.GroupResource) Pair(org.xdi.util.Pair)

Aggregations

GluuCustomPerson (org.gluu.oxtrust.model.GluuCustomPerson)18 User (org.gluu.oxtrust.model.scim2.User)17 ArrayList (java.util.ArrayList)13 Response (javax.ws.rs.core.Response)13 DefaultValue (javax.ws.rs.DefaultValue)12 HeaderParam (javax.ws.rs.HeaderParam)12 Produces (javax.ws.rs.Produces)12 URI (java.net.URI)11 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)11 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)10 ScimPatchUser (org.gluu.oxtrust.model.scim2.ScimPatchUser)10 DuplicateEntryException (org.gluu.site.ldap.exception.DuplicateEntryException)10 User (org.openstack4j.model.identity.v3.User)10 Date (java.util.Date)9 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)8 PersonRequiredFieldsException (org.gluu.oxtrust.exception.PersonRequiredFieldsException)8 EntryPersistenceException (org.gluu.site.ldap.persistence.exception.EntryPersistenceException)8 IOException (java.io.IOException)7 Map (java.util.Map)7 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)7