Search in sources :

Example 51 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class PingCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final String sessionId = webSocketData.getSessionId();
    logger.debug("PING received from session {}", sessionId);
    final Principal currentUser = AuthHelper.getPrincipalForSessionId(SessionHelper.getShortSessionId(sessionId), true);
    if (currentUser != null) {
        logger.debug("User found by session id: " + currentUser.getName());
        getWebSocket().send(MessageBuilder.status().callback(webSocketData.getCallback()).data("username", currentUser.getProperty(AbstractNode.name)).data("isAdmin", currentUser.isAdmin()).code(100).build(), true);
    } else {
        logger.debug("Invalid session id");
        getWebSocket().send(MessageBuilder.status().code(401).build(), true);
    }
}
Also used : Principal(org.structr.core.entity.Principal)

Example 52 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class CreateNodeCommand method execute.

public T execute(final PropertyMap attributes) throws FrameworkException {
    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final Principal user = securityContext.getUser(false);
    T node = null;
    if (graphDb != null) {
        final NodeFactory<T> nodeFactory = new NodeFactory<>(securityContext);
        final PropertyMap properties = new PropertyMap(attributes);
        final PropertyMap toNotify = new PropertyMap();
        final Object typeObject = properties.get(AbstractNode.type);
        final Class nodeType = getTypeOrGeneric(typeObject);
        final Set<String> labels = TypeProperty.getLabelsForType(nodeType);
        final CreationContainer tmp = new CreationContainer();
        final Date now = new Date();
        final boolean isCreation = true;
        // use user-supplied UUID?
        String uuid = properties.get(GraphObject.id);
        if (uuid == null) {
            // no, create new one
            uuid = getNextUuid();
            properties.put(GraphObject.id, uuid);
        } else {
            // enable UUID validation
            securityContext.uuidWasSetManually(true);
        }
        // use property keys to set property values on creation dummy
        // set default values for common properties in creation query
        GraphObject.id.setProperty(securityContext, tmp, uuid);
        GraphObject.type.setProperty(securityContext, tmp, nodeType.getSimpleName());
        AbstractNode.createdDate.setProperty(securityContext, tmp, now);
        AbstractNode.lastModifiedDate.setProperty(securityContext, tmp, now);
        // default property values
        AbstractNode.visibleToPublicUsers.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.visibleToPublicUsers, false));
        AbstractNode.visibleToAuthenticatedUsers.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.visibleToAuthenticatedUsers, false));
        AbstractNode.hidden.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.hidden, false));
        AbstractNode.deleted.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.deleted, false));
        if (user != null) {
            final String userId = user.getProperty(GraphObject.id);
            AbstractNode.createdBy.setProperty(securityContext, tmp, userId);
            AbstractNode.lastModifiedBy.setProperty(securityContext, tmp, userId);
        }
        // prevent double setting of properties
        properties.remove(AbstractNode.id);
        properties.remove(AbstractNode.type);
        properties.remove(AbstractNode.visibleToPublicUsers);
        properties.remove(AbstractNode.visibleToAuthenticatedUsers);
        properties.remove(AbstractNode.hidden);
        properties.remove(AbstractNode.deleted);
        properties.remove(AbstractNode.lastModifiedDate);
        properties.remove(AbstractNode.lastModifiedBy);
        properties.remove(AbstractNode.createdDate);
        properties.remove(AbstractNode.createdBy);
        // move properties to creation container that can be set directly on creation
        tmp.filterIndexableForCreation(securityContext, properties, tmp, toNotify);
        // collect default values and try to set them on creation
        for (final PropertyKey key : StructrApp.getConfiguration().getPropertySet(nodeType, PropertyView.All)) {
            if (key instanceof AbstractPrimitiveProperty && !tmp.hasProperty(key.jsonName())) {
                final Object defaultValue = key.defaultValue();
                if (defaultValue != null) {
                    key.setProperty(securityContext, tmp, defaultValue);
                }
            }
        }
        node = (T) nodeFactory.instantiateWithType(createNode(graphDb, user, labels, tmp.getData()), nodeType, null, isCreation);
        if (node != null) {
            TransactionCommand.nodeCreated(user, node);
            securityContext.disableModificationOfAccessTime();
            node.setProperties(securityContext, properties);
            securityContext.enableModificationOfAccessTime();
            // ensure modification callbacks are called (necessary for validation)
            for (final Entry<PropertyKey, Object> entry : toNotify.entrySet()) {
                final PropertyKey key = entry.getKey();
                final Object value = entry.getValue();
                if (!key.isUnvalidated()) {
                    TransactionCommand.nodeModified(securityContext.getCachedUser(), (AbstractNode) node, key, null, value);
                }
            }
            properties.clear();
            // ensure indexing of newly created node
            node.addToIndex();
            // invalidate UUID cache
            StructrApp.invalidate(uuid);
        }
    }
    if (node != null) {
        // notify node of its creation
        node.onNodeCreation();
        // iterate post creation transformations
        final Set<Transformation<GraphObject>> transformations = StructrApp.getConfiguration().getEntityCreationTransformations(node.getClass());
        for (Transformation<GraphObject> transformation : transformations) {
            transformation.apply(securityContext, node);
        }
    }
    return node;
}
Also used : Transformation(org.structr.core.Transformation) DatabaseService(org.structr.api.DatabaseService) GraphObject(org.structr.core.GraphObject) Date(java.util.Date) PropertyMap(org.structr.core.property.PropertyMap) AbstractPrimitiveProperty(org.structr.core.property.AbstractPrimitiveProperty) GraphObject(org.structr.core.GraphObject) Principal(org.structr.core.entity.Principal) PropertyKey(org.structr.core.property.PropertyKey)

Example 53 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class CreateRelationshipCommand method createRelationship.

private synchronized <A extends NodeInterface, B extends NodeInterface, R extends Relation<A, B, ?, ?>> R createRelationship(final A fromNode, final B toNode, final Class<R> relType, final PropertyMap attributes) throws FrameworkException {
    // disable updating access time when creating relationships
    securityContext.disableModificationOfAccessTime();
    final RelationshipFactory<R> factory = new RelationshipFactory(securityContext);
    final PropertyMap properties = new PropertyMap(attributes);
    final CreationContainer tmp = new CreationContainer();
    final R template = instantiate(relType);
    final Node startNode = fromNode.getNode();
    final Node endNode = toNode.getNode();
    final Date now = new Date();
    final Principal user = securityContext.getCachedUser();
    template.ensureCardinality(securityContext, fromNode, toNode);
    // date properties need converter
    AbstractRelationship.createdDate.setProperty(securityContext, tmp, now);
    AbstractRelationship.lastModifiedDate.setProperty(securityContext, tmp, now);
    // set initial properties manually (caution, this can only be used for primitive properties!)
    tmp.getData().put(GraphObject.id.jsonName(), getNextUuid());
    tmp.getData().put(GraphObject.type.jsonName(), relType.getSimpleName());
    tmp.getData().put(AbstractRelationship.relType.jsonName(), template.name());
    tmp.getData().put(AbstractRelationship.sourceId.jsonName(), fromNode.getUuid());
    tmp.getData().put(AbstractRelationship.targetId.jsonName(), toNode.getUuid());
    tmp.getData().put(AbstractRelationship.visibleToPublicUsers.jsonName(), false);
    tmp.getData().put(AbstractRelationship.visibleToAuthenticatedUsers.jsonName(), false);
    tmp.getData().put(AbstractRelationship.cascadeDelete.jsonName(), template.getCascadingDeleteFlag());
    if (user != null) {
        tmp.getData().put(AbstractRelationship.createdBy.jsonName(), user.getUuid());
    }
    // create relationship including initial properties
    final Relationship rel = startNode.createRelationshipTo(endNode, template, tmp.getData());
    final R newRel = factory.instantiateWithType(rel, relType, null, true);
    if (newRel != null) {
        newRel.setProperties(securityContext, properties);
        // notify transaction handler
        TransactionCommand.relationshipCreated(user, newRel);
        // notify relationship of its creation
        newRel.onRelationshipCreation();
        // iterate post creation transformations
        for (Transformation<GraphObject> transformation : StructrApp.getConfiguration().getEntityCreationTransformations(newRel.getClass())) {
            transformation.apply(securityContext, newRel);
        }
    }
    // enable access time update again for subsequent calls
    securityContext.enableModificationOfAccessTime();
    return newRel;
}
Also used : PropertyMap(org.structr.core.property.PropertyMap) Node(org.structr.api.graph.Node) AbstractRelationship(org.structr.core.entity.AbstractRelationship) Relationship(org.structr.api.graph.Relationship) GraphObject(org.structr.core.GraphObject) Date(java.util.Date) Principal(org.structr.core.entity.Principal)

Example 54 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class RemoveFromGroupFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (!arrayHasLengthAndAllElementsNotNull(sources, 2)) {
            return "";
        }
        if (!(sources[0] instanceof Group)) {
            logger.warn("Error: first argument is not a Group. Parameters: {}", getParametersAsString(sources));
            return "Error: first argument is not a Group.";
        }
        if (!(sources[1] instanceof Principal)) {
            logger.warn("Error: second argument is not a Principal. Parameters: {}", getParametersAsString(sources));
            return "Error: second argument is not a Principal.";
        }
        final Group group = (Group) sources[0];
        final Principal user = (Principal) sources[1];
        group.removeMember(user);
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
    return "";
}
Also used : Group(org.structr.core.entity.Group) Principal(org.structr.core.entity.Principal)

Example 55 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class SSHService method authenticate.

@Override
public boolean authenticate(final String username, final String password, final ServerSession session) {
    boolean isValid = false;
    Principal principal = null;
    try (final Tx tx = StructrApp.getInstance().tx()) {
        principal = AuthHelper.getPrincipalForPassword(AbstractNode.name, username, password);
        if (principal != null) {
            isValid = true;
            securityContext = SecurityContext.getInstance(principal, AccessMode.Backend);
        }
        tx.success();
    } catch (AuthenticationException ae) {
        logger.warn(ae.getMessage());
        isValid = false;
    } catch (Throwable t) {
        logger.warn("", t);
        isValid = false;
    }
    try {
        if (isValid) {
            session.setAuthenticated();
        }
    } catch (IOException ex) {
        logger.error("", ex);
    }
    return isValid;
}
Also used : Tx(org.structr.core.graph.Tx) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) IOException(java.io.IOException) Principal(org.structr.core.entity.Principal)

Aggregations

Principal (org.structr.core.entity.Principal)112 FrameworkException (org.structr.common.error.FrameworkException)68 Tx (org.structr.core.graph.Tx)65 Test (org.junit.Test)41 App (org.structr.core.app.App)31 StructrApp (org.structr.core.app.StructrApp)31 TestOne (org.structr.core.entity.TestOne)16 Group (org.structr.core.entity.Group)14 NodeAttribute (org.structr.core.graph.NodeAttribute)13 PropertyMap (org.structr.core.property.PropertyMap)13 SecurityContext (org.structr.common.SecurityContext)10 LinkedList (java.util.LinkedList)9 Result (org.structr.core.Result)8 User (org.structr.web.entity.User)8 AbstractNode (org.structr.core.entity.AbstractNode)7 SuperUser (org.structr.core.entity.SuperUser)7 StructrUiTest (org.structr.web.StructrUiTest)7 Page (org.structr.web.entity.dom.Page)7 IOException (java.io.IOException)6 List (java.util.List)6