Search in sources :

Example 26 with QueryImpl

use of org.molgenis.data.support.QueryImpl in project molgenis by molgenis.

the class RestControllerTest method loginPasswordReset.

@Test
public void loginPasswordReset() throws Exception {
    String username = "henk";
    String password = "123henk";
    Authentication authentication = mock(Authentication.class);
    when(authentication.isAuthenticated()).thenReturn(true);
    when(authentication.getName()).thenReturn(username);
    when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))).thenReturn(authentication);
    User user = mock(User.class);
    when(user.isChangePassword()).thenReturn(true);
    when(dataService.findOne(UserMetaData.USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, username), User.class)).thenReturn(user);
    mockMvc.perform(post(BASE_URI + "/login").content(format("{username: '%s', password: '%s'}", username, password)).contentType(APPLICATION_JSON)).andExpect(status().isUnauthorized());
}
Also used : QueryImpl(org.molgenis.data.support.QueryImpl) User(org.molgenis.data.security.auth.User) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Test(org.testng.annotations.Test)

Example 27 with QueryImpl

use of org.molgenis.data.support.QueryImpl in project molgenis by molgenis.

the class QueryStringParser method parseQueryString.

public Query<Entity> parseQueryString(Map<String, String[]> parameterMap) {
    QueryImpl<Entity> q = new QueryImpl<>();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
        String paramName = entry.getKey();
        String[] paramValues = entry.getValue();
        if ((paramValues != null) && (paramValues.length > 0) && (paramValues[0] != null)) {
            if (paramName.equalsIgnoreCase("num")) {
                q.pageSize(DataConverter.toInt(paramValues[0]));
            } else if (paramName.equalsIgnoreCase("start")) {
                q.offset(DataConverter.toInt(paramValues[0]));
            } else if (paramName.equalsIgnoreCase("q")) {
                Query<Entity> query = molgenisRSQL.createQuery(paramValues[0], entityType);
                for (QueryRule rule : query.getRules()) {
                    q.addRule(rule);
                }
            }
        }
    }
    return q;
}
Also used : Entity(org.molgenis.data.Entity) QueryImpl(org.molgenis.data.support.QueryImpl) QueryRule(org.molgenis.data.QueryRule) Map(java.util.Map)

Example 28 with QueryImpl

use of org.molgenis.data.support.QueryImpl in project molgenis by molgenis.

the class RestController method login.

/**
 * Login to the api.
 * <p>
 * Returns a json object with a token on correct login else throws an AuthenticationException. Clients can use this
 * token when calling the api.
 * <p>
 * Example:
 * <p>
 * Request: {username:admin,password:xxx}
 * <p>
 * Response: {token: b4fd94dc-eae6-4d9a-a1b7-dd4525f2f75d}
 */
@PostMapping(value = "/login", produces = APPLICATION_JSON_VALUE)
@ResponseBody
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) {
    if (login == null) {
        throw new HttpMessageNotReadableException("Missing login");
    }
    if (isUser2fa()) {
        throw new BadCredentialsException("Login using /api/v1/login is disabled, two factor authentication is enabled");
    }
    return runAsSystem(() -> {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
        authToken.setDetails(new WebAuthenticationDetails(request));
        // Authenticate the login
        Authentication authentication = authenticationManager.authenticate(authToken);
        if (!authentication.isAuthenticated()) {
            throw new BadCredentialsException("Unknown username or password");
        }
        User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class);
        if (user.isChangePassword()) {
            throw new BadCredentialsException("Unable to log in because a password reset is required. Sign in to the website to reset your password.");
        }
        // User authenticated, log the user in
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Generate a new token for the user
        String token = tokenService.generateAndStoreToken(authentication.getName(), "REST API login");
        return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName());
    });
}
Also used : QueryImpl(org.molgenis.data.support.QueryImpl) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) User(org.molgenis.data.security.auth.User) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 29 with QueryImpl

use of org.molgenis.data.support.QueryImpl in project molgenis by molgenis.

the class QueryValidatorTest method validateInvalidProvider.

@DataProvider(name = "validateInvalidProvider")
public static Iterator<Object[]> validateInvalidProvider() {
    List<Object[]> queries = new ArrayList<>(6);
    EnumSet.of(BOOL, DECIMAL, INT, LONG, DATE, DATE_TIME, ENUM).forEach(attrType -> queries.add(new Object[] { new QueryImpl().eq("attr", "invalid"), createEntityType(attrType) }));
    EnumSet.of(BOOL, DECIMAL, INT, LONG, DATE, DATE_TIME, ENUM, XREF, MREF, CATEGORICAL, CATEGORICAL_MREF).forEach(attrType -> queries.add(new Object[] { new QueryImpl().eq("attr", new Object()), createEntityType(attrType) }));
    queries.add(new Object[] { new QueryImpl().eq("unknownAttr", "str"), createEntityType(STRING) });
    queries.add(new Object[] { new QueryImpl().eq("attr", "str"), createEntityType(COMPOUND) });
    return queries.iterator();
}
Also used : QueryImpl(org.molgenis.data.support.QueryImpl) ArrayList(java.util.ArrayList) DataProvider(org.testng.annotations.DataProvider)

Example 30 with QueryImpl

use of org.molgenis.data.support.QueryImpl in project molgenis by molgenis.

the class RepositoryValidationDecorator method initReferenceValidation.

private void initReferenceValidation(ValidationResource validationResource) {
    // get reference attrs
    List<Attribute> refAttrs;
    if (!getCapabilities().contains(VALIDATE_REFERENCE_CONSTRAINT)) {
        // get reference attrs
        refAttrs = stream(getEntityType().getAtomicAttributes().spliterator(), false).filter(attr -> isReferenceType(attr) && attr.getExpression() == null).collect(toList());
    } else {
        // validate cross-repository collection reference constraints. the decorated repository takes care of
        // validating other reference constraints
        String backend = dataService.getMeta().getBackend(getEntityType()).getName();
        refAttrs = stream(getEntityType().getAtomicAttributes().spliterator(), false).filter(attr -> isReferenceType(attr) && attr.getExpression() == null && isDifferentBackend(backend, attr)).collect(toList());
    }
    // get referenced entity ids
    if (!refAttrs.isEmpty()) {
        Map<String, HugeSet<Object>> refEntitiesIds = new HashMap<>();
        refAttrs.forEach(refAttr -> {
            EntityType refEntityType = refAttr.getRefEntity();
            String refEntityName = refEntityType.getId();
            HugeSet<Object> refEntityIds = refEntitiesIds.get(refEntityName);
            if (refEntityIds == null) {
                refEntityIds = new HugeSet<>();
                refEntitiesIds.put(refEntityName, refEntityIds);
                Query<Entity> q = new QueryImpl<>().fetch(new Fetch().field(refEntityType.getIdAttribute().getName()));
                for (Iterator<Entity> it = dataService.findAll(refEntityName, q).iterator(); it.hasNext(); ) {
                    refEntityIds.add(it.next().getIdValue());
                }
            }
        });
        validationResource.setRefEntitiesIds(refEntitiesIds);
    }
    validationResource.setSelfReferencing(refAttrs.stream().anyMatch(refAttr -> refAttr.getRefEntity().getId().equals(getEntityType().getId())));
    validationResource.setRefAttrs(refAttrs);
}
Also used : java.util(java.util) RepositoryCapability(org.molgenis.data.RepositoryCapability) org.molgenis.data(org.molgenis.data) IOException(java.io.IOException) QueryImpl(org.molgenis.data.support.QueryImpl) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) Attribute(org.molgenis.data.meta.model.Attribute) EntityType(org.molgenis.data.meta.model.EntityType) String.format(java.lang.String.format) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) StreamSupport.stream(java.util.stream.StreamSupport.stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Objects.requireNonNull(java.util.Objects.requireNonNull) HugeSet(org.molgenis.util.HugeSet) HugeMap(org.molgenis.util.HugeMap) Collections(java.util.Collections) Attribute(org.molgenis.data.meta.model.Attribute) EntityType(org.molgenis.data.meta.model.EntityType) HugeSet(org.molgenis.util.HugeSet)

Aggregations

QueryImpl (org.molgenis.data.support.QueryImpl)98 Test (org.testng.annotations.Test)70 DynamicEntity (org.molgenis.data.support.DynamicEntity)37 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)36 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)36 EntityType (org.molgenis.data.meta.model.EntityType)28 Attribute (org.molgenis.data.meta.model.Attribute)25 Entity (org.molgenis.data.Entity)15 WithMockUser (org.springframework.security.test.context.support.WithMockUser)8 Stream (java.util.stream.Stream)7 AbstractMolgenisSpringTest (org.molgenis.data.AbstractMolgenisSpringTest)7 AggregateQueryImpl (org.molgenis.data.support.AggregateQueryImpl)7 Objects.requireNonNull (java.util.Objects.requireNonNull)6 QueryRule (org.molgenis.data.QueryRule)6 AggregateQuery (org.molgenis.data.aggregation.AggregateQuery)6 EntityTypeIdentity (org.molgenis.data.security.EntityTypeIdentity)6 BeforeMethod (org.testng.annotations.BeforeMethod)6 Instant (java.time.Instant)5 LocalDate (java.time.LocalDate)5 Operator (org.molgenis.data.QueryRule.Operator)5