Search in sources :

Example 1 with User

use of nl.knaw.huygens.timbuctoo.v5.security.dto.User in project timbuctoo by HuygensING.

the class GraphQl method executeGraphql.

public Response executeGraphql(String query, String acceptHeader, String acceptParam, String queryFromBody, Map variables, String operationName, String authHeader) {
    final SerializerWriter serializerWriter;
    if (acceptParam != null && !acceptParam.isEmpty()) {
        // Accept param overrules header because it's more under the user's control
        acceptHeader = acceptParam;
    }
    if (unSpecifiedAcceptHeader(acceptHeader)) {
        acceptHeader = MediaType.APPLICATION_JSON;
    }
    if (MediaType.APPLICATION_JSON.equals(acceptHeader)) {
        serializerWriter = null;
    } else {
        Optional<SerializerWriter> bestMatch = serializerWriterRegistry.getBestMatch(acceptHeader);
        if (bestMatch.isPresent()) {
            serializerWriter = bestMatch.get();
        } else {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"The available mediatypes are: " + String.join(", ", serializerWriterRegistry.getSupportedMimeTypes()) + "\"]}").build();
        }
    }
    if (query != null && queryFromBody != null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"There's both a query as url paramatere and a query in the body. Please pick one.\"]}").build();
    }
    if (query == null && queryFromBody == null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"Please provide the graphql query as the query property of a JSON encoded object. " + "E.g. {query: \\\"{\\n  persons {\\n ... \\\"}\"]}").build();
    }
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    UserPermissionCheck userPermissionCheck = new UserPermissionCheck(user, permissionFetcher, newHashSet(Permission.READ));
    final GraphQLSchema transform = graphqlGetter.get().transform(b -> b.fieldVisibility(new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository)));
    final GraphQL.Builder builder = GraphQL.newGraphQL(transform);
    if (serializerWriter != null) {
        builder.queryExecutionStrategy(new SerializerExecutionStrategy());
    }
    GraphQL graphQl = builder.build();
    final ExecutionResult result = graphQl.execute(newExecutionInput().root(new RootData(user)).context(contextData(userPermissionCheck, user)).query(queryFromBody).operationName(operationName).variables(variables == null ? Collections.emptyMap() : variables).build());
    if (serializerWriter == null) {
        return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
    } else {
        if (result.getErrors() != null && !result.getErrors().isEmpty()) {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
        }
        return Response.ok().type(serializerWriter.getMimeType()).entity((StreamingOutput) os -> {
            serializerWriter.getSerializationFactory().create(os).serialize(new SerializableResult(result.getData()));
        }).build();
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) GraphQL(graphql.GraphQL) SerializableResult(nl.knaw.huygens.timbuctoo.v5.serializable.SerializableResult) SerializerWriter(nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes.SerializerWriter) ExecutionResult(graphql.ExecutionResult) StreamingOutput(javax.ws.rs.core.StreamingOutput) GraphQLSchema(graphql.schema.GraphQLSchema) RootData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.RootData) PermissionBasedFieldVisibility(nl.knaw.huygens.timbuctoo.v5.graphql.security.PermissionBasedFieldVisibility) SerializerExecutionStrategy(nl.knaw.huygens.timbuctoo.v5.graphql.serializable.SerializerExecutionStrategy) UserPermissionCheck(nl.knaw.huygens.timbuctoo.v5.graphql.security.UserPermissionCheck)

Example 2 with User

use of nl.knaw.huygens.timbuctoo.v5.security.dto.User in project timbuctoo by HuygensING.

the class Rml method upload.

@POST
public Response upload(final String rdfData, @PathParam("userId") final String ownerId, @PathParam("dataSetId") final String dataSetId, @HeaderParam("authorization") String authHeader) throws DataStoreCreationException, LogStorageFailedException, ExecutionException, InterruptedException {
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        LOG.error("Exception validating user", e);
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    if (!user.isPresent()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    final Optional<DataSet> dataSet = dataSetRepository.getDataSet(user.get(), ownerId, dataSetId);
    if (dataSet.isPresent()) {
        ImportManager importManager = dataSet.get().getImportManager();
        final String baseUri = dataSet.get().getMetadata().getBaseUri();
        Future<ImportStatus> promise = importManager.generateLog(baseUri, baseUri, new RmlRdfCreator(baseUri, rdfData));
        return handleImportManagerResult(promise);
    } else {
        return errorResponseHelper.dataSetNotFound(ownerId, dataSetId);
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) ImportManager(nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) RmlRdfCreator(nl.knaw.huygens.timbuctoo.v5.rml.RmlRdfCreator) POST(javax.ws.rs.POST)

Example 3 with User

use of nl.knaw.huygens.timbuctoo.v5.security.dto.User in project timbuctoo by HuygensING.

the class RsEndpoint method getDescription.

@GET
@Path("{ownerId}/{dataSetName}/description.xml")
public Response getDescription(@HeaderParam("authorization") String authHeader, @PathParam("ownerId") String owner, @PathParam("dataSetName") String dataSetName) {
    User user = getUser(authHeader);
    Optional<File> maybeFile = rsDocumentBuilder.getDataSetDescription(user, owner, dataSetName);
    if (maybeFile.isPresent()) {
        if (maybeFile.get().exists()) {
            return Response.ok(maybeFile.get(), MediaType.APPLICATION_XML_TYPE).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } else if (user != null) {
        return Response.status(Response.Status.FORBIDDEN).build();
    } else {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
}
Also used : User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) CachedFile(nl.knaw.huygens.timbuctoo.v5.filestorage.dto.CachedFile) File(java.io.File) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 4 with User

use of nl.knaw.huygens.timbuctoo.v5.security.dto.User in project timbuctoo by HuygensING.

the class RsEndpoint method getResourceList.

@GET
@Path("{ownerId}/{dataSetName}/resourcelist.xml")
@Produces(MediaType.APPLICATION_XML)
public Response getResourceList(@HeaderParam("authorization") String authHeader, @PathParam("ownerId") String owner, @PathParam("dataSetName") String dataSetName) throws IOException {
    User user = getUser(authHeader);
    Optional<Urlset> maybeResourceList = rsDocumentBuilder.getResourceList(user, owner, dataSetName);
    if (maybeResourceList.isPresent()) {
        return Response.ok(maybeResourceList.get()).build();
    } else if (user != null) {
        return Response.status(Response.Status.FORBIDDEN).build();
    } else {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
}
Also used : User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) Urlset(nl.knaw.huygens.timbuctoo.remote.rs.xml.Urlset) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 5 with User

use of nl.knaw.huygens.timbuctoo.v5.security.dto.User in project timbuctoo by HuygensING.

the class DataSetRepository method removeDataSet.

public void removeDataSet(String ownerId, String dataSetName, User user) throws IOException, NotEnoughPermissionsException, DataSetDoesNotExistException {
    try {
        DataSet dataSet = dataSetMap.get(ownerId).get(dataSetName);
        if (dataSet == null) {
            LOG.warn("DataSet '{}' of user with id '{}' does not exist (anymore).", dataSetName, ownerId);
            throw new DataSetDoesNotExistException(dataSetName, ownerId);
        }
        String combinedId = dataSet.getMetadata().getCombinedId();
        if (!permissionFetcher.getPermissions(user, dataSet.getMetadata()).contains(Permission.ADMIN)) {
            throw new NotEnoughPermissionsException(String.format("User '%s' is not allowed to remove dataset '%s'", user.getDisplayName(), combinedId));
        }
        dataSet.stop();
        dataSetMap.get(ownerId).remove(dataSetName);
        permissionFetcher.removeAuthorizations(combinedId);
    } catch (PermissionFetchingException e) {
        throw new IOException(e);
    }
    // remove folder
    dataStorage.getDataSetStorage(ownerId, dataSetName).clear();
}
Also used : PermissionFetchingException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.PermissionFetchingException) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) NotEnoughPermissionsException(nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.NotEnoughPermissionsException) IOException(java.io.IOException)

Aggregations

User (nl.knaw.huygens.timbuctoo.v5.security.dto.User)42 Test (org.junit.Test)22 DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)19 IOException (java.io.IOException)11 DataSetMetaData (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData)9 UserValidationException (nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException)7 PermissionFetchingException (nl.knaw.huygens.timbuctoo.v5.security.exceptions.PermissionFetchingException)6 Path (javax.ws.rs.Path)5 Urlset (nl.knaw.huygens.timbuctoo.remote.rs.xml.Urlset)5 ImportStatus (nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus)5 Matchers.isEmptyString (org.hamcrest.Matchers.isEmptyString)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 GET (javax.ws.rs.GET)4 Response (javax.ws.rs.core.Response)4 BasicDataSetMetaData (nl.knaw.huygens.timbuctoo.v5.dataset.dto.BasicDataSetMetaData)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 GraphQLSchema (graphql.schema.GraphQLSchema)3 Optional (java.util.Optional)3 DataStoreCreationException (nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.DataStoreCreationException)3 QuadStore (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore)3