Search in sources :

Example 6 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class NamespaceProvider method mockEclipseNamespace.

public static Namespace mockEclipseNamespace() {
    Namespace namespace = new Namespace();
    namespace.setName("org.eclipse.vorto");
    namespace.setId(1L);
    namespace.setWorkspaceId("playground");
    return namespace;
}
Also used : Namespace(org.eclipse.vorto.repository.domain.Namespace)

Example 7 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class NamespaceController method getAllNamespacesForLoggedUser.

/**
 * @return all namespaces the logged on user has access to.
 */
@RequestMapping(method = RequestMethod.GET, value = "/all")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Collection<NamespaceDto>> getAllNamespacesForLoggedUser() {
    IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
    Collection<NamespaceDto> namespaces = new TreeSet<>(Comparator.comparing(NamespaceDto::getName));
    try {
        for (Map.Entry<Namespace, Map<User, Collection<IRole>>> entry : userNamespaceRoleService.getNamespacesCollaboratorsAndRoles(userContext.getUsername(), userContext.getUsername(), "namespace_admin").entrySet()) {
            namespaces.add(EntityDTOConverter.createNamespaceDTO(entry.getKey(), entry.getValue()));
        }
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(namespaces, HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException d) {
        return new ResponseEntity<>(namespaces, HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>(namespaces, HttpStatus.OK);
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) NamespaceDto(org.eclipse.vorto.repository.web.api.v1.dto.NamespaceDto) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ResponseEntity(org.springframework.http.ResponseEntity) IRole(org.eclipse.vorto.repository.domain.IRole) TreeSet(java.util.TreeSet) Map(java.util.Map) Namespace(org.eclipse.vorto.repository.domain.Namespace) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class NamespaceService method create.

// namespace operations
/**
 * This creates a new namespace with the given name, setting the given target {@link User} as
 * owner, and giving them all available roles on that namespace. <br/>
 * The difference between the actor and target users is that depending on the repository roles of
 * the actor user, some operations may not succeed.<br/>
 * For instance, if the actor and target are the same user (typical situation when a user
 * requests to create their own namespace), but the user is not a sysadmin and already has a
 * private namespace, the creation would fail (one private namespace per user). <br/>
 * However, if the actor was sysadmin and creating, e.g. an official namespace for a target user
 * who happens to already have a private namespace, the operation should succeed. <br/>
 * The operation can fail the given {@link User} or namespace name are invalid. <br/>
 * Examples of invalid {@link User} or namespace are:
 * <ul>
 *   <li>
 *     The user is {@code null}, has a {@code null} user name, or does not exist.
 *   </li>
 *   <li>
 *     The namespace name is {@code null}, empty, does not conform to naming standards (lowercase
 *     ASCII alphanumerics, dots as separators, underscores allowed).
 *   </li>
 *   <li>
 *     A namespace with that name already exists.
 *   </li>
 * </ul>
 * This method is invoked in two distinct cases:
 * <ol>
 *   <li>
 *     A user creates their own private namespace.
 *   </li>
 *   <li>
 *     A sysadmin creates an official namespace for any user, including themselves.
 *   </li>
 * </ol>
 * This method only deals with creating namespaces. <br/>
 *
 * @param actor
 * @param target
 * @param namespaceName
 * @return
 * @throws IllegalArgumentException
 * @throws DoesNotExistException
 * @throws CollisionException
 * @throws NameSyntaxException
 */
@Transactional(rollbackFor = { DoesNotExistException.class, CollisionException.class, NameSyntaxException.class, PrivateNamespaceQuotaExceededException.class, OperationForbiddenException.class })
public Namespace create(User actor, User target, String namespaceName) throws IllegalArgumentException, DoesNotExistException, CollisionException, NameSyntaxException, PrivateNamespaceQuotaExceededException, OperationForbiddenException {
    // boilerplate null validation
    ServiceValidationUtil.validate(actor, target);
    ServiceValidationUtil.validateNulls(namespaceName);
    // lightweight validation of required properties
    ServiceValidationUtil.validateNulls(actor.getId(), target.getId());
    if (namespaceName.trim().isEmpty()) {
        throw new NameSyntaxException(String.format("Namespace name is empty - aborting namespace creation.", namespaceName));
    }
    // pattern-based namespace name validation
    if (!VALID_NAMESPACE_NAME.matcher(namespaceName).matches()) {
        throw new NameSyntaxException(String.format("[%s] is not a valid namespace name - aborting namespace creation.", namespaceName));
    }
    // namespace collision validation
    if (cache.namespace(namespaceName).isPresent()) {
        throw new CollisionException(String.format("A namespace with name [%s] already exists - aborting namespace creation.", namespaceName));
    }
    // actor is not sysadmin - need to enforce quota validation and private namespace notation
    if (!userRepositoryRoleService.isSysadmin(actor)) {
        if (!namespaceName.startsWith(PRIVATE_NAMESPACE_PREFIX)) {
            throw new NameSyntaxException(String.format("[%s] is an invalid name for a private namespace - aborting namespace creation.", namespaceName));
        }
        verifyPrivateNamespaceQuota(actor, target);
    }
    // persists the new namespace
    Namespace namespace = new Namespace();
    namespace.setName(namespaceName);
    namespace.setWorkspaceId(UUID.randomUUID().toString().replace("-", ""));
    namespaceRepository.save(namespace);
    userNamespaceRoleService.setAllRoles(actor, target, namespace, true);
    // making cache stale so it will load the newly created namespace upon next usage within request
    cache.stale();
    // application event handling
    eventPublisher.publishEvent(new AppEvent(this, target.getUsername(), UserContext.user(target.getUsername(), namespace.getWorkspaceId()), EventType.NAMESPACE_ADDED));
    return namespace;
}
Also used : AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) CollisionException(org.eclipse.vorto.repository.services.exceptions.CollisionException) NameSyntaxException(org.eclipse.vorto.repository.services.exceptions.NameSyntaxException) Namespace(org.eclipse.vorto.repository.domain.Namespace) Transactional(org.springframework.transaction.annotation.Transactional)

Example 9 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class UserService method delete.

/**
 * Deletes the given {@link User} and their namespace-role associations, as acted by the given
 * acting {@link User}.<br/>
 * This can fail for a number of reasons:
 * <ul>
 *   <li>
 *     The acting {@link User} does not have the {@literal sysadmin} repository role, or is not
 *     the same {@link User} as the target.
 *   </li>
 *   <li>
 *     The target {@link User} owns a {@link org.eclipse.vorto.repository.domain.Namespace} - in
 *     which case, ownership should be given to another {@link User} before deleting.
 *   </li>
 *   <li>
 *     The target {@link User} is the only one listed with namespace role {@literal namespace_admin}
 *     on one or more {@link org.eclipse.vorto.repository.domain.Namespace}s - in which case, the
 *     role should be given to at least one other {@link User} before deleting.
 *   </li>
 * </ul>
 * Failures above will throw checked exceptions. <br/>
 * It is also possible that this method will fail by returning {@code false}, should the target
 * {@link User} simply not exist.
 *
 * @param actor
 * @param target
 * @return
 */
@Transactional(rollbackFor = { OperationForbiddenException.class, DoesNotExistException.class })
public boolean delete(User actor, User target) throws OperationForbiddenException, DoesNotExistException {
    // boilerplate null validation
    ServiceValidationUtil.validateNulls(actor, target);
    if (cache.withUser(target).getUser() == null) {
        LOGGER.info("Attempting to delete a user that does not exist. ");
        return false;
    }
    // authorizing actor
    userUtil.authorizeActorAsTargetOrSysadmin(actor, target);
    // checking if only admin in any namespace
    if (userNamespaceRoleService.isOnlyAdminInAnyNamespace(actor, target)) {
        throw new OperationForbiddenException("User is the only administrator of at least one namespace - aborting delete operation.");
    }
    // retrieving namespaces target manages
    Collection<Namespace> namespacesManagedByTarget = userNamespaceRoleService.getNamespacesAndRolesByUser(actor, target).entrySet().stream().filter(e -> e.getValue().contains(userNamespaceRoleService.namespaceAdminRole())).map(Entry::getKey).collect(Collectors.toSet());
    // target owns at least one namespace - failing
    if (!namespacesManagedByTarget.isEmpty()) {
        throw new OperationForbiddenException("User is administrator in at least one namespace. Ownership must change before user can be deleted. Aborting operation.");
    }
    // collecting target user's e-mail address if any
    DeleteAccountMessage message = null;
    if (target.hasEmailAddress()) {
        message = new DeleteAccountMessage(target);
    }
    // firstly, publish the user deleted event - this way, the models are all anonymized while the
    // user and their namespace associations are still there
    eventPublisher.publishEvent(new AppEvent(this, target.getUsername(), EventType.USER_DELETED));
    // then, retrie namespaces where target has any role
    Collection<Namespace> namespacesWhereTargetHasAnyRole = userNamespaceRoleService.getNamespaces(actor, target);
    // and remove association for all namespaces
    for (Namespace namespace : namespacesWhereTargetHasAnyRole) {
        userNamespaceRoleService.deleteAllRoles(actor, target, namespace, false);
    }
    // finally, delete target user
    userRepository.delete(target);
    // and send them a message if possible
    if (message != null) {
        notificationService.sendNotification(message);
    }
    return true;
}
Also used : AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) Namespace(org.eclipse.vorto.repository.domain.Namespace) DeleteAccountMessage(org.eclipse.vorto.repository.notification.message.DeleteAccountMessage) Transactional(org.springframework.transaction.annotation.Transactional)

Example 10 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class ModelRepository method rename.

@Override
public ModelInfo rename(ModelId oldModelId, ModelId newModelId, IUserContext user) {
    Namespace namespace = namespaceService.findNamespaceByWorkspaceId(getWorkspaceId());
    if (getById(newModelId) != null) {
        throw new ModelAlreadyExistsException();
    } else if (!newModelId.getNamespace().startsWith(namespace.getName())) {
        throw new NewNamespacesNotSupersetException();
    }
    ModelInfo oldModel = getById(oldModelId);
    ChangeSet changeSet = refactorModelWithNewId(oldModel, newModelId);
    saveChangeSetIntoRepository(changeSet, user);
    ModelInfo newModel = getById(newModelId);
    newModel = copy(oldModel, newModel, user);
    removeModel(oldModel.getId());
    return newModel;
}
Also used : NewNamespacesNotSupersetException(org.eclipse.vorto.repository.tenant.NewNamespacesNotSupersetException) ChangeSet(org.eclipse.vorto.model.refactor.ChangeSet) Namespace(org.eclipse.vorto.repository.domain.Namespace)

Aggregations

Namespace (org.eclipse.vorto.repository.domain.Namespace)16 DoesNotExistException (org.eclipse.vorto.repository.services.exceptions.DoesNotExistException)7 IUserContext (org.eclipse.vorto.repository.core.IUserContext)6 OperationForbiddenException (org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException)6 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)6 Map (java.util.Map)5 ResponseEntity (org.springframework.http.ResponseEntity)5 Collection (java.util.Collection)4 Optional (java.util.Optional)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 Collectors (java.util.stream.Collectors)4 NamespaceService (org.eclipse.vorto.repository.services.NamespaceService)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 PutMapping (org.springframework.web.bind.annotation.PutMapping)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 ApiParam (io.swagger.annotations.ApiParam)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 User (org.eclipse.vorto.repository.domain.User)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3