ownerType,
27 | @NonNull Class entityType,
28 | @NonNull BaseService ownerBaseService,
29 | @NonNull BaseService policyBaseService,
30 | @NonNull NameablePermissionRepository repository) {
31 | super(ownerType, entityType, ownerBaseService, policyBaseService, repository);
32 | this.nameablePermissionRepository = repository;
33 | this.ownerType = ownerType;
34 | this.policyBaseService = policyBaseService;
35 | this.ownerBaseService = ownerBaseService;
36 | }
37 |
38 | protected PolicyResponse convertToPolicyResponse(@NonNull P p) {
39 | val name = p.getOwner().getName();
40 | val id = p.getOwner().getId().toString();
41 | val mask = p.getAccessLevel();
42 | return PolicyResponse.builder().name(name).id(id).mask(mask).build();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/AbstractNamedService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import static bio.overture.ego.model.exceptions.NotFoundException.checkNotFound;
4 |
5 | import bio.overture.ego.model.entity.Identifiable;
6 | import bio.overture.ego.repository.NamedRepository;
7 | import java.util.Optional;
8 | import lombok.NonNull;
9 | import lombok.val;
10 |
11 | public abstract class AbstractNamedService, ID>
12 | extends AbstractBaseService implements NamedService {
13 |
14 | private final NamedRepository namedRepository;
15 |
16 | public AbstractNamedService(
17 | @NonNull Class entityType, @NonNull NamedRepository repository) {
18 | super(entityType, repository);
19 | this.namedRepository = repository;
20 | }
21 |
22 | @Override
23 | public Optional findByName(@NonNull String name) {
24 | return namedRepository.findByName(name);
25 | }
26 |
27 | @Override
28 | public T getByName(@NonNull String name) {
29 | val result = findByName(name);
30 | checkNotFound(
31 | result.isPresent(),
32 | "The '%s' entity with name '%s' was not found",
33 | getEntityTypeName(),
34 | name);
35 | return result.get();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/BaseService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import static java.lang.String.format;
4 |
5 | import bio.overture.ego.model.exceptions.NotFoundException;
6 | import bio.overture.ego.repository.queryspecification.builder.AbstractSpecificationBuilder;
7 | import java.util.Collection;
8 | import java.util.List;
9 | import java.util.Optional;
10 | import java.util.Set;
11 | import lombok.NonNull;
12 | import lombok.val;
13 | import org.springframework.data.domain.Page;
14 | import org.springframework.data.domain.Pageable;
15 | import org.springframework.data.jpa.domain.Specification;
16 |
17 | public interface BaseService {
18 |
19 | String getEntityTypeName();
20 |
21 | default T getById(@NonNull ID id) {
22 | val entity = findById(id);
23 | return entity.orElseThrow(
24 | () ->
25 | new NotFoundException(
26 | format(
27 | "The '%s' entity with id '%s' does not exist",
28 | getEntityTypeName(), id.toString())));
29 | }
30 |
31 | Optional findById(ID id);
32 |
33 | boolean isExist(ID id);
34 |
35 | void delete(ID id);
36 |
37 | long countAll();
38 |
39 | Page findAll(Specification specification, Pageable pageable);
40 |
41 | Page findAll(AbstractSpecificationBuilder specificationBuilder, Pageable pageable);
42 |
43 | List getMany(Collection ids, AbstractSpecificationBuilder specificationBuilder);
44 |
45 | Set getMany(Collection ids);
46 |
47 | T getWithRelationships(ID id);
48 |
49 | void checkExistence(Collection ids);
50 |
51 | void checkExistence(ID id);
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/DefaultProviderService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import static bio.overture.ego.model.exceptions.NotFoundException.buildNotFoundException;
4 | import static bio.overture.ego.utils.CollectionUtils.convertToUnmodifiableList;
5 |
6 | import bio.overture.ego.model.entity.DefaultProvider;
7 | import bio.overture.ego.model.enums.ProviderType;
8 | import bio.overture.ego.repository.DefaultProviderRepository;
9 | import java.util.List;
10 | import lombok.NonNull;
11 | import lombok.extern.slf4j.Slf4j;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.stereotype.Service;
14 |
15 | @Slf4j
16 | @Service
17 | public class DefaultProviderService extends AbstractBaseService {
18 |
19 | private final DefaultProviderRepository defaultProviderRepository;
20 |
21 | @Autowired
22 | public DefaultProviderService(@NonNull DefaultProviderRepository defaultProviderRepository) {
23 | super(DefaultProvider.class, defaultProviderRepository);
24 | this.defaultProviderRepository = defaultProviderRepository;
25 | }
26 |
27 | @Override
28 | public DefaultProvider getWithRelationships(@NonNull ProviderType id) {
29 | return defaultProviderRepository
30 | .findById(id)
31 | .orElseThrow(() -> buildNotFoundException("Could not find default provider type '%s'", id));
32 | }
33 |
34 | public List findAll() {
35 | return convertToUnmodifiableList(getRepository().findAll());
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/GithubService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import static bio.overture.ego.utils.Joiners.BLANK;
4 |
5 | import java.util.Arrays;
6 | import java.util.Collections;
7 | import java.util.List;
8 | import java.util.Map;
9 | import lombok.NonNull;
10 | import lombok.val;
11 | import org.springframework.core.ParameterizedTypeReference;
12 | import org.springframework.http.HttpMethod;
13 | import org.springframework.stereotype.Service;
14 | import org.springframework.web.client.RestTemplate;
15 |
16 | @Service
17 | public class GithubService {
18 |
19 | public String getVerifiedEmail(RestTemplate restTemplate) {
20 | String email;
21 | email =
22 | (String)
23 | restTemplate
24 | .exchange(
25 | "https://api.github.com/user/emails",
26 | HttpMethod.GET,
27 | null,
28 | new ParameterizedTypeReference>>() {})
29 | .getBody().stream()
30 | .filter(x -> x.get("verified").equals(true) && x.get("primary").equals(true))
31 | .findAny()
32 | .orElse(Collections.emptyMap())
33 | .get("email");
34 | return email;
35 | }
36 |
37 | public Map parseName(@NonNull String name, Map map) {
38 | List names = Arrays.asList(name.split(" "));
39 | val numNames = names.size();
40 |
41 | if (numNames > 0) {
42 | if (numNames == 1) {
43 | map.put("given_name", names.get(0));
44 | } else {
45 | List firstNames = names.subList(0, numNames - 1);
46 | List lastName = names.subList(numNames - 1, numNames);
47 | map.put("given_name", BLANK.join(firstNames));
48 | map.put("family_name", lastName.get(0));
49 | }
50 | }
51 | return map;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/NamedService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import java.util.Optional;
4 |
5 | public interface NamedService extends BaseService {
6 |
7 | Optional findByName(String name);
8 |
9 | T getByName(String name);
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/service/UserGroupService.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import bio.overture.ego.model.join.UserGroup;
4 | import lombok.NonNull;
5 |
6 | public class UserGroupService {
7 |
8 | public static void associateSelf(@NonNull UserGroup ug) {
9 | ug.getGroup().getUserGroups().add(ug);
10 | ug.getUser().getUserGroups().add(ug);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/IDToken.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token;
18 |
19 | import bio.overture.ego.model.enums.ProviderType;
20 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
21 | import com.fasterxml.jackson.annotation.JsonProperty;
22 | import lombok.*;
23 |
24 | @Data
25 | @Builder
26 | @NoArgsConstructor
27 | @AllArgsConstructor
28 | @JsonIgnoreProperties(ignoreUnknown = true)
29 | public class IDToken {
30 |
31 | private String email;
32 |
33 | @JsonProperty("given_name")
34 | private String givenName;
35 |
36 | @JsonProperty("family_name")
37 | private String familyName;
38 |
39 | @JsonProperty("provider_type")
40 | @NonNull
41 | ProviderType providerType;
42 |
43 | @JsonProperty("provider_subject_id")
44 | @NonNull
45 | String providerSubjectId;
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/TokenClaims.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token;
18 |
19 | import bio.overture.ego.view.Views;
20 | import com.fasterxml.jackson.annotation.JsonIgnore;
21 | import com.fasterxml.jackson.annotation.JsonView;
22 | import java.util.UUID;
23 | import lombok.*;
24 |
25 | @Data
26 | @NoArgsConstructor
27 | @JsonView(Views.JWTAccessToken.class)
28 | public abstract class TokenClaims {
29 | @NonNull protected Integer iat;
30 |
31 | @NonNull protected Integer exp;
32 |
33 | @NonNull @JsonIgnore protected Integer validDuration;
34 |
35 | @Getter protected String sub;
36 |
37 | @NonNull protected String iss;
38 |
39 | /*
40 | Defaults
41 | */
42 | private String jti = UUID.randomUUID().toString();
43 |
44 | @Getter(AccessLevel.NONE)
45 | @Setter(AccessLevel.NONE)
46 | @JsonIgnore
47 | private long initTime = System.currentTimeMillis();
48 |
49 | public int getExp() {
50 | return ((int) ((this.initTime + validDuration) / 1000L));
51 | }
52 |
53 | public int getIat() {
54 | return (int) (this.initTime / 1000L);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/app/AppTokenClaims.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token.app;
18 |
19 | import bio.overture.ego.token.TokenClaims;
20 | import bio.overture.ego.view.Views;
21 | import com.fasterxml.jackson.annotation.JsonView;
22 | import lombok.Data;
23 | import lombok.NoArgsConstructor;
24 | import lombok.NonNull;
25 | import org.springframework.security.oauth2.core.AuthorizationGrantType;
26 | import org.springframework.util.StringUtils;
27 |
28 | @Data
29 | @NoArgsConstructor
30 | @JsonView(Views.JWTAccessToken.class)
31 | public class AppTokenClaims extends TokenClaims {
32 |
33 | /*
34 | Constants
35 | */
36 | public static final AuthorizationGrantType[] AUTHORIZED_GRANT_TYPES = {
37 | AuthorizationGrantType.AUTHORIZATION_CODE,
38 | AuthorizationGrantType.CLIENT_CREDENTIALS,
39 | AuthorizationGrantType.REFRESH_TOKEN
40 | };
41 | public static final String ROLE = "ROLE_CLIENT";
42 |
43 | @NonNull private AppTokenContext context;
44 |
45 | public String getSub() {
46 | if (StringUtils.isEmpty(sub)) {
47 | return String.valueOf(this.context.getAppInfo().getId());
48 | } else {
49 | return sub;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/app/AppTokenContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token.app;
18 |
19 | import bio.overture.ego.model.entity.Application;
20 | import bio.overture.ego.view.Views;
21 | import com.fasterxml.jackson.annotation.JsonInclude;
22 | import com.fasterxml.jackson.annotation.JsonProperty;
23 | import com.fasterxml.jackson.annotation.JsonView;
24 | import java.util.Set;
25 | import lombok.*;
26 |
27 | @Data
28 | @NoArgsConstructor
29 | @RequiredArgsConstructor
30 | @JsonInclude(JsonInclude.Include.ALWAYS)
31 | @JsonView(Views.JWTAccessToken.class)
32 | public class AppTokenContext {
33 |
34 | @NonNull
35 | @JsonProperty("application")
36 | private Application appInfo;
37 |
38 | private Set scope;
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/signer/TokenSigner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token.signer;
18 |
19 | import java.security.Key;
20 | import java.security.KeyPair;
21 | import java.util.Optional;
22 |
23 | public interface TokenSigner {
24 |
25 | Optional getKey();
26 |
27 | Optional getKeyPair();
28 |
29 | Optional getEncodedPublicKey();
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/user/UserTokenClaims.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token.user;
18 |
19 | import bio.overture.ego.model.entity.Application;
20 | import bio.overture.ego.model.join.UserApplication;
21 | import bio.overture.ego.token.TokenClaims;
22 | import bio.overture.ego.view.Views;
23 | import com.fasterxml.jackson.annotation.JsonView;
24 | import java.util.List;
25 | import java.util.stream.Collectors;
26 | import lombok.Data;
27 | import lombok.Getter;
28 | import lombok.NoArgsConstructor;
29 | import lombok.NonNull;
30 | import org.springframework.util.StringUtils;
31 |
32 | @Data
33 | @NoArgsConstructor
34 | @JsonView(Views.JWTAccessToken.class)
35 | public class UserTokenClaims extends TokenClaims {
36 |
37 | @NonNull private UserTokenContext context;
38 |
39 | @Getter protected List aud;
40 |
41 | public String getSub() {
42 | if (StringUtils.isEmpty(sub)) {
43 | return String.valueOf(this.context.getUserInfo().getId());
44 | } else {
45 | return sub;
46 | }
47 | }
48 |
49 | public List getAud() {
50 | return this.context.getUserInfo().getUserApplications().stream()
51 | .map(UserApplication::getApplication)
52 | .map(Application::getName)
53 | .collect(Collectors.toList());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/token/user/UserTokenContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.token.user;
18 |
19 | import bio.overture.ego.model.entity.User;
20 | import bio.overture.ego.view.Views;
21 | import com.fasterxml.jackson.annotation.JsonInclude;
22 | import com.fasterxml.jackson.annotation.JsonProperty;
23 | import com.fasterxml.jackson.annotation.JsonView;
24 | import java.util.Set;
25 | import lombok.Data;
26 | import lombok.NoArgsConstructor;
27 | import lombok.NonNull;
28 | import lombok.RequiredArgsConstructor;
29 |
30 | @Data
31 | @NoArgsConstructor
32 | @RequiredArgsConstructor
33 | @JsonInclude(JsonInclude.Include.ALWAYS)
34 | @JsonView(Views.JWTAccessToken.class)
35 | public class UserTokenContext {
36 | @NonNull
37 | @JsonProperty("user")
38 | private User userInfo;
39 |
40 | private Set scope;
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Collectors.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static lombok.AccessLevel.PRIVATE;
4 |
5 | import com.google.common.collect.ImmutableList;
6 | import com.google.common.collect.ImmutableMap;
7 | import com.google.common.collect.ImmutableSet;
8 | import java.util.function.BiConsumer;
9 | import java.util.function.Function;
10 | import java.util.stream.Collector;
11 | import lombok.NoArgsConstructor;
12 | import lombok.NonNull;
13 |
14 | @NoArgsConstructor(access = PRIVATE)
15 | public class Collectors {
16 |
17 | public static Collector, ImmutableList> toImmutableList() {
18 | return Collector.of(
19 | ImmutableList.Builder::new,
20 | ImmutableList.Builder::add,
21 | (b1, b2) -> b1.addAll(b2.build()),
22 | ImmutableList.Builder::build);
23 | }
24 |
25 | public static Collector, ImmutableSet> toImmutableSet() {
26 | return Collector.of(
27 | ImmutableSet.Builder::new,
28 | ImmutableSet.Builder::add,
29 | (b1, b2) -> b1.addAll(b2.build()),
30 | ImmutableSet.Builder::build);
31 | }
32 |
33 | public static
34 | Collector, ImmutableMap> toImmutableMap(
35 | @NonNull Function super T, ? extends K> keyMapper,
36 | @NonNull Function super T, ? extends V> valueMapper) {
37 |
38 | final BiConsumer, T> accumulator =
39 | (builder, entry) -> builder.put(keyMapper.apply(entry), valueMapper.apply(entry));
40 |
41 | return Collector.of(
42 | ImmutableMap.Builder::new,
43 | accumulator,
44 | (b1, b2) -> b1.putAll(b2.build()),
45 | ImmutableMap.Builder::build);
46 | }
47 |
48 | public static Collector, ImmutableMap> toImmutableMap(
49 | @NonNull Function super T, ? extends K> keyMapper) {
50 | return toImmutableMap(keyMapper, Function.identity());
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Defaults.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import lombok.SneakyThrows;
4 |
5 | public class Defaults {
6 | T val;
7 |
8 | @SneakyThrows
9 | Defaults(T value) {
10 | val = value;
11 | }
12 |
13 | static Defaults create(X value) {
14 | return new Defaults<>(value);
15 | }
16 |
17 | T def(T value) {
18 | return value == null ? val : value;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/HibernateSessions.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import java.util.Collection;
4 | import java.util.List;
5 | import java.util.Set;
6 | import lombok.NonNull;
7 | import lombok.extern.slf4j.Slf4j;
8 | import lombok.val;
9 | import org.hibernate.collection.internal.AbstractPersistentCollection;
10 |
11 | @Slf4j
12 | public class HibernateSessions {
13 |
14 | public static void unsetSession(@NonNull Set property) {
15 | unsetSession((Collection) property);
16 | }
17 |
18 | public static void unsetSession(@NonNull List property) {
19 | unsetSession((Collection) property);
20 | }
21 |
22 | public static void unsetSession(@NonNull Collection property) {
23 | if (property instanceof AbstractPersistentCollection) {
24 | val persistentProperty = (AbstractPersistentCollection) property;
25 | persistentProperty.unsetSession(persistentProperty.getSession());
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Ids.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static bio.overture.ego.model.exceptions.MalformedRequestException.checkMalformedRequest;
4 | import static bio.overture.ego.utils.CollectionUtils.findDuplicates;
5 | import static bio.overture.ego.utils.Joiners.PRETTY_COMMA;
6 | import static lombok.AccessLevel.PRIVATE;
7 |
8 | import bio.overture.ego.model.entity.Identifiable;
9 | import java.util.Collection;
10 | import java.util.UUID;
11 | import lombok.NoArgsConstructor;
12 | import lombok.val;
13 |
14 | @NoArgsConstructor(access = PRIVATE)
15 | public class Ids {
16 |
17 | public static > void checkDuplicates(
18 | Class entityType, Collection ids) {
19 | // check duplicate ids
20 | val duplicateIds = findDuplicates(ids);
21 | checkMalformedRequest(
22 | duplicateIds.isEmpty(),
23 | "The following %s ids contain duplicates: [%s]",
24 | entityType.getSimpleName(),
25 | PRETTY_COMMA.join(duplicateIds));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Joiners.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static lombok.AccessLevel.PRIVATE;
4 |
5 | import com.google.common.base.Joiner;
6 | import lombok.NoArgsConstructor;
7 |
8 | @NoArgsConstructor(access = PRIVATE)
9 | public class Joiners {
10 |
11 | public static final Joiner COMMA = Joiner.on(",");
12 | public static final Joiner NEWLINE_COMMA = Joiner.on(",\n");
13 | public static final Joiner PRETTY_COMMA = Joiner.on(" , ");
14 | public static final Joiner PATH = Joiner.on("/");
15 | public static final Joiner AMPERSAND = Joiner.on("&");
16 | public static final Joiner BLANK = Joiner.on(" ");
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/PolicyPermissionUtils.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static bio.overture.ego.utils.CollectionUtils.mapToList;
4 |
5 | import bio.overture.ego.model.entity.AbstractPermission;
6 | import java.util.Collection;
7 | import java.util.List;
8 | import lombok.NonNull;
9 |
10 | public class PolicyPermissionUtils {
11 |
12 | public static String extractPermissionString(@NonNull AbstractPermission permission) {
13 | return String.format(
14 | "%s.%s", permission.getPolicy().getName(), permission.getAccessLevel().toString());
15 | }
16 |
17 | public static List extractPermissionStrings(
18 | @NonNull Collection extends AbstractPermission> permissions) {
19 | return mapToList(permissions, PolicyPermissionUtils::extractPermissionString);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/QueryUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.utils;
18 |
19 | import lombok.extern.slf4j.Slf4j;
20 | import org.springframework.util.StringUtils;
21 |
22 | @Slf4j
23 | public class QueryUtils {
24 |
25 | public static String prepareForQuery(String text) {
26 | String output = text;
27 | if (StringUtils.isEmpty(output)) {
28 | return "%";
29 | }
30 | if (!output.contains("%")) {
31 | output = "%" + output + "%";
32 | }
33 | return output.toLowerCase();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Splitters.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static lombok.AccessLevel.PRIVATE;
4 |
5 | import com.google.common.base.Splitter;
6 | import lombok.NoArgsConstructor;
7 |
8 | @NoArgsConstructor(access = PRIVATE)
9 | public class Splitters {
10 |
11 | public static final Splitter COMMA_SPLITTER = Splitter.on(',');
12 | public static final Splitter COLON_SPLITTER = Splitter.on(':');
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Streams.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import java.util.Iterator;
5 | import java.util.stream.Stream;
6 | import java.util.stream.StreamSupport;
7 | import lombok.NonNull;
8 |
9 | public class Streams {
10 |
11 | public static Stream stream(@NonNull Iterator iterator) {
12 | return stream(() -> iterator, false);
13 | }
14 |
15 | public static Stream stream(@NonNull Iterable iterable) {
16 | return stream(iterable, false);
17 | }
18 |
19 | @SafeVarargs
20 | public static Stream stream(@NonNull T... values) {
21 | return ImmutableList.copyOf(values).stream();
22 | }
23 |
24 | /*
25 | * Helpers
26 | */
27 | private static Stream stream(Iterable iterable, boolean inParallel) {
28 | return StreamSupport.stream(iterable.spliterator(), inParallel);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Strings.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static java.util.Objects.nonNull;
4 |
5 | import lombok.NoArgsConstructor;
6 |
7 | @NoArgsConstructor
8 | public final class Strings {
9 | public static boolean isDefined(String s) {
10 | return nonNull(s) && !s.isBlank();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/SwaggerConstants.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | public class SwaggerConstants {
4 | public static final String AUTH_CONTROLLER = "auth-controller";
5 | public static final String POST_ACCESS_TOKEN = "postAccessToken";
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/Tokens.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2019. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package bio.overture.ego.utils;
19 |
20 | public class Tokens {
21 |
22 | public static String removeTokenPrefix(String token, String prefix) {
23 | return token.replace(prefix, "").trim();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/utils/TypeUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.utils;
18 |
19 | import com.fasterxml.jackson.core.JsonGenerator;
20 | import com.fasterxml.jackson.databind.DeserializationFeature;
21 | import com.fasterxml.jackson.databind.MapperFeature;
22 | import com.fasterxml.jackson.databind.ObjectMapper;
23 | import java.io.IOException;
24 | import lombok.val;
25 |
26 | public class TypeUtils {
27 | public static T convertToAnotherType(
28 | Object fromObject, Class tClass, Class> serializationView) throws IOException {
29 | val mapper = new ObjectMapper();
30 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
31 | mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
32 | mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
33 | val serializedValue = mapper.writerWithView(serializationView).writeValueAsBytes(fromObject);
34 | return mapper.readValue(serializedValue, tClass);
35 | }
36 |
37 | public static T convertToAnotherType(Object fromObject, Class tClass) {
38 | val mapper = new ObjectMapper();
39 | mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
40 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
41 | return mapper.convertValue(fromObject, tClass);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/bio/overture/ego/view/Views.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package bio.overture.ego.view;
18 |
19 | public interface Views {
20 | interface JWTAccessToken {};
21 |
22 | interface REST {};
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/lib/libwrapper-linux-x86-64.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/overture-stack/ego/5034b11fefd55ad6c868fe737ed73e708feb625c/src/main/lib/libwrapper-linux-x86-64.so
--------------------------------------------------------------------------------
/src/main/lib/libwrapper-macosx-universal-64.jnilib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/overture-stack/ego/5034b11fefd55ad6c868fe737ed73e708feb625c/src/main/lib/libwrapper-macosx-universal-64.jnilib
--------------------------------------------------------------------------------
/src/main/lib/wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/overture-stack/ego/5034b11fefd55ad6c868fe737ed73e708feb625c/src/main/lib/wrapper.jar
--------------------------------------------------------------------------------
/src/main/proto/Ego.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | import "google/protobuf/wrappers.proto";
3 |
4 | option java_multiple_files = true;
5 | option java_package = "bio.overture.ego.grpc";
6 | option java_outer_classname = "EgoProto";
7 |
8 | package bio.overture.ego.grpc;
9 |
10 | service UserService {
11 | rpc GetUser (GetUserRequest) returns (User) {}
12 | rpc ListUsers (ListUsersRequest) returns (ListUsersResponse) {}
13 | }
14 |
15 | message PagedRequest {
16 | uint32 page_number = 1;
17 | uint32 page_size = 2;
18 | string order_by = 3;
19 | }
20 |
21 | message PagedResponse {
22 | uint32 max_results = 1;
23 | google.protobuf.UInt32Value next_page = 2;
24 | }
25 |
26 | message GetUserRequest {
27 | string id = 1;
28 | }
29 |
30 | message ListUsersRequest {
31 | PagedRequest page = 1;
32 |
33 | google.protobuf.StringValue query = 2;
34 | repeated string group_ids = 3;
35 | }
36 |
37 | message ListUsersResponse {
38 | PagedResponse page = 1;
39 |
40 | repeated User users = 2;
41 | }
42 |
43 | message User {
44 | google.protobuf.StringValue id = 1;
45 | google.protobuf.StringValue email = 2;
46 | google.protobuf.StringValue first_name = 3;
47 | google.protobuf.StringValue last_name = 4;
48 |
49 | google.protobuf.StringValue created_at = 5;
50 | google.protobuf.StringValue last_login = 6;
51 | google.protobuf.StringValue preferred_language = 8;
52 | google.protobuf.StringValue status = 9;
53 | google.protobuf.StringValue type = 10;
54 |
55 | repeated string applications = 11;
56 | repeated string groups = 12;
57 | repeated string scopes = 13;
58 |
59 | google.protobuf.StringValue provider_type = 14;
60 | google.protobuf.StringValue provider_subject_id = 15;
61 |
62 | // removed name = 7 field as part of EGO-530
63 | reserved 7;
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/resources/bootstrap-iam.properties:
--------------------------------------------------------------------------------
1 | spring.cloud.vault.enabled=true
2 | spring.application.name=development/oicr/ego
3 | spring.cloud.vault.generic.default-context=${spring.application.name}
4 | spring.cloud.vault.uri=""
5 | spring.cloud.vault.authentication=AWS_IAM
6 | spring.cloud.vault.aws-iam.role=""
7 |
--------------------------------------------------------------------------------
/src/main/resources/bootstrap-token.properties:
--------------------------------------------------------------------------------
1 | spring.cloud.vault.enabled=true
2 | spring.application.name=ego-dev
3 | spring.cloud.vault.generic.default-context=${spring.application.name}
4 | spring.cloud.vault.kv.backend-version=1
5 | spring.cloud.vault.generic.backend=ego
6 | spring.cloud.vault.scheme=http
7 | spring.cloud.vault.host=localhost
8 | spring.cloud.vault.port=8200
9 | spring.cloud.vault.token=00000000-0000-0000-0000-000000000000
10 |
--------------------------------------------------------------------------------
/src/main/resources/bootstrap.properties:
--------------------------------------------------------------------------------
1 | spring.cloud.vault.enabled=false
2 |
--------------------------------------------------------------------------------
/src/main/resources/dummy-data/02-insert-dummy-groups.sql:
--------------------------------------------------------------------------------
1 | /* WARNING: Clears all data in the EgoGroup Table
2 |
3 | Clears the EgoGroup table and insert 5 sample groups (4 APPROVED, 1 PENDING)
4 | */
5 | TRUNCATE public.egogroup CASCADE;
6 |
7 | INSERT INTO egogroup (name, status, description) VALUES ('XYZ Cancer Research Institute', 'APPROVED', 'Sample group for elite cancer researchers');
8 | INSERT INTO egogroup (name, status, description) VALUES ('Extreme Research Consortium', 'APPROVED', 'Sample group for generalist researchers');
9 | INSERT INTO egogroup (name, status, description) VALUES ('Healthcare Providers Anonymous', 'APPROVED', 'Sample group for patient care specialist');
10 | INSERT INTO egogroup (name, status, description) VALUES ('Pediatric Patient Support Network', 'APPROVED', 'Sample group for patients and their supporters');
11 | INSERT INTO egogroup (name, status, description) VALUES ('Generic Genomics Geniuses', 'PENDING', 'Sample group for super-duper smart genetic investigators');
--------------------------------------------------------------------------------
/src/main/resources/dummy-data/03-insert-dummy-applications.sql:
--------------------------------------------------------------------------------
1 | /* WARNING: Clears all data in the EgoApplication Table
2 |
3 | Clears the EgoApplication table and insert 4 sample Applications (3 Approved, 1 Pending)
4 | */
5 | TRUNCATE public.egoapplication CASCADE;
6 |
7 | INSERT INTO EGOAPPLICATION (name, clientId, clientSecret, redirectUri, description, status) VALUES ('Example Data Portal', 'sample-data-portal', 'sample-data-portal-secret', 'http://google.com', 'Sample application for some data portal', 'Approved');
8 | INSERT INTO EGOAPPLICATION (name, clientId, clientSecret, redirectUri, description, status) VALUES ('Personal Information Manager', 'personal-info-manager', 'personal-info-manager-secret', 'http://yahoo.com', 'Sample application for some user manager', 'Approved');
9 | INSERT INTO EGOAPPLICATION (name, clientId, clientSecret, redirectUri, description, status) VALUES ('Daily News Feed', 'daily-news-feed', 'daily-news-feed-secret', 'http://bing.com', 'Sample application for some news feed', 'Approved');
10 | INSERT INTO EGOAPPLICATION (name, clientId, clientSecret, redirectUri, description, status) VALUES ('User Notification System', 'user-notification-system', 'user-notification-system-secret', 'http://aol.com', 'Sample application for a user notification management system', 'Pending');
--------------------------------------------------------------------------------
/src/main/resources/dummy-data/05-insert-dummy-rel-user-application.sql:
--------------------------------------------------------------------------------
1 | TRUNCATE public.userapplication CASCADE;
2 |
3 | -- 6 Users to Personal Information Manager
4 | INSERT INTO public.userapplication (userId, appId)
5 | SELECT u.id, a.id
6 | FROM public.egouser AS u
7 | LEFT JOIN public.egoapplication AS a
8 | ON a.name='Personal Information Manager'
9 | WHERE u.name IN ('Brennan.Denesik@example.com','Anika.Stehr@example.com','Janessa.Cronin@example.com','Sharon.Farrell@example.com','Zane.Rath@example.com','Elisha.Weimann@example.com');
10 |
11 | -- 35 Users to Example Data Portal
12 | INSERT INTO public.userapplication (userId, appId)
13 | SELECT u.id, a.id
14 | FROM public.egouser AS u
15 | LEFT JOIN public.egoapplication AS a
16 | ON a.name='Example Data Portal'
17 | WHERE u.name IN ('Justice.Heller@example.com','Sharon.Farrell@example.com','Janessa.Cronin@example.com','Shayne.Lubowitz@example.com','Gretchen.Wintheiser@example.com','Daija.Pacocha@example.com','Osvaldo.Bahringer@example.com','Halie.Heller@example.com','Chauncey.Schiller@example.com','Oral.Gleason@example.com','Lupe.Hilll@example.com','Jocelyn.Grant@example.com','Hollie.Kunde@example.com','Ed.Olson@example.com','Jeromy.Larkin@example.com','Marquis.Oberbrunner@example.com','Lyda.Macejkovic@example.com','Gordon.Ullrich@example.com','Kenton.Kilback@example.com','Maya.DuBuque@example.com','Jeromy.Abernathy@example.com','Furman.Volkman@example.com','Yesenia.Schmeler@example.com','Waylon.Wiza@example.com','Helen.Trantow@example.com','Claudine.McKenzie@example.com','Korbin.Sawayn@example.com','Brionna.Mertz@example.com','Orin.Mraz@example.com','Rusty.Hickle@example.com','Rafaela.Harvey@example.com','Herminio.Kub@example.com','Lera.White@example.com','Chandler.Collier@example.com','Edd.Thompson@example.com');
--------------------------------------------------------------------------------
/src/main/resources/dummy-data/06-insert-dummy-rel-group-application.sql:
--------------------------------------------------------------------------------
1 | TRUNCATE public.groupapplication CASCADE;
2 |
3 | -- Add all Approved groups to Perssonal Information Manager
4 | INSERT INTO public.groupapplication (grpId, appId)
5 | SELECT g.id, a.id
6 | FROM public.egogroup AS g
7 | LEFT JOIN public.egoapplication AS a
8 | ON a.name='Personal Information Manager'
9 | WHERE g.name IN ('Pediatric Patient Support Network', 'Extreme Research Consortium', 'XYZ Cancer Research Institute', 'Healthcare Providers Anonymous');
10 |
11 | -- Add Research Groups to the Data Portal
12 | INSERT INTO public.groupapplication (grpId, appId)
13 | SELECT g.id, a.id
14 | FROM public.egogroup AS g
15 | LEFT JOIN public.egoapplication AS a
16 | ON a.name='Example Data Portal'
17 | WHERE g.name IN ('XYZ Cancer Research Institute', 'Extreme Research Consortium');
--------------------------------------------------------------------------------
/src/main/resources/dummy-data/reset-dummy-data.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -o nounset
3 | set -o errexit
4 |
5 | # usage: ./reset-dummy-data.sh --path='/srv/ego/dummy-data' --user='dbuser' --log='/path/to/logfile.log'
6 | # Note: This script assumes that there is a PGPASSFILE with the required password for that user.
7 |
8 | while [ $# -gt 0 ]; do
9 | case "$1" in
10 | --path=*)
11 | path="${1#*=}"
12 | ;;
13 | --user=*)
14 | user="${1#*=}"
15 | ;;
16 | --log=*)
17 | log="${1#*=}"
18 | ;;
19 | *)
20 | printf "***************************\n"
21 | printf "* Error: Invalid argument.*\n"
22 | printf "***************************\n"
23 | exit 1
24 | esac
25 | shift
26 | done
27 |
28 | psql -w -U $user ego -a -f $path/01-insert-dummy-users.sql -L $log
29 | psql -w -U $user ego -a -f $path/02-insert-dummy-groups.sql -L $log
30 | psql -w -U $user ego -a -f $path/03-insert-dummy-applications.sql -L $log
31 | psql -w -U $user ego -a -f $path/04-insert-dummy-rel-user-group.sql -L $log
32 | psql -w -U $user ego -a -f $path/05-insert-dummy-rel-user-application.sql -L $log
33 | psql -w -U $user ego -a -f $path/06-insert-dummy-rel-group-application.sql -L $log
--------------------------------------------------------------------------------
/src/main/resources/ego-jwt.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/overture-stack/ego/5034b11fefd55ad6c868fe737ed73e708feb625c/src/main/resources/ego-jwt.jks
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_10__remove_apps_from_apitokens.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE tokenapplication;
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_11__add_expiry_date_api_tokens.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE token ADD expirydate TIMESTAMP NOT NULL DEFAULT NOW();
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_12__egoapplication_unique_constraints.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE egoapplication ADD CONSTRAINT egoapplication_name_key UNIQUE (name);
2 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_13__fname_lname_not_null_constraints.sql:
--------------------------------------------------------------------------------
1 | UPDATE egouser SET lastname = '' WHERE lastname IS NULL;
2 | ALTER TABLE egouser ALTER COLUMN lastname SET NOT NULL;
3 | ALTER TABLE egouser ALTER COLUMN lastname SET DEFAULT '';
4 |
5 | UPDATE egouser SET firstname = '' WHERE firstname IS NULL;
6 | ALTER TABLE egouser ALTER COLUMN firstname SET NOT NULL;
7 | ALTER TABLE egouser ALTER COLUMN firstname SET DEFAULT '';
8 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_14__indices.sql:
--------------------------------------------------------------------------------
1 | CREATE INDEX idx_usergroup_user ON usergroup(user_id);
2 | CREATE INDEX idx_usergroup_group ON usergroup(group_id);
3 | CREATE INDEX idx_usergroup_both ON usergroup(user_id, group_id);
4 |
5 | CREATE INDEX idx_userpermission_user ON userpermission(user_id);
6 | CREATE INDEX idx_userpermission_policy ON userpermission(policy_id);
7 | CREATE INDEX idx_userpermission_both ON userpermission(user_id, policy_id);
8 |
9 | CREATE INDEX idx_grouppermission_group ON grouppermission(group_id);
10 | CREATE INDEX idx_grouppermission_policy ON grouppermission(policy_id);
11 | CREATE INDEX idx_grouppermission_both ON grouppermission(group_id, policy_id);
12 |
13 | CREATE INDEX idx_token_owner ON token(owner);
14 | CREATE INDEX idx_tokenscope ON tokenscope(token_id, policy_id, access_level);
15 | CREATE INDEX idx_tokenscope_policy ON tokenscope(policy_id);
16 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_15__add_refresh_token_table.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE REFRESHTOKEN (
2 | id UUID PRIMARY KEY,
3 | user_id UUID UNIQUE NOT NULL,
4 | jti UUID UNIQUE NOT NULL,
5 | issuedate TIMESTAMP NOT NULL,
6 | expirydate TIMESTAMP NOT NULL,
7 | FOREIGN KEY (user_id) REFERENCES EGOUSER(id)
8 | );
9 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_16__add_primary_key_constraint_to_associations.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE USERGROUP ADD PRIMARY KEY (group_id,user_id);
2 | ALTER TABLE USERAPPLICATION ADD PRIMARY KEY (user_id, application_id);
3 | ALTER TABLE GROUPAPPLICATION ADD PRIMARY KEY (group_id, application_id);
4 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_17__add_application_permissions.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE APPLICATIONPERMISSION (
2 | id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
3 | policy_id UUID,
4 | application_id UUID,
5 | access_level ACLMASK NOT NULL,
6 | FOREIGN KEY (policy_id) REFERENCES POLICY(id),
7 | FOREIGN KEY (application_id) REFERENCES EGOAPPLICATION(id)
8 | );
9 |
10 | ALTER TABLE APPLICATIONPERMISSION RENAME CONSTRAINT APPLICATIONPERMISSION_POLICY_ID_FKEY TO APPLICATIONPERMISSION_POLICY_FKEY;
11 | ALTER TABLE APPLICATIONPERMISSION RENAME CONSTRAINT APPLICATIONPERMISSION_APPLICATION_ID_FKEY TO APPLICATIONPERMISSION_APPLICATION_FKEY;
12 |
13 | CREATE INDEX idx_applicationpermission_application ON APPLICATIONPERMISSION(application_id);
14 | CREATE INDEX idx_applicationpermission_policy ON APPLICATIONPERMISSION(policy_id);
15 | CREATE INDEX idx_applicationpermission_both ON APPLICATIONPERMISSION(application_id, policy_id);
16 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_18__ego_init.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE inittripwire (
2 | initialized INT PRIMARY KEY DEFAULT 0
3 | );
4 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_19__add_identity_provider_to_user.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE egouser ALTER COLUMN email DROP NOT NULL;
2 | ALTER TABLE egouser DROP CONSTRAINT egouser_email_key;
3 |
4 | ALTER TABLE egouser DROP COLUMN name;
5 |
6 | CREATE TYPE providerType AS ENUM('GOOGLE', 'FACEBOOK', 'LINKEDIN', 'GITHUB', 'ORCID');
7 | ALTER TABLE egouser ADD COLUMN providertype providerType;
8 | ALTER TABLE egouser ALTER COLUMN providertype SET DEFAULT '${default-provider}';
9 | -- default values are not added to existing rows, need to explicitly update where providertype is NULL
10 | UPDATE egouser SET providertype = DEFAULT WHERE providertype IS NULL;
11 | -- then set not null constraint
12 | ALTER TABLE egouser ALTER COLUMN providertype SET NOT NULL;
13 |
14 | ALTER TABLE egouser ADD COLUMN providersubjectid VARCHAR(255);
15 | UPDATE egouser SET providersubjectid = email WHERE providersubjectid IS NULL;
16 | ALTER TABLE egouser ALTER COLUMN providersubjectid SET NOT NULL;
17 |
18 | ALTER TABLE egouser ADD UNIQUE(providertype, providersubjectid);
19 |
20 | -- create tripwire table for verifying configured default provider
21 | CREATE TABLE defaultprovidertripwire (
22 | id providerType PRIMARY KEY
23 | );
24 |
25 | INSERT INTO defaultprovidertripwire (id) VALUES ('${default-provider}');
26 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_20__keycloak_provider_type.sql:
--------------------------------------------------------------------------------
1 | ALTER TYPE providerType ADD VALUE 'KEYCLOAK';
2 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_21__add_application_error_redirect.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE egoapplication ADD COLUMN errorredirecturi text;
2 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_2__acl_expansion.sql:
--------------------------------------------------------------------------------
1 | CREATE TYPE ACLMASK AS ENUM ('READ', 'WRITE', 'DENY');
2 |
3 | CREATE TABLE ACLENTITY (
4 | id UUID PRIMARY KEY,
5 | owner UUID,
6 | name varchar(255) UNIQUE NOT NULL,
7 | FOREIGN KEY (owner) REFERENCES EGOGROUP(id)
8 | );
9 |
10 |
11 | CREATE TABLE ACLUSERPERMISSION (
12 | id UUID PRIMARY KEY,
13 | entity UUID,
14 | sid UUID,
15 | mask ACLMASK NOT NULL,
16 | FOREIGN KEY (entity) REFERENCES ACLENTITY(id),
17 | FOREIGN KEY (sid) REFERENCES EGOUSER(id)
18 | );
19 |
20 |
21 | CREATE TABLE ACLGROUPPERMISSION (
22 | id UUID PRIMARY KEY,
23 | entity UUID,
24 | sid UUID,
25 | mask ACLMASK NOT NULL,
26 | FOREIGN KEY (entity) REFERENCES ACLENTITY(id),
27 | FOREIGN KEY (sid) REFERENCES EGOGROUP(id)
28 | );
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_4__score_integration.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE TOKEN(
2 | id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
3 | token VARCHAR(2048) NOT NULL,
4 | owner UUID NOT NULL REFERENCES EGOUSER(ID),
5 | issuedate TIMESTAMP DEFAULT NOW(),
6 | isrevoked BOOLEAN DEFAULT FALSE
7 | );
8 |
9 | CREATE TABLE TOKENSCOPE (
10 | token_id UUID NOT NULL REFERENCES TOKEN(ID),
11 | policy_id UUID NOT NULL REFERENCES ACLENTITY(ID),
12 | access_level ACLMASK NOT NULL
13 | );
14 |
15 | CREATE TABLE TOKENAPPLICATION (
16 | tokenid UUID NOT NULL REFERENCES TOKEN(ID),
17 | appid UUID NOT NULL REFERENCES EGOAPPLICATION(ID)
18 | );
19 |
20 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_6__add_not_null_constraint.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE EGOAPPLICATION ALTER COLUMN name SET NOT NULL;
2 | ALTER TABLE EGOAPPLICATION ALTER COLUMN clientid SET NOT NULL;
3 | ALTER TABLE EGOAPPLICATION ALTER COLUMN clientsecret SET NOT NULL;
4 | ALTER TABLE EGOAPPLICATION ALTER COLUMN status SET NOT NULL;
5 |
6 | ALTER TABLE EGOGROUP ALTER COLUMN name SET NOT NULL;
7 | ALTER TABLE EGOGROUP ALTER COLUMN status SET NOT NULL;
8 |
9 | ALTER TABLE EGOUSER ALTER COLUMN name SET NOT NULL;
10 | ALTER TABLE EGOUSER ALTER COLUMN email SET NOT NULL;
11 | ALTER TABLE EGOUSER ALTER COLUMN role SET NOT NULL;
12 | ALTER TABLE EGOUSER ALTER COLUMN createdat SET NOT NULL;
13 | -- ALTER TABLE EGOUSER ALTER COLUMN lastlogin SET NOT NULL;
14 | ALTER TABLE EGOUSER ALTER COLUMN status SET NOT NULL;
15 | -- ALTER TABLE EGOUSER ALTER COLUMN preferredlanguage SET NOT NULL;
16 |
17 | ALTER TABLE GROUPAPPLICATION ALTER COLUMN group_id SET NOT NULL;
18 | ALTER TABLE GROUPAPPLICATION ALTER COLUMN application_id SET NOT NULL;
19 |
20 | ALTER TABLE TOKEN ALTER COLUMN issuedate SET NOT NULL;
21 | ALTER TABLE TOKEN ALTER COLUMN isrevoked SET NOT NULL;
22 |
23 | ALTER TABLE USERAPPLICATION ALTER COLUMN application_id SET NOT NULL;
24 |
25 | ALTER TABLE USERGROUP ALTER COLUMN group_id SET NOT NULL;
26 |
27 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_7__token_modification.sql:
--------------------------------------------------------------------------------
1 | ALTER TABLE token RENAME COLUMN token TO name;
2 | ALTER TABLE token ADD CONSTRAINT token_name_key UNIQUE (name);
3 | ALTER TABLE token ADD description VARCHAR(255);
4 |
--------------------------------------------------------------------------------
/src/main/resources/flyway/sql/V1_8__application_types.sql:
--------------------------------------------------------------------------------
1 | CREATE TYPE APPLICATIONTYPE AS ENUM('CLIENT','ADMIN');
2 | ALTER TABLE EGOUSER RENAME COLUMN role to usertype;
3 | ALTER TABLE EGOAPPLICATION add column applicationtype APPLICATIONTYPE not null DEFAULT 'CLIENT';
4 |
--------------------------------------------------------------------------------
/src/main/resources/schemas/00-psql-drop-tables.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE IF EXISTS EGOAPPLICATION CASCADE;
2 | DROP TABLE IF EXISTS EGOUSER CASCADE;
3 | DROP TABLE IF EXISTS EGOGROUP CASCADE;
4 | DROP TABLE IF EXISTS GROUPAPPLICATION CASCADE;
5 | DROP TABLE IF EXISTS USERGROUP CASCADE;
6 | DROP TABLE IF EXISTS USERAPPLICATION CASCADE;
7 | DROP TABLE IF EXISTS ACLENTITY CASCADE;
8 | DROP TABLE IF EXISTS ACLUSERPERMISSION CASCADE;
9 | DROP TABLE IF EXISTS ACLGROUPPERMISSION CASCADE;
10 | DROP TYPE IF EXISTS ACLMASK CASCADE;
--------------------------------------------------------------------------------
/src/main/resources/scripts/env_template.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ### =================================================== ###
4 | # Reference file for server environment variables #
5 | ### =================================================== ###
6 |
7 | # === Install Path
8 | export EGO_INSTALL_PATH=
9 | export EGO_KEYSTORE_PATH=
10 |
11 | # === DB Config
12 | export EGO_DB=
13 | export EGO_DB_HOST=
14 | export EGO_DB_PORT=
15 |
16 | # Leave DB_USER AND DB_PASS empty if using VAULT
17 | export EGO_DB_USER=
18 | export EGO_DB_PASS=
19 |
20 | # === App Server Config
21 | export EGO_ACTIVE_PROFILES="default"
22 | export EGO_SERVER_PORT=8081
23 |
24 | # Leave IDs and Secrets empty if using VAULT
25 | export EGO_SERVER_GOOGLE_CLIENT_IDS=""
26 | export EGO_SERVER_FACEBOOK_APP_ID=""
27 | export EGO_SERVER_FACEBOOK_SECRET=""
28 |
29 | # === VAULT CONFIG
30 | # Leave all below empty if not using VAULT
31 | export VAULT_APPLICATION_NAME="development/oicr/ego"
32 | export EGO_VAULT_URI=
33 | export EGO_VAULT_SCHEME=
34 | export EGO_VAULT_HOST=
35 | export EGO_VAULT_PORT=
36 | #leave IAM Role blank if using Token authentication
37 | export EGO_IAM_ROLE=
38 | #leave Token blank if using IAM Role
39 | export VAULT_TOKEN=
40 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/jwt/export-pub-key.sh:
--------------------------------------------------------------------------------
1 | keytool -list -rfc --keystore $1 | openssl x509 -inform pem -pubkey
2 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/jwt/gen-key-pair.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # generate pubkey and private keys
4 | openssl genrsa -out private_key.pem 2048
5 | openssl rsa -in private_key.pem -pubout -out public_key.pem
6 | openssl pkcs8 -topk8 -in private_key.pem -inform pem -out private_key_pkcs8.pem -outform pem -nocrypt
7 | awk '{ printf "%s", $0 }' public_key.pem | awk '{ gsub("-----BEGIN PUBLIC KEY-----","",$0); print $0 }' | awk '{ gsub("-----END PUBLIC KEY-----","",$0); print $0 }' > public_key_text.pem
8 | awk '{ printf "%s", $0 }' private_key_pkcs8.pem | awk '{ gsub("-----BEGIN PRIVATE KEY-----","",$0); print $0 }' | awk '{ gsub("-----END PRIVATE KEY-----","",$0); print $0 }' > private_key_text.pem
9 |
10 | # cleanup
11 | rm private_key.pem private_key_pkcs8.pem public_key.pem
12 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/jwt/gen-keystore.sh:
--------------------------------------------------------------------------------
1 | keytool -genkeypair -alias $1 -keyalg RSA -keypass $2 -keystore ego-jwt.jks -storepass $3
2 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/start-server-iam.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # === Add IAM profile
4 | export EGO_IAM_PROFILE=$EGO_ACTIVE_PROFILES,app,db,iam
5 |
6 | # === Start Server
7 | $EGO_INSTALL_PATH/install/bin/ego start \
8 | wrapper.app.parameter.4=--spring.profiles.active=$EGO_IAM_PROFILE \
9 | wrapper.app.parameter.5=--token.key-store=$EGO_KEYSTORE_PATH \
10 | set.SPRING_DATASOURCE_URL=jdbc:postgresql://$EGO_DB_HOST:$EGO_DB_PORT/$EGO_DB \
11 | set.SERVER_PORT=$EGO_SERVER_PORT \
12 | set.SPRING_APPLICATION_NAME=$VAULT_APPLICATION_NAME \
13 | set.SPRING_CLOUD_VAULT_URI=$EGO_VAULT_URI \
14 | set.SPRING_CLOUD_VAULT_SCHEME=$EGO_VAULT_SCHEME \
15 | set.SPRING_CLOUD_VAULT_HOST=$EGO_VAULT_HOST \
16 | set.SPRING_CLOUD_VAULT_PORT=$EGO_VAULT_PORT \
17 | set.SPRING_CLOUD_VAULT_AWS-IAM_ROLE=$EGO_IAM_ROLE
18 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/start-server-token.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # === Add token profile
3 | export EGO_TOKEN_PROFILE=$EGO_ACTIVE_PROFILES,app,db,token
4 |
5 | # === Start Server
6 | $EGO_INSTALL_PATH/install/bin/ego start \
7 | wrapper.app.parameter.4=--spring.profiles.active=EGO_TOKEN_PROFILE \
8 | wrapper.app.parameter.5=--token.key-store=$EGO_KEYSTORE_PATH \
9 | set.SPRING_DATASOURCE_URL=jdbc:postgresql://$EGO_DB_HOST:$EGO_DB_PORT/$EGO_DB \
10 | set.SERVER_PORT=$EGO_SERVER_PORT \
11 | set.SPRING_APPLICATION_NAME=$VAULT_APPLICATION_NAME \
12 | set.SPRING_CLOUD_VAULT_URI=$EGO_VAULT_URI \
13 | set.SPRING_CLOUD_VAULT_SCHEME=$EGO_VAULT_SCHEME \
14 | set.SPRING_CLOUD_VAULT_HOST=$EGO_VAULT_HOST \
15 | set.SPRING_CLOUD_VAULT_PORT=$EGO_VAULT_PORT \
16 | set.SPRING_CLOUD_VAULT_TOKEN=$VAULT_TOKEN
17 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/start-server.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | $EGO_INSTALL_PATH/install/bin/ego start \
3 | wrapper.app.parameter.4=--spring.profiles.active=$EGO_ACTIVE_PROFILES,jks \
4 | wrapper.app.parameter.5=--token.key-store=$EGO_KEYSTORE_PATH \
5 | set.SPRING_DATASOURCE_URL=jdbc:postgresql://$EGO_DB_HOST:$EGO_DB_PORT/$EGO_DB \
6 | set.SPRING_DATASOURCE_USERNAME=$EGO_DB_USER \
7 | set.SPRING_DATASOURCE_PASSWORD=$EGO_DB_PASS \
8 | set.SERVER_PORT=$EGO_SERVER_PORT \
9 | set.GOOGLE_CLIENT_IDS=$EGO_SERVER_GOOGLE_CLIENT_IDS \
10 | set.FACEBOOK_CLIENT_ID=$EGO_SERVER_FACEBOOK_APP_ID \
11 | set.FACEBOOK_CLIENT_SECRET=$EGO_SERVER_FACEBOOK_SECRET
12 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/stop-server.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | $EGO_INSTALL_PATH/install/bin/ego stop
3 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/vault/setup-local-vault.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo 'To test vault locally: download vault from: https://www.vaultproject.io/downloads.html and unzip in this folder'
4 | echo 'start vault server using : ./vault server -config ./vault.conf'
5 | echo 'Once server is running, execute this file again to setup required keys in vault'
6 |
7 | # Vault server address
8 | export VAULT_ADDR=http://localhost:8200
9 |
10 | # initialize vault
11 | export OUTPUT=$(./vault operator init)
12 |
13 | # set token
14 | export VAULT_TOKEN=$(echo $(echo $OUTPUT | awk -F'Token: ' '{print$2}' | awk -F' Vault' '{print $1}'))
15 |
16 | echo 'User this token in bootstrap-token.properties:' $VAULT_TOKEN
17 |
18 | # grab all unseal keys
19 | export VAULT_UNSEAL_KEY1=$(echo $(echo $OUTPUT | awk -F'Unseal Key 1:' '{print$2}' | awk -F' Unseal' '{print $1}'))
20 | export VAULT_UNSEAL_KEY2=$(echo $(echo $OUTPUT | awk -F'Unseal Key 2:' '{print$2}' | awk -F' Unseal' '{print $1}'))
21 | export VAULT_UNSEAL_KEY3=$(echo $(echo $OUTPUT | awk -F'Unseal Key 3:' '{print$2}' | awk -F' Unseal' '{print $1}'))
22 |
23 | # unseal vault
24 | ./vault operator unseal $VAULT_UNSEAL_KEY1
25 | ./vault operator unseal $VAULT_UNSEAL_KEY2
26 | ./vault operator unseal $VAULT_UNSEAL_KEY3
27 |
28 | ./vault write secret/development/oicr/ego/dev spring.datasource.username=postgres spring.datasource.password=postgres facebook.client.id=140524976574963 facebook.client.secret=2439abe7ae008bda7ab5cfdf706b4d66 google.client.Ids=808545688838-99s198l9lhl2hsvkpo5u91f3sflegemp.apps.googleusercontent.com,911372380614-7m296bg4eadc7m43e2mm6fs1a0ggkke1.apps.googleusercontent.com,814606937527-v7tr5dfqegjijicq3jeu5arv5tcl4ks0.apps.googleusercontent.com,814606937527-kk7ooglk6pj2tvpn7ldip6g3b74f8o72.apps.googleusercontent.com token.key-alias=ego-jwt token.keystore-password:=eG0tistic@lly
29 | ./vault read /secret/development/oicr/ego/dev
30 |
--------------------------------------------------------------------------------
/src/main/resources/scripts/vault/vault.conf:
--------------------------------------------------------------------------------
1 | backend "inmem" {
2 | }
3 |
4 | listener "tcp" {
5 | address = "0.0.0.0:8200"
6 | tls_disable = 1
7 | }
8 |
9 | disable_mlock = true
10 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/controller/AbstractNameableResolvablePermissionControllerTest.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.controller;
2 |
3 | import bio.overture.ego.model.entity.AbstractPermission;
4 | import bio.overture.ego.model.entity.NameableEntity;
5 | import java.util.UUID;
6 |
7 | public abstract class AbstractNameableResolvablePermissionControllerTest<
8 | O extends NameableEntity, P extends AbstractPermission>
9 | extends AbstractResolvablePermissionControllerTest {}
10 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/model/enums/AccessLevelTest.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.model.enums;
2 |
3 | import static bio.overture.ego.model.enums.AccessLevel.DENY;
4 | import static bio.overture.ego.model.enums.AccessLevel.READ;
5 | import static bio.overture.ego.model.enums.AccessLevel.WRITE;
6 | import static org.junit.Assert.assertEquals;
7 | import static org.junit.Assert.assertFalse;
8 | import static org.junit.Assert.assertTrue;
9 |
10 | import lombok.extern.slf4j.Slf4j;
11 | import org.junit.Test;
12 | import org.junit.runner.RunWith;
13 | import org.springframework.boot.test.context.SpringBootTest;
14 | import org.springframework.test.context.ActiveProfiles;
15 | import org.springframework.test.context.junit4.SpringRunner;
16 | import org.springframework.transaction.annotation.Transactional;
17 |
18 | @Slf4j
19 | @SpringBootTest
20 | @RunWith(SpringRunner.class)
21 | @ActiveProfiles("test")
22 | @Transactional
23 | public class AccessLevelTest {
24 | @Test
25 | public void testFromValue() {
26 | assertEquals(AccessLevel.fromValue("read"), AccessLevel.READ);
27 | assertEquals(AccessLevel.fromValue("write"), AccessLevel.WRITE);
28 | assertEquals(AccessLevel.fromValue("deny"), AccessLevel.DENY);
29 | }
30 |
31 | @Test
32 | public void testAllows() {
33 | allows(READ, READ);
34 | allows(WRITE, READ);
35 | denies(DENY, READ);
36 |
37 | denies(READ, WRITE);
38 | allows(WRITE, WRITE);
39 | denies(DENY, WRITE);
40 |
41 | denies(READ, DENY);
42 | denies(WRITE, DENY);
43 | denies(DENY, DENY);
44 | }
45 |
46 | public void allows(AccessLevel have, AccessLevel want) {
47 | assertTrue(AccessLevel.allows(have, want));
48 | }
49 |
50 | public void denies(AccessLevel have, AccessLevel want) {
51 | assertFalse(AccessLevel.allows(have, want));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/model/params/ScopeNameTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package bio.overture.ego.model.params;
19 |
20 | import static org.junit.Assert.assertEquals;
21 |
22 | import bio.overture.ego.model.enums.AccessLevel;
23 | import lombok.val;
24 | import org.junit.Test;
25 |
26 | public class ScopeNameTest {
27 | @Test
28 | public void testRead() {
29 | val s = new ScopeName("song.READ");
30 | assertEquals("song", s.getName());
31 | assertEquals(AccessLevel.READ, s.getAccessLevel());
32 | }
33 |
34 | @Test
35 | public void testNamedStudy() {
36 | val s = new ScopeName("song.ABC.WRITE");
37 | assertEquals("song.ABC", s.getName());
38 | assertEquals(AccessLevel.WRITE, s.getAccessLevel());
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/service/FirstUserAsAdminTest.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service;
2 |
3 | import bio.overture.ego.model.entity.User;
4 | import bio.overture.ego.model.enums.UserType;
5 | import bio.overture.ego.utils.EntityGenerator;
6 | import lombok.extern.slf4j.Slf4j;
7 | import lombok.val;
8 | import org.junit.Assert;
9 | import org.junit.Test;
10 | import org.junit.runner.RunWith;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.boot.test.context.SpringBootTest;
13 | import org.springframework.test.context.ActiveProfiles;
14 | import org.springframework.test.context.TestPropertySource;
15 | import org.springframework.test.context.junit4.SpringRunner;
16 | import org.springframework.transaction.annotation.Transactional;
17 |
18 | @Slf4j
19 | @SpringBootTest
20 | @RunWith(SpringRunner.class)
21 | @ActiveProfiles("test")
22 | @TestPropertySource(properties = "default.user.firstUserAsAdmin=true")
23 | @Transactional
24 | public class FirstUserAsAdminTest {
25 |
26 | @Autowired private UserService userService;
27 | @Autowired private EntityGenerator entityGenerator;
28 |
29 | @Test
30 | public void testOnlyFirstUserShouldBeAdminByDefault() {
31 | userService.getRepository().deleteAll();
32 | val usersCount = userService.countAll();
33 | Assert.assertEquals(0, usersCount);
34 | User u = entityGenerator.setupUser("First User", UserType.USER);
35 | val user = userService.findById(u.getId()).get();
36 | Assert.assertEquals(user.getType(), UserType.ADMIN);
37 |
38 | // add another user make sure they don't get ADMIN type
39 | User u2 = entityGenerator.setupUser("Second User", UserType.USER);
40 | val user2 = userService.findById(u2.getId()).get();
41 | Assert.assertEquals(user2.getType(), UserType.USER);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/service/initialization/InitializationEventTest.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.service.initialization;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import bio.overture.ego.repository.InitTripWireRepository;
6 | import bio.overture.ego.service.InitializationService;
7 | import lombok.extern.slf4j.Slf4j;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.context.ActiveProfiles;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | @Slf4j
16 | @ActiveProfiles("test")
17 | @RunWith(SpringRunner.class)
18 | @SpringBootTest(properties = "initialization.enabled=true")
19 | public class InitializationEventTest {
20 |
21 | @Autowired private InitializationService service;
22 | @Autowired private InitTripWireRepository repository;
23 |
24 | @Test
25 | public void testInitializationUsingSpringEvents() {
26 | assertTrue(service.isInitialized());
27 | // Note: this is necessary since this will persist the initialization flag for other tests.
28 | // This is out of context of a test transaction because the initialization happens at when
29 | // spring boots,
30 | // which is before the execution of this test.
31 | // Because of this, we need to delete the initialization value from the database for other
32 | // tests.
33 | repository.deleteAll();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/EntityTools.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import bio.overture.ego.model.entity.Application;
4 | import bio.overture.ego.model.entity.Group;
5 | import bio.overture.ego.model.entity.Identifiable;
6 | import bio.overture.ego.model.entity.User;
7 | import java.util.Collection;
8 | import java.util.List;
9 | import java.util.Set;
10 | import java.util.UUID;
11 | import java.util.stream.Collectors;
12 |
13 | public class EntityTools {
14 | public static List extractGroupIds(Set entities) {
15 | return entities.stream().map(Group::getId).collect(java.util.stream.Collectors.toList());
16 | }
17 |
18 | public static List extractGroupNames(List entities) {
19 | return entities.stream().map(Group::getName).collect(java.util.stream.Collectors.toList());
20 | }
21 |
22 | public static List extractUserIds(Set entities) {
23 | return entities.stream().map(User::getId).collect(java.util.stream.Collectors.toList());
24 | }
25 |
26 | public static List extractAppIds(Set entities) {
27 | return entities.stream().map(Application::getId).collect(Collectors.toList());
28 | }
29 |
30 | public static > List extractIDs(Collection entities) {
31 | return entities.stream().map(Identifiable::getId).collect(Collectors.toList());
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/WithMockCustomApplication.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static bio.overture.ego.model.enums.ApplicationType.ADMIN;
4 |
5 | import bio.overture.ego.model.enums.ApplicationType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 | import org.springframework.security.test.context.support.WithSecurityContext;
9 |
10 | @Retention(RetentionPolicy.RUNTIME)
11 | @WithSecurityContext(factory = WithMockCustomApplicationSecurityContextFactory.class)
12 | public @interface WithMockCustomApplication {
13 |
14 | String name() default "Admin Security App";
15 |
16 | String clientId() default "Admin-Security-APP-ID";
17 |
18 | String clientSecret() default "Admin-Security-APP-Secret";
19 |
20 | String redirectUri() default "mock.com";
21 |
22 | String description() default "Mock Application";
23 |
24 | String errorRedirectUri() default "mock.com/error";
25 |
26 | ApplicationType type() default ADMIN;
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/WithMockCustomUser.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils;
2 |
3 | import static bio.overture.ego.model.enums.ProviderType.GOOGLE;
4 | import static bio.overture.ego.model.enums.UserType.ADMIN;
5 |
6 | import bio.overture.ego.model.enums.ProviderType;
7 | import bio.overture.ego.model.enums.UserType;
8 | import java.lang.annotation.Retention;
9 | import java.lang.annotation.RetentionPolicy;
10 | import org.springframework.security.test.context.support.WithSecurityContext;
11 |
12 | @Retention(RetentionPolicy.RUNTIME)
13 | @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
14 | public @interface WithMockCustomUser {
15 |
16 | String firstName() default "Admin";
17 |
18 | String lastName() default "User";
19 |
20 | UserType type() default ADMIN;
21 |
22 | ProviderType providerType() default GOOGLE;
23 |
24 | String providerSubjectId() default "0123";
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/web/BasicWebResource.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils.web;
2 |
3 | import org.springframework.boot.test.web.client.TestRestTemplate;
4 | import org.springframework.http.ResponseEntity;
5 |
6 | public class BasicWebResource>
7 | extends AbstractWebResource> {
8 |
9 | public BasicWebResource(TestRestTemplate restTemplate, String serverUrl, Class responseType) {
10 | super(restTemplate, serverUrl, responseType);
11 | }
12 |
13 | @Override
14 | protected O createResponseOption(ResponseEntity responseEntity) {
15 | return (O) new ResponseOption(responseEntity);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/web/CleanResponse.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils.web;
2 |
3 | import lombok.Builder;
4 | import lombok.NonNull;
5 | import lombok.Value;
6 |
7 | @Value
8 | @Builder
9 | public class CleanResponse {
10 | @NonNull private final String statusCodeName;
11 | private final int statusCodeValue;
12 | private final Object body;
13 | }
14 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/web/QueryParam.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils.web;
2 |
3 | import static bio.overture.ego.utils.Joiners.COMMA;
4 | import static java.lang.String.format;
5 |
6 | import lombok.Builder;
7 | import lombok.NonNull;
8 | import lombok.Value;
9 |
10 | @Value
11 | @Builder
12 | public class QueryParam {
13 | @NonNull private final String key;
14 | @NonNull private final Object value;
15 |
16 | public static QueryParam createQueryParam(String key, Object... values) {
17 | return new QueryParam(key, COMMA.join(values));
18 | }
19 |
20 | @Override
21 | public String toString() {
22 | return format("%s=%s", key, value);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/web/ResponseOption.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils.web;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.springframework.http.HttpStatus.BAD_REQUEST;
5 | import static org.springframework.http.HttpStatus.CONFLICT;
6 | import static org.springframework.http.HttpStatus.NOT_FOUND;
7 | import static org.springframework.http.HttpStatus.OK;
8 |
9 | import java.util.function.Function;
10 | import lombok.Getter;
11 | import lombok.NonNull;
12 | import lombok.RequiredArgsConstructor;
13 | import org.junit.Assert;
14 | import org.springframework.http.HttpStatus;
15 | import org.springframework.http.ResponseEntity;
16 |
17 | @RequiredArgsConstructor
18 | public class ResponseOption> {
19 |
20 | @Getter @NonNull private final ResponseEntity response;
21 |
22 | public O assertStatusCode(HttpStatus code) {
23 |
24 | assertEquals(code, response.getStatusCode());
25 | return thisInstance();
26 | }
27 |
28 | public O assertOk() {
29 | return assertStatusCode(OK);
30 | }
31 |
32 | public O assertNotFound() {
33 | return assertStatusCode(NOT_FOUND);
34 | }
35 |
36 | public O assertConflict() {
37 | return assertStatusCode(CONFLICT);
38 | }
39 |
40 | public O assertBadRequest() {
41 | return assertStatusCode(BAD_REQUEST);
42 | }
43 |
44 | public O assertHasBody() {
45 | Assert.assertTrue(response.hasBody());
46 | Assert.assertNotNull(response.getBody());
47 | return thisInstance();
48 | }
49 |
50 | public R map(Function, R> transformingFunction) {
51 | return transformingFunction.apply(getResponse());
52 | }
53 |
54 | private O thisInstance() {
55 | return (O) this;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/bio/overture/ego/utils/web/StringWebResource.java:
--------------------------------------------------------------------------------
1 | package bio.overture.ego.utils.web;
2 |
3 | import org.springframework.boot.test.web.client.TestRestTemplate;
4 | import org.springframework.http.ResponseEntity;
5 |
6 | public class StringWebResource
7 | extends AbstractWebResource {
8 |
9 | public StringWebResource(TestRestTemplate restTemplate, String serverUrl) {
10 | super(restTemplate, serverUrl, String.class);
11 | }
12 |
13 | @Override
14 | protected StringResponseOption createResponseOption(ResponseEntity responseEntity) {
15 | return new StringResponseOption(responseEntity);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/selenium/driver/BrowserStackDriverProxy.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2019. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package selenium.driver;
19 |
20 | import com.browserstack.local.Local;
21 | import java.net.URL;
22 | import lombok.SneakyThrows;
23 | import org.openqa.selenium.remote.DesiredCapabilities;
24 | import org.openqa.selenium.remote.RemoteWebDriver;
25 |
26 | public class BrowserStackDriverProxy extends RemoteWebDriver {
27 |
28 | /** State */
29 | private final Local local;
30 |
31 | @SneakyThrows
32 | public BrowserStackDriverProxy(URL url, DesiredCapabilities capabilities, Local local) {
33 | super(url, capabilities);
34 | this.local = local;
35 | }
36 |
37 | @Override
38 | @SneakyThrows
39 | public void quit() {
40 | if (local != null) local.stop();
41 | super.quit();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/selenium/rule/AssumingSeleniumEnvironment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2019. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package selenium.rule;
19 |
20 | import org.junit.AssumptionViolatedException;
21 | import org.junit.rules.TestRule;
22 | import org.junit.runner.Description;
23 | import org.junit.runners.model.Statement;
24 | import selenium.driver.WebDriverFactory.DriverType;
25 |
26 | public class AssumingSeleniumEnvironment implements TestRule {
27 |
28 | private SeleniumEnvironmentChecker checker;
29 |
30 | public AssumingSeleniumEnvironment(SeleniumEnvironmentChecker checker) {
31 | this.checker = checker;
32 | }
33 |
34 | public DriverType getDriverType() {
35 | return checker.getType();
36 | }
37 |
38 | @Override
39 | public Statement apply(Statement base, Description description) {
40 | return new Statement() {
41 | @Override
42 | public void evaluate() throws Throwable {
43 | if (!checker.shouldRunTest()) {
44 | throw new AssumptionViolatedException("Could not connect. Skipping test!");
45 | } else {
46 | base.evaluate();
47 | }
48 | }
49 | };
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/test/java/selenium/rule/SeleniumEnvironmentChecker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2019. The Ontario Institute for Cancer Research. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package selenium.rule;
19 |
20 | import lombok.Getter;
21 | import selenium.driver.WebDriverFactory.DriverType;
22 |
23 | public class SeleniumEnvironmentChecker {
24 |
25 | @Getter private DriverType type;
26 |
27 | public SeleniumEnvironmentChecker() {
28 | String envVar = System.getenv("SELENIUM_TEST_TYPE");
29 | if (envVar != null) {
30 | type = DriverType.valueOf(envVar);
31 | }
32 | }
33 |
34 | public boolean shouldRunTest() {
35 | if (type == DriverType.BROWSERSTACK || type == DriverType.LOCAL) {
36 | return true;
37 | } else {
38 | return false;
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/resources/conf/bs.conf.json:
--------------------------------------------------------------------------------
1 | {
2 | "server": "hub-cloud.browserstack.com",
3 | "user": "*",
4 | "key": "*",
5 |
6 | "capabilities": {
7 | "os": "Windows",
8 | "os_version": "10",
9 | "browser": "Chrome",
10 | "browser_version": "62.0",
11 | "browserstack.debug": true,
12 | "browserstack.local": true,
13 | "project": "ego"
14 | },
15 |
16 | "environments": [{
17 | "browser": "chrome"
18 | }]
19 | }
--------------------------------------------------------------------------------