Search in sources :

Example 1 with PermissionFetcher

use of nl.knaw.huygens.timbuctoo.v5.security.PermissionFetcher 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 PermissionFetcher

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

the class AuthCheckTest method checkAdminAccessReturnsNullIfTheUserIsAnAdminForTheDataSet.

@Test
public void checkAdminAccessReturnsNullIfTheUserIsAnAdminForTheDataSet() throws Exception {
    User notOwner = User.create(null, "user");
    UserValidator userValidator = mock(UserValidator.class);
    given(userValidator.getUserFromAccessToken(anyString())).willReturn(Optional.of(notOwner));
    PermissionFetcher permissionFetcher = mock(PermissionFetcher.class);
    given(permissionFetcher.getPermissions(any(User.class), any(BasicDataSetMetaData.class))).willReturn(permissionsForAdmin());
    Response response = checkAdminAccess(permissionFetcher, userValidator, "auth", new BasicDataSetMetaData("ownerid", "datasetid", "http://ex.org", "http://example.org/prefix/", false, false));
    assertThat(response.getStatus(), is(200));
}
Also used : Response(javax.ws.rs.core.Response) PermissionFetcher(nl.knaw.huygens.timbuctoo.v5.security.PermissionFetcher) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) BasicDataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.BasicDataSetMetaData) UserValidator(nl.knaw.huygens.timbuctoo.v5.security.UserValidator) Test(org.junit.Test)

Example 3 with PermissionFetcher

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

the class UserPermissionCheckTest method getPermissionsReturnsNoPermissionsForEmptyUserIfPrivateDataSet.

@Test
public void getPermissionsReturnsNoPermissionsForEmptyUserIfPrivateDataSet() {
    PermissionFetcher permissionFetcher = mock(PermissionFetcher.class);
    Set<Permission> defaultPermissions = Sets.newHashSet(Permission.READ);
    UserPermissionCheck userPermissionCheck = new UserPermissionCheck(Optional.empty(), permissionFetcher, defaultPermissions);
    DataSetMetaData dataSetMetaData = mock(BasicDataSetMetaData.class);
    given(dataSetMetaData.isPublished()).willReturn(false);
    Set<Permission> permissions = userPermissionCheck.getPermissions(dataSetMetaData);
    assertEquals(Sets.newHashSet(), permissions);
}
Also used : PermissionFetcher(nl.knaw.huygens.timbuctoo.v5.security.PermissionFetcher) Permission(nl.knaw.huygens.timbuctoo.v5.security.dto.Permission) DataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData) BasicDataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.BasicDataSetMetaData) Test(org.junit.Test)

Example 4 with PermissionFetcher

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

the class JsonLdEditEndpoint method submitChanges.

@PUT
public Response submitChanges(String jsonLdImport, @PathParam("user") String ownerId, @PathParam("dataset") String dataSetId, @HeaderParam("authorization") String authHeader) throws LogStorageFailedException {
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user.get(), ownerId, dataSetId);
    if (!dataSetOpt.isPresent()) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    final DataSet dataSet = dataSetOpt.get();
    final QuadStore quadStore = dataSet.getQuadStore();
    final ImportManager importManager = dataSet.getImportManager();
    final Response response = checkWriteAccess(dataSet, user, permissionFetcher);
    if (response != null) {
        return response;
    }
    try {
        final Future<ImportStatus> promise = importManager.generateLog(dataSet.getMetadata().getBaseUri(), dataSet.getMetadata().getBaseUri(), fromCurrentState(documentLoader, jsonLdImport, quadStore, TIM_USERS + user.get().getPersistentId(), UUID.randomUUID().toString(), Clock.systemUTC()));
        return handleImportManagerResult(promise);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (ConcurrentUpdateException e) {
        return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) 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) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) IOException(java.io.IOException) ConcurrentUpdateException(nl.knaw.huygens.timbuctoo.v5.jsonldimport.ConcurrentUpdateException) PUT(javax.ws.rs.PUT)

Example 5 with PermissionFetcher

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

the class DataSetRepositoryTest method removeDataSetRemovesTheDataSetsAuthorizations.

@Test
public void removeDataSetRemovesTheDataSetsAuthorizations() throws Exception {
    User user = User.create(null, "user");
    final DataSet dataSet = dataSetRepository.createDataSet(user, "dataset");
    DataSetMetaData metadata = dataSet.getMetadata();
    String owner = metadata.getOwnerId();
    given(permissionFetcher.getPermissions(user, metadata)).willReturn(Sets.newHashSet(Permission.ADMIN));
    dataSetRepository.removeDataSet(owner, "dataset", user);
    verify(permissionFetcher).removeAuthorizations(metadata.getCombinedId());
}
Also used : User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) DataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData) Test(org.junit.Test)

Aggregations

User (nl.knaw.huygens.timbuctoo.v5.security.dto.User)6 Test (org.junit.Test)6 BasicDataSetMetaData (nl.knaw.huygens.timbuctoo.v5.dataset.dto.BasicDataSetMetaData)5 PermissionFetcher (nl.knaw.huygens.timbuctoo.v5.security.PermissionFetcher)5 Response (javax.ws.rs.core.Response)4 DataSetMetaData (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData)3 UserValidator (nl.knaw.huygens.timbuctoo.v5.security.UserValidator)3 DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)2 Permission (nl.knaw.huygens.timbuctoo.v5.security.dto.Permission)2 UserValidationException (nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException)2 ExecutionResult (graphql.ExecutionResult)1 GraphQL (graphql.GraphQL)1 GraphQLSchema (graphql.schema.GraphQLSchema)1 IOException (java.io.IOException)1 PUT (javax.ws.rs.PUT)1 StreamingOutput (javax.ws.rs.core.StreamingOutput)1 ImportManager (nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager)1 ImportStatus (nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus)1 QuadStore (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore)1 SerializerWriter (nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes.SerializerWriter)1