Search in sources :

Example 21 with MembershipTO

use of org.apache.syncope.common.lib.to.MembershipTO in project syncope by apache.

the class UserSelfCreateResource method newResourceResponse.

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    ResourceResponse response = new ResourceResponse();
    response.setContentType(MediaType.TEXT_PLAIN);
    try {
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN is not matching");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN is not matching");
            return response;
        }
        String jsonString = request.getReader().readLine();
        final UserTO userTO = MAPPER.readValue(jsonString, UserTO.class);
        if (!captchaCheck(request.getHeader("captcha"), request.getSession().getAttribute(SyncopeEnduserConstants.CAPTCHA_SESSION_KEY))) {
            throw new IllegalArgumentException("Entered captcha is not matching");
        }
        if (isSelfRegistrationAllowed() && userTO != null) {
            LOG.debug("User self registration request for [{}]", userTO.getUsername());
            LOG.trace("Request is [{}]", userTO);
            // check if request is compliant with customization form rules
            if (UserRequestValidator.compliant(userTO, SyncopeEnduserApplication.get().getCustomForm(), true)) {
                // 1. membership attributes management
                Set<AttrTO> membAttrs = new HashSet<>();
                userTO.getPlainAttrs().stream().filter(attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))).forEachOrdered(attr -> {
                    String[] simpleAttrs = attr.getSchema().split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                    MembershipTO membership = userTO.getMemberships().stream().filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst().orElse(null);
                    if (membership == null) {
                        membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                        userTO.getMemberships().add(membership);
                    }
                    AttrTO clone = SerializationUtils.clone(attr);
                    clone.setSchema(simpleAttrs[1]);
                    membership.getPlainAttrs().add(clone);
                    membAttrs.add(attr);
                });
                userTO.getPlainAttrs().removeAll(membAttrs);
                // 2. millis -> Date conversion for PLAIN attributes of USER and its MEMBERSHIPS
                SyncopeEnduserSession.get().getDatePlainSchemas().stream().map(plainSchema -> {
                    millisToDate(userTO.getPlainAttrs(), plainSchema);
                    return plainSchema;
                }).forEachOrdered(plainSchema -> {
                    userTO.getMemberships().forEach(membership -> {
                        millisToDate(membership.getPlainAttrs(), plainSchema);
                    });
                });
                membAttrs.clear();
                userTO.getDerAttrs().stream().filter(attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))).forEachOrdered(attr -> {
                    String[] simpleAttrs = attr.getSchema().split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                    MembershipTO membership = userTO.getMemberships().stream().filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst().orElse(null);
                    if (membership == null) {
                        membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                        userTO.getMemberships().add(membership);
                    }
                    AttrTO clone = SerializationUtils.clone(attr);
                    clone.setSchema(simpleAttrs[1]);
                    membership.getDerAttrs().add(clone);
                    membAttrs.add(attr);
                });
                userTO.getDerAttrs().removeAll(membAttrs);
                membAttrs.clear();
                userTO.getVirAttrs().stream().filter(attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))).forEachOrdered(attr -> {
                    String[] simpleAttrs = attr.getSchema().split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                    MembershipTO membership = userTO.getMemberships().stream().filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst().orElse(null);
                    if (membership == null) {
                        membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                        userTO.getMemberships().add(membership);
                    }
                    AttrTO clone = SerializationUtils.clone(attr);
                    clone.setSchema(simpleAttrs[1]);
                    membership.getVirAttrs().add(clone);
                    membAttrs.add(attr);
                });
                userTO.getVirAttrs().removeAll(membAttrs);
                LOG.debug("Received user self registration request for user: [{}]", userTO.getUsername());
                LOG.trace("Received user self registration request is: [{}]", userTO);
                // adapt request and create user
                final Response res = SyncopeEnduserSession.get().getService(UserSelfService.class).create(userTO, true);
                buildResponse(response, res.getStatus(), Response.Status.Family.SUCCESSFUL.equals(res.getStatusInfo().getFamily()) ? "User[ " + userTO.getUsername() + "] successfully created" : "ErrorMessage{{ " + res.getStatusInfo().getReasonPhrase() + " }}");
            } else {
                LOG.warn("Incoming create request [{}] is not compliant with form customization rules. " + "Create NOT allowed", userTO.getUsername());
                buildResponse(response, Response.Status.OK.getStatusCode(), "User: " + userTO.getUsername() + " successfully created");
            }
        } else {
            response.setError(Response.Status.FORBIDDEN.getStatusCode(), new StringBuilder().append("ErrorMessage{{").append(userTO == null ? "Request received is not valid }}" : "Self registration not allowed }}").toString());
        }
    } catch (Exception e) {
        LOG.error("Unable to create userTO", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(), new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}
Also used : SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) AttrTO(org.apache.syncope.common.lib.to.AttrTO) Set(java.util.Set) SerializationUtils(org.apache.commons.lang3.SerializationUtils) UserSelfService(org.apache.syncope.common.rest.api.service.UserSelfService) HashSet(java.util.HashSet) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) SyncopeEnduserConstants(org.apache.syncope.client.enduser.SyncopeEnduserConstants) SyncopeEnduserSession(org.apache.syncope.client.enduser.SyncopeEnduserSession) Response(javax.ws.rs.core.Response) UserRequestValidator(org.apache.syncope.client.enduser.util.UserRequestValidator) SyncopeEnduserApplication(org.apache.syncope.client.enduser.SyncopeEnduserApplication) Resource(org.apache.syncope.client.enduser.annotations.Resource) UserTO(org.apache.syncope.common.lib.to.UserTO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) UserSelfService(org.apache.syncope.common.rest.api.service.UserSelfService) AttrTO(org.apache.syncope.common.lib.to.AttrTO) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) UserTO(org.apache.syncope.common.lib.to.UserTO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) HashSet(java.util.HashSet)

Example 22 with MembershipTO

use of org.apache.syncope.common.lib.to.MembershipTO in project syncope by apache.

the class UserSelfReadResource method newResourceResponse.

@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
    LOG.debug("Requested user self information");
    ResourceResponse response = new AbstractResource.ResourceResponse();
    response.setContentType(MediaType.APPLICATION_JSON);
    try {
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN does not match");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN does not match");
            return response;
        }
        UserTO userTO = SerializationUtils.clone(SyncopeEnduserSession.get().getSelfTO());
        // 1. Date -> millis conversion for PLAIN MEMBERSHIPS attributes of USER
        for (PlainSchemaTO plainSchema : SyncopeEnduserSession.get().getDatePlainSchemas()) {
            for (MembershipTO membership : userTO.getMemberships()) {
                dateToMillis(membership.getPlainAttrs(), plainSchema);
            }
        }
        // 2. membership attributes management
        for (MembershipTO membership : userTO.getMemberships()) {
            String groupName = membership.getGroupName();
            membership.getPlainAttrs().stream().map(attr -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR).concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getPlainAttrs().add(attr);
            });
            membership.getPlainAttrs().clear();
            membership.getDerAttrs().stream().map(attr -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR).concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getDerAttrs().add(attr);
            });
            membership.getDerAttrs().clear();
            membership.getVirAttrs().stream().map((attr) -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR).concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getVirAttrs().add(attr);
            });
            membership.getVirAttrs().clear();
        }
        // USER from customization, if empty or null ignore it, use it to filter attributes otherwise
        applyFromCustomization(userTO, SyncopeEnduserApplication.get().getCustomForm());
        // 1.1 Date -> millis conversion for PLAIN attributes of USER
        for (PlainSchemaTO plainSchema : SyncopeEnduserSession.get().getDatePlainSchemas()) {
            dateToMillis(userTO.getPlainAttrs(), plainSchema);
        }
        final String selfTOJson = MAPPER.writeValueAsString(userTO);
        response.setContentType(MediaType.APPLICATION_JSON);
        response.setTextEncoding(StandardCharsets.UTF_8.name());
        response.setWriteCallback(new WriteCallback() {

            @Override
            public void writeData(final Attributes attributes) throws IOException {
                attributes.getResponse().write(selfTOJson);
            }
        });
        response.setStatusCode(Response.Status.OK.getStatusCode());
    } catch (Exception e) {
        LOG.error("Error retrieving selfTO", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(), new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}
Also used : AttrTO(org.apache.syncope.common.lib.to.AttrTO) Set(java.util.Set) AbstractResource(org.apache.wicket.request.resource.AbstractResource) IOException(java.io.IOException) SerializationUtils(org.apache.commons.lang3.SerializationUtils) SchemaType(org.apache.syncope.common.lib.types.SchemaType) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) SyncopeEnduserConstants(org.apache.syncope.client.enduser.SyncopeEnduserConstants) SyncopeEnduserSession(org.apache.syncope.client.enduser.SyncopeEnduserSession) PlainSchemaTO(org.apache.syncope.common.lib.to.PlainSchemaTO) IResource(org.apache.wicket.request.resource.IResource) Response(javax.ws.rs.core.Response) Map(java.util.Map) SyncopeEnduserApplication(org.apache.syncope.client.enduser.SyncopeEnduserApplication) CustomAttributesInfo(org.apache.syncope.client.enduser.model.CustomAttributesInfo) Resource(org.apache.syncope.client.enduser.annotations.Resource) UserTO(org.apache.syncope.common.lib.to.UserTO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) IOException(java.io.IOException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) PlainSchemaTO(org.apache.syncope.common.lib.to.PlainSchemaTO) UserTO(org.apache.syncope.common.lib.to.UserTO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO)

Example 23 with MembershipTO

use of org.apache.syncope.common.lib.to.MembershipTO in project syncope by apache.

the class AnyOperations method patch.

public static AnyObjectTO patch(final AnyObjectTO anyObjectTO, final AnyObjectPatch anyObjectPatch) {
    AnyObjectTO result = SerializationUtils.clone(anyObjectTO);
    patch(anyObjectTO, anyObjectPatch, result);
    if (anyObjectPatch.getName() != null) {
        result.setName(anyObjectPatch.getName().getValue());
    }
    // 1. relationships
    anyObjectPatch.getRelationships().forEach(relPatch -> {
        if (relPatch.getRelationshipTO() == null) {
            LOG.warn("Invalid {} specified: {}", RelationshipPatch.class.getName(), relPatch);
        } else {
            result.getRelationships().remove(relPatch.getRelationshipTO());
            if (relPatch.getOperation() == PatchOperation.ADD_REPLACE) {
                result.getRelationships().add(relPatch.getRelationshipTO());
            }
        }
    });
    // 2. memberships
    anyObjectPatch.getMemberships().forEach(membPatch -> {
        if (membPatch.getGroup() == null) {
            LOG.warn("Invalid {} specified: {}", MembershipPatch.class.getName(), membPatch);
        } else {
            Optional<MembershipTO> memb = result.getMemberships().stream().filter(membership -> membPatch.getGroup().equals(membership.getGroupKey())).findFirst();
            if (memb.isPresent()) {
                result.getMemberships().remove(memb.get());
            }
            if (membPatch.getOperation() == PatchOperation.ADD_REPLACE) {
                MembershipTO newMembershipTO = new MembershipTO.Builder().group(membPatch.getGroup()).build();
                // 3. plain attributes
                newMembershipTO.getPlainAttrs().addAll(membPatch.getPlainAttrs());
                // 4. virtual attributes
                newMembershipTO.getVirAttrs().addAll(membPatch.getVirAttrs());
                result.getMemberships().add(newMembershipTO);
            }
        }
    });
    return result;
}
Also used : StringPatchItem(org.apache.syncope.common.lib.patch.StringPatchItem) AttrTO(org.apache.syncope.common.lib.to.AttrTO) AnyObjectPatch(org.apache.syncope.common.lib.patch.AnyObjectPatch) LoggerFactory(org.slf4j.LoggerFactory) AnyTO(org.apache.syncope.common.lib.to.AnyTO) HashMap(java.util.HashMap) SerializationUtils(org.apache.commons.lang3.SerializationUtils) BooleanReplacePatchItem(org.apache.syncope.common.lib.patch.BooleanReplacePatchItem) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) RelationshipPatch(org.apache.syncope.common.lib.patch.RelationshipPatch) StringUtils(org.apache.commons.lang3.StringUtils) GroupPatch(org.apache.syncope.common.lib.patch.GroupPatch) MembershipPatch(org.apache.syncope.common.lib.patch.MembershipPatch) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) AbstractReplacePatchItem(org.apache.syncope.common.lib.patch.AbstractReplacePatchItem) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) AnyPatch(org.apache.syncope.common.lib.patch.AnyPatch) Logger(org.slf4j.Logger) Collection(java.util.Collection) Set(java.util.Set) GroupTO(org.apache.syncope.common.lib.to.GroupTO) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) PasswordPatch(org.apache.syncope.common.lib.patch.PasswordPatch) RelationshipTO(org.apache.syncope.common.lib.to.RelationshipTO) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) Optional(java.util.Optional) StringReplacePatchItem(org.apache.syncope.common.lib.patch.StringReplacePatchItem) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) MembershipPatch(org.apache.syncope.common.lib.patch.MembershipPatch) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) RelationshipPatch(org.apache.syncope.common.lib.patch.RelationshipPatch)

Aggregations

MembershipTO (org.apache.syncope.common.lib.to.MembershipTO)23 UserTO (org.apache.syncope.common.lib.to.UserTO)18 AttrTO (org.apache.syncope.common.lib.to.AttrTO)15 GroupTO (org.apache.syncope.common.lib.to.GroupTO)12 Map (java.util.Map)11 Set (java.util.Set)9 SerializationUtils (org.apache.commons.lang3.SerializationUtils)9 AttrPatch (org.apache.syncope.common.lib.patch.AttrPatch)9 StringUtils (org.apache.commons.lang3.StringUtils)8 AnyObjectTO (org.apache.syncope.common.lib.to.AnyObjectTO)8 PatchOperation (org.apache.syncope.common.lib.types.PatchOperation)8 List (java.util.List)7 Optional (java.util.Optional)7 UserPatch (org.apache.syncope.common.lib.patch.UserPatch)7 AnyTO (org.apache.syncope.common.lib.to.AnyTO)7 Test (org.junit.jupiter.api.Test)7 Collections (java.util.Collections)6 Response (javax.ws.rs.core.Response)6 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)6 StringPatchItem (org.apache.syncope.common.lib.patch.StringPatchItem)6