target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgSingleContextRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, entity, SecurityUtil.UserContext.TEACHER_CONTEXT, false); Assert.assertEquals(4, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(TEACHER_CONTEXT)); Assert.assertFalse(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); Assert.assertFalse(grantedAuthorities.contains(STAFF_CONTEXT)); }
public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
@Test public void testFilterFields() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); EntityBody sb = new EntityBody(student.getBody()); entityRightsFilter.filterFields(sb, auths, "", EntityNames.STUDENT); Assert.assertEquals(1, sb.size()); Assert.assertEquals(STUDENT_UNIQUE_STATE_ID, sb.get(ParameterConstants.STUDENT_UNIQUE_STATE_ID)); }
@SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } }
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } }
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } }
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testComplexFilterReadGeneral() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(1, telepone.size()); Assert.assertEquals(1, emails.size()); Assert.assertEquals(WORK_PHONE, telepone.get(0).get(TELEPONE_VALUE)); Assert.assertEquals(WORK_EMAIL, emails.get(0).get(EMAIL_VALUE)); }
protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testComplexFilterReadRestrict() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_RESTRICTED); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(2, telepone.size()); Assert.assertEquals(2, emails.size()); }
protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testMakeEntityBody() { Treatment treatment1 = Mockito.mock(Treatment.class); Treatment treatment2 = Mockito.mock(Treatment.class); List<Treatment> treatments = new ArrayList<Treatment>(); treatments.add(treatment1); treatments.add(treatment2); Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); student.getEmbeddedData().put("studentSchoolAssociation", Arrays.asList(staff)); EntityBody sb = new EntityBody(student.getBody()); EntityBody staffBody = new EntityBody(staff.getBody()); Mockito.when(treatment1.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); Mockito.when(treatment2.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); EntityDefinition definition = Mockito.mock(EntityDefinition.class); Mockito.when(definition.getType()).thenReturn("student"); EntityBody res = entityRightsFilter.makeEntityBody(student, treatments, definition, false, auths, SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertNotNull(res); List<EntityBody> ssa = (List<EntityBody>) res.get("studentSchoolAssociation"); Assert.assertNotNull(ssa); Assert.assertEquals(1, ssa.size()); Assert.assertEquals(STAFF_ID, ssa.get(0).get(ParameterConstants.STAFF_UNIQUE_STATE_ID)); }
public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); }
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } }
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } }
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testBuildEdOrgContextualRoles () { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); Set<Role> edOrg1RolesSet = new HashSet<Role>(); edOrg1RolesSet.add(createRole("Educator")); edOrg1RolesSet.add(createRole("IT Admin")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator", "IT Admin"), false)).thenReturn(edOrg1RolesSet); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("IT Admin", "Educator"), false)).thenReturn(edOrg1RolesSet); Set<Role> edOrg2RolesSet = new HashSet<Role>(); edOrg2RolesSet.add(createRole("Educator")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator"), false)).thenReturn(edOrg2RolesSet); Mockito.when(edorgHelper.locateNonExpiredSEOAs(staffId)).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId,tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(2,edOrgRoles.size()); List<String> edOrg1Roles = edOrgRoles.get("LEA1"); Assert.assertNotNull(edOrg1Roles); Assert.assertEquals(2, edOrg1Roles.size()); Assert.assertTrue(edOrg1Roles.contains("IT Admin")); Assert.assertTrue(edOrg1Roles.contains("Educator")); List<String> edOrg2Roles = edOrgRoles.get("LEA2"); Assert.assertNotNull(edOrg2Roles); Assert.assertEquals(1, edOrg2Roles.size()); Assert.assertTrue(edOrg2Roles.contains("Educator")); }
private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; }
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } }
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } }
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test (expected = AccessDeniedException.class) public void testNoCustomRoleMatch () { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); Set<Role> edOrg1RolesSet = new HashSet<Role>(); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator", "IT Admin"), false)).thenReturn(edOrg1RolesSet); Mockito.when(edorgHelper.locateNonExpiredSEOAs(staffId)).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId,tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(0,edOrgRoles.size()); }
public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test (expected = AccessDeniedException.class) public void testInvalidEdOrgRoles() { Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(new HashSet<Entity>()); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(0,edOrgRoles.size()); }
public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test public void testComposeResponse() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, TransformerException, MarshalException, XMLSignatureException, SAXException, IOException, ParserConfigurationException { Mockito.when(sigHelper.signSamlAssertion(Mockito.any(Document.class))).thenAnswer(new Answer<Document>() { @Override public Document answer(InvocationOnMock invocation) throws Throwable { return (Document) invocation.getArguments()[0]; } }); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("userName", "User Name"); attributes.put("tenant", "tenantId"); attributes.put("edorg", "NC-edorg"); attributes.put("adminRealm", "myrealm"); attributes.put("userType", "staff"); String encodedXml = composer.componseResponse("dest", "issuer", "requestId", "userId", attributes, Arrays.asList("role1", "role2")); String xml = new String(Base64.decodeBase64(encodedXml), "UTF8"); Mockito.verify(sigHelper).signSamlAssertion(Mockito.any(Document.class)); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); Document doc = fact.newDocumentBuilder().parse(new InputSource(new StringReader(xml))); assertEquals("dest", doc.getDocumentElement().getAttribute("Destination")); assertEquals("requestId", doc.getDocumentElement().getAttribute("InResponseTo")); assertTrue(hasAttributeValue(doc, "userName", "User Name")); assertTrue(hasAttributeValue(doc, "userId", "userId")); assertTrue(hasAttributeValue(doc, "userType", "staff")); assertTrue(hasAttributeValue(doc, "roles", "role1")); assertTrue(hasAttributeValue(doc, "roles", "role2")); assertTrue(hasAttributeValue(doc, "tenant", "tenantId")); assertTrue(hasAttributeValue(doc, "edorg", "NC-edorg")); assertTrue(hasAttributeValue(doc, "adminRealm", "myrealm")); assertEquals("issuer", xpathOne(doc, "/samlp:Response/saml:Issuer").getTextContent()); assertTrue(xpathOne(doc, "/samlp:Response/@IssueInstant").getTextContent().matches( "\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ")); assertTrue(xpathOne(doc, "/samlp:Response/saml:Assertion/@IssueInstant").getTextContent().matches( "\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ")); assertTrue(!xpathOne(doc, "/samlp:Response/@ID").getTextContent().equals("__RESPONSE_ID__")); assertTrue(!xpathOne(doc, "/samlp:Response/saml:Assertion/@ID").getTextContent().equals("__ASSERTION_ID__")); assertTrue(!xpathOne(doc, "/samlp:Response/@Destination").getTextContent().equals("__DESTINATION__")); assertEquals("requestId", xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@InResponseTo").getTextContent()); assertEquals("dest", xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@Recipient").getTextContent()); String expDate = xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@NotOnOrAfter").getTextContent(); DateTime dt = DateTime.parse(expDate); assertTrue(dt.minusMinutes(9).isAfterNow()); assertTrue(dt.minusMinutes(11).isBeforeNow()); }
public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); }
SamlResponseComposer { public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); } }
SamlResponseComposer { public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); } }
SamlResponseComposer { public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); } String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles); }
SamlResponseComposer { public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); } String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles); }
@Test (expected = AccessDeniedException.class) public void noMatchingRoles() { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "Random Role1")); seoas.add(createSEOA("LEA1", "Random Role2")); seoas.add(createSEOA("LEA2", "Random Role2")); Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, samlRoles); Assert.assertTrue(edOrgRoles.isEmpty()); }
public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test (expected = AccessDeniedException.class) public void testNoSamlRoles() { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, new ArrayList<String>()); Assert.assertTrue(edOrgRoles.isEmpty()); }
public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test public void testEquals() { MutatedContainer m1 = new MutatedContainer(); setParams(m1, "a", "b", null); MutatedContainer m2 = new MutatedContainer(); setParams(m2, "a", "b", null); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "c", "b", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "a", "c", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", new HashMap<String, String>()); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", null); Assert.assertFalse(m1.equals(m2)); HashMap<String, String> h1 = new HashMap<String, String>(); h1.put("1", "1"); HashMap<String, String> h2 = new HashMap<String, String>(); h2.put("1", "2"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertFalse(m1.equals(m2)); h1 = new HashMap<String, String>(); h1.put("1", "1"); h2 = new HashMap<String, String>(); h2.put("1", "1"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertTrue(m1.equals(m2)); }
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); }
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } }
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } }
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } static MutatedContainer generate(String queryParameters, String pathFormat, String... pathArgs); String getPath(); void setPath(String path); String getQueryParameters(); void setQueryParameters(String queryParameters); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); boolean isModified(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } static MutatedContainer generate(String queryParameters, String pathFormat, String... pathArgs); String getPath(); void setPath(String path); String getQueryParameters(); void setQueryParameters(String queryParameters); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); boolean isModified(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testMutatePath() throws Exception { String expectedPath; String resultPath; resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id&something=else"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "key1=val1&studentId=some_id&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.REPORT_CARDS, "schoolId=school_id&studentId=id1,id2,id3&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "id1,id2,id3" + "/" + ResourceNames.REPORT_CARDS; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.TEACHER_SECTION_ASSOCIATIONS, "schoolId=school_id"); expectedPath = null; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); }
public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; }
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } }
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } }
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } String mutatePath(String version, String resource, String queryParameters); }
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } String mutatePath(String version, String resource, String queryParameters); }
@Test public void testGetResourceVersionForSearch() { List<PathSegment> segments = getPathSegmentList("v1/search"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/search"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/search"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/search"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); }
protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
@Test public void testGetResourceVersion() { List<PathSegment> segments = getPathSegmentList("v1/students"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/studentSectionAssociations/1234/students"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/students"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/students"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); when(mutated.getPath()).thenReturn(null); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); }
protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
@Test public void testGetResourceVersionForPublicResources() { List<PathSegment> segments = getPathSegmentList("v1/assessments"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search/assessments"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/assessments"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); }
protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
@Test(expected = NotFoundException.class) public void testNoPathSegments() throws URISyntaxException { SLIPrincipal principle = mock(SLIPrincipal.class); ClientToken clientToken = mock(ClientToken.class); when(clientToken.getClientId()).thenReturn("theAppId"); OAuth2Authentication auth = mock(OAuth2Authentication.class); when(auth.getPrincipal()).thenReturn(principle); when(auth.getClientAuthentication()).thenReturn(clientToken); ContainerRequest request = mock(ContainerRequest.class); List<PathSegment> segments = Collections.emptyList(); when(request.getPathSegments()).thenReturn(segments); when(request.getMethod()).thenReturn("GET"); when(request.getRequestUri()).thenReturn(new URI("http: endpointMutator.mutateURI(auth, request); }
public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } }
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } }
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } }
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } void mutateURI(Authentication auth, ContainerRequest request); }
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } void mutateURI(Authentication auth, ContainerRequest request); }
@Test public void testV1Mutate() { PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("v1"); when(principal.getEntity()).thenReturn(staff); Assert.assertEquals("Bad endpoint of /v1 is redirected to v1/home safely", createMutatedContainer("/home", "").toString(), mutator.mutate(Arrays.asList(v1), null, principal, "nonAdminAppId").toString()); when(principal.getEntity()).thenReturn(teacher); Assert.assertEquals("Bad endpoint of /v1 is redirected to v1/home safely", createMutatedContainer("/home", "").toString(), mutator.mutate(Arrays.asList(v1), null, principal, "nonAdminAppId").toString()); }
public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testDeterministicRewrite() { when(principal.getEntity()).thenReturn(null); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "teacher"); Entity teacher = repo.create("teacher", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /teachers/id", createMutatedContainer("/teachers/" + teacher.getEntityId(), "staffUniqueStateId=teacher"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=teacher", principal, null)); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /staff/id", createMutatedContainer("/staff/" + teacher.getEntityId(), "staffUniqueStateId=staff"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=staff", principal, null)); }
public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testIsPreviouslyIngested() { NeutralRecord originalRecord = createBaseNeutralRecord(); NeutralRecord recordClone = (NeutralRecord) originalRecord.clone(); TenantContext.setTenantId("tenantId"); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(null); Mockito.when(mockDIdStrategy.generateId(any(NaturalKeyDescriptor.class))).thenReturn(RECORD_DID); Mockito.when(mockDidResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(createNaturalKeyMap()); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(originalRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(originalRecord); List<Map<String, String>> fData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String fTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String fHash=fData.get(0).get("rhHash"); String fRhId=fData.get(0).get("rhId"); RecordHash hash = createRecordHash(fHash); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(hash); Assert.assertTrue(SliDeltaManager.isPreviouslyIngested(recordClone, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(recordClone); List<Map<String, String>> sData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String sTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String sHash=sData.get(0).get("rhHash"); String sRhId=sData.get(0).get("rhId"); Assert.assertEquals(fRhId, sRhId); Assert.assertEquals(fHash, sHash); Assert.assertEquals(fTenantId, sTenantId); }
public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats); }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats); static final String RECORDHASH_DATA; static final String RECORDHASH_HASH; static final String RECORDHASH_ID; static final String RECORDHASH_CURRENT; static final String NRKEYVALUEFIELDNAMES; static final String OPTIONALNRKEYVALUEFIELDNAMES; }
@Test(expected = MissingConfigException.class) public void missingServer() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); static final String KEY_USER; static final String KEY_PASSWORD; static final String KEY_SFTP_SERVER; static final String KEY_LOCAL_DIRECTORY; static final String KEY_PORT; final static Options OPTIONS; }
@Test public void testMutateSkipForAppAuthRightAdminApp() { SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/v1"); PathSegment edorgs = Mockito.mock(PathSegment.class); when(edorgs.getPath()).thenReturn("/educationOrganizations"); when(principal.getEntity()).thenReturn(staff); Map<String, Collection<GrantedAuthority>> edOrgRights = generateSimpleEdOrgRightsMap("theEdOrg", Right.APP_AUTHORIZE); when(principal.getEdOrgRights()).thenReturn(edOrgRights); MutatedContainer mutated = mutator.mutate(Arrays.asList(v1,edorgs), null, principal, ADMIN_APP_ID); System.out.println("The path is : " + mutated.getPath() + ", qparams : " + mutated.getQueryParameters()); Assert.assertEquals("Endpoint should NOT have been rewritten to " + mutated.getPath(), createMutatedContainer(null, ""), mutated); }
public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testGetInferredUrisForTeacherContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/sections/section123/studentSectionAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSectionAssociations/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.STUDENT_SECTION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/sections/section123/studentSectionAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SECTION_ASSOCIATIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/school123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHER_SECTION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSectionAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SECTION_ASSOCIATIONS, "", teacher)); }
public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testGetInferredUrisForStaffContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.COHORTS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations/cohorts", ""), mutator.mutateBaseUri(VERSION, ResourceNames.COHORTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.PROGRAMS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations/programs", ""), mutator.mutateBaseUri(VERSION, ResourceNames.PROGRAMS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF + " is incorrect.", createMutatedContainer("/educationOrganizations/edOrg123/staffEducationOrgAssignmentAssociations/staff", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_COHORT_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_COHORT_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffEducationOrgAssignmentAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_PROGRAM_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_PROGRAM_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENTS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", staff)); }
public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testGetInferredUrisForDualContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.COHORTS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations/cohorts", ""), mutator.mutateBaseUri(VERSION, ResourceNames.COHORTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.PROGRAMS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations/programs", ""), mutator.mutateBaseUri(VERSION, ResourceNames.PROGRAMS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF + " is incorrect.", createMutatedContainer("/educationOrganizations/edOrg123/staffEducationOrgAssignmentAssociations/staff", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_COHORT_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_COHORT_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffEducationOrgAssignmentAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_PROGRAM_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_PROGRAM_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENTS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", staff)); }
public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testStudentType() { SLIPrincipal principal = locator.locate(tenant, "testId", "student"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STUDENT)); }
@Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
@Test public void testStaffType() { Set<String> edorgs = new HashSet<String>(); edorgs.add("testEdorg"); Mockito.when(edorgHelper.locateDirectEdorgs((Entity)Matchers.any())).thenReturn(edorgs); SLIPrincipal principal = locator.locate(tenant, "testId", "staff"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); principal = locator.locate(tenant, "testId", ""); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); principal = locator.locate(tenant, "testId", null); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); }
@Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
@Test(expected = AccessDeniedException.class) public void testInvalidStaff() { Set<String> edorgs = new HashSet<String>(); Mockito.when(edorgHelper.locateDirectEdorgs((Entity)Matchers.any())).thenReturn(edorgs); SLIPrincipal principal = locator.locate(tenant, "testId", "staff"); }
@Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
@Test public void testInvalidType() { SLIPrincipal principal = locator.locate(tenant, "testId", "nobody"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals("user")); }
@Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
@Test public void sandboxAdminBecomeDeveloperInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, sandboxRole, false); assertTrue("sandbox admin is not mapped to developer in developer realm", roles.containsAll(defaultRoles.findAdminRoles(appAndProdLoginUser))); assertTrue("sandbox admin is not only mapped to developer in developer realm", defaultRoles.findAdminRoles(appAndProdLoginUser).containsAll(roles)); }
@Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
@Test public void sandboxAdminstaysSandboxAdminInAdminRealm() { Set<Role> roles = resolver.mapRoles(null, ADMIN_REALM_ID, sandboxRole, true); assertTrue("sandbox admin is changed in admin realm", roles.containsAll(defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)))); assertTrue("sandbox admin is only mapped to sandbox admin in admin realm", defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)).containsAll(roles)); }
@Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
@Test public void testIsPreviouslyIngestedModified() { NeutralRecord originalRecord = createBaseNeutralRecord(); NeutralRecord modifiedRecord = (NeutralRecord) originalRecord.clone(); modifiedRecord.getAttributes().put("commonAttrib1", "commonAttrib1_modified_value"); TenantContext.setTenantId("tenantId"); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(null); Mockito.when(mockDIdStrategy.generateId(any(NaturalKeyDescriptor.class))).thenReturn(RECORD_DID); Mockito.when(mockDidResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(createNaturalKeyMap()); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(originalRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(originalRecord); List<Map<String, String>> fData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String fTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String fHash=fData.get(0).get("rhHash"); String fRhId=fData.get(0).get("rhId"); RecordHash hash = createRecordHash(fHash); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(hash); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(modifiedRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(modifiedRecord); List<Map<String, String>> sData = (List<Map<String, String>>) modifiedRecord.getMetaData().get("rhData"); String sTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String sHash=sData.get(0).get("rhHash"); String sRhId=sData.get(0).get("rhId"); Assert.assertEquals(fRhId, sRhId); Assert.assertEquals(fTenantId, sTenantId); Assert.assertFalse(fHash.equals(sHash)); }
public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats); }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats); static final String RECORDHASH_DATA; static final String RECORDHASH_HASH; static final String RECORDHASH_ID; static final String RECORDHASH_CURRENT; static final String NRKEYVALUEFIELDNAMES; static final String OPTIONALNRKEYVALUEFIELDNAMES; }
@Test public void roleWithoutProdLoginIsChangedToEmptyGroupInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, otherRole, false); assertTrue("other admin is not mapped to developer in developer realm", roles.isEmpty()); }
@Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
@Test public void testMangleListQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(baseCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, baseCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); assertEquals(finalQuery.getOrQueries().get(0).getCriteria().get(0), baseCriteria); }
public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testMangleSpecificQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); assertEquals(finalQuery.getOrQueries().get(0).getCriteria().get(0), baseCriteria); }
public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testMangleSpecificFailedQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"4", "5"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertEquals(finalQuery.getOrQueries().size(), 0); }
public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testMangleListWithPaging() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); List<String> totalQuery = buildLargeQuery(100); query.setOffset(0); query.setLimit(50); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery.subList(0, 50)); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); NeutralCriteria finalCriteria = finalQuery.getOrQueries().get(0).getCriteria().get(0); assertEquals(((List) finalCriteria.getValue()).size(), 50); }
public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testMangleListWithPagingAndQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); List<String> totalQuery = buildLargeQuery(50); query.setOffset(0); query.setLimit(50); NeutralCriteria baseCriteria = new NeutralCriteria("body.something", NeutralCriteria.OPERATOR_EQUAL, "Waffletown"); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 1); assertTrue(finalQuery.getOrQueries().size() == 1); NeutralCriteria finalCriteria = finalQuery.getOrQueries().get(0).getCriteria().get(0); assertEquals(((List) finalCriteria.getValue()).size(), 50); }
public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testApplySecurityCriteria() { injector.setAccessAllAdminContext(); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setSecurityCriteria(new NeutralCriteria("key", "in", "value")); NeutralQuery query = new NeutralQuery(); query = securityCriteria.applySecurityCriteria(query); assertEquals("Should match", 1, query.getOrQueries().size()); }
public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; }
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } }
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } }
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } String getCollectionName(); void setCollectionName(String collectionName); NeutralCriteria getSecurityCriteria(); void setSecurityCriteria(NeutralCriteria securityCriteria); NeutralQuery applySecurityCriteria(NeutralQuery query); void setInClauseSize(Long size); }
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } String getCollectionName(); void setCollectionName(String collectionName); NeutralCriteria getSecurityCriteria(); void setSecurityCriteria(NeutralCriteria securityCriteria); NeutralQuery applySecurityCriteria(NeutralQuery query); void setInClauseSize(Long size); }
@Test public void testGetArtifactUrl() { setRealm(VALID_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test(expected = APIAccessDeniedException.class) public void testGetArtifactUrlIncorrectSourceId() { setRealm(INCORRECT_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test(expected = IllegalArgumentException.class) public void testGetArtifactUrlInvalidSourceIdFormat() { setRealm(NOT_HEX_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testEnsureIndexes() { String result = MongoCommander.ensureIndexes("mongoTestIndexes.txt", dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } }
public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }
@Test public void testInlineDecryption() { Resource inlineAssertionResource = new ClassPathResource("saml/inlineEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(inlineAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); }
protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testPeerDecryption() { Resource peerAssertionResource = new ClassPathResource("saml/peerEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(peerAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); }
protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testIsAssertionEncrypted() { Response samlResponse = Mockito.mock(Response.class); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(null); boolean result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertFalse(result); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(new ArrayList<EncryptedAssertion>()); result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertFalse(result); EncryptedAssertion encryptedAssertion = Mockito.mock(EncryptedAssertion.class); List<EncryptedAssertion> assertionList = new ArrayList<EncryptedAssertion>(); assertionList.add(encryptedAssertion); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(assertionList); result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertTrue(result); }
protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; }
SamlHelper { protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; } }
SamlHelper { protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; } }
SamlHelper { protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); }
SamlHelper { protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testValidateContextToEntities() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Entity student3 = createEntity("student", 3); Entity student5 = createEntity("student", 5); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1, student2, student3, student5)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student2))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student3))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student5))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student3, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student5, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(Arrays.asList("student1", "student2", "student3", "student5")); contextValidator.validateContextToEntities(def, ids, isTransitive); }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesOrphaned() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("createdBy", "staff1"); metaData.put("isOrphaned", "true"); Mockito.when(student1.getMetaData()).thenReturn(metaData); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("student1")); contextValidator.validateContextToEntities(def, ids, isTransitive); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesSelf() { EntityDefinition def = createEntityDef("staff"); Entity staff1 = createEntity("staff", 1); Mockito.when(repo.findAll(Mockito.matches("staff"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(staff1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(staff1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("staff1")); contextValidator.validateContextToEntities(def, ids, isTransitive); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesCannotAccess() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(false); Collection<String> ids = new HashSet<String>(Arrays.asList("student1")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("Access to " + student1.getEntityId() + " is not authorized", ex.getMessage()); } }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesNoEntitiesInDb() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(new ArrayList<Entity>()); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); String id = "student1"; Collection<String> ids = new HashSet<String>(Arrays.asList(id)); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (EntityNotFoundException ex) { Assert.assertEquals(id, ex.getId()); } }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesNotAllValidated() { EntityDefinition def = createEntityDef("student"); Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student0, student1, student2)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(Arrays.asList("student0", "student1", "student2")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("Cannot access entities", ex.getMessage()); } }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntitiesSelfNoValidators() { EntityDefinition def = createEntityDef("session"); Entity session1 = createEntity("session", 1); Mockito.when(repo.findAll(Mockito.matches("session"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(session1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(session1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("session1")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("No validator for " + def.getType() + ", transitive=" + isTransitive, ex.getMessage()); } }
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testEnsureSetIndexes() { String result = MongoCommander.ensureIndexes(indexes, dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } }
public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }
@Test public void testGetValidatedEntityContexts() { EntityDefinition def = createEntityDef("student"); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.any(Entity.class))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(Mockito.any(Entity.class), Mockito.anyBoolean())).thenReturn(true); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Entity student3 = createEntity("student", 3); Entity student4 = createEntity("student", 4); Entity student5 = createEntity("student", 5); List<Entity> students = Arrays.asList(student1, student2, student3, student4, student5); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(5, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student1")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student2")); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student3")); Assert.assertEquals(SecurityUtil.UserContext.TEACHER_CONTEXT, validatedEntityContexts.get("student4")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student5")); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testGetValidatedEntityContextsOrphaned() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("createdBy", "staff1"); metaData.put("isOrphaned", "true"); Mockito.when(student1.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(student1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(1, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student1")); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsSelf() { EntityDefinition def = createEntityDef("staff"); Entity staff1 = createEntity("staff", 1); List<Entity> staff = Arrays.asList(staff1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(staff1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, staff, isTransitive, true); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsCannotAccess() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); List<Entity> students = Arrays.asList(student1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(false); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(1, validatedEntityContexts.size()); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsNoEntitiesInList() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, new ArrayList<Entity>(), isTransitive, true); Assert.assertTrue(validatedEntityContexts.isEmpty()); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testGetValidatedEntityContextsNotAllValidated() { EntityDefinition def = createEntityDef("student"); Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); List<Entity> students = Arrays.asList(student0, student1, student2); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(2, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student1")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student2")); }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsNoValidators() { EntityDefinition def = createEntityDef("session"); Entity session1 = createEntity("session", 1); List<Entity> sessions = Arrays.asList(session1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(session1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; try { Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, sessions, isTransitive, true); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("No validator for " + def.getType() + ", transitive=" + isTransitive, ex.getMessage()); } }
public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testgetEntityIdsToValidateForgiving() { Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); List<Entity> students = Arrays.asList(student0, student1, student2); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenThrow(new AccessDeniedException("")); Set<String> ids = contextValidator.getEntityIdsToValidateForgiving(students, isTransitive); Assert.assertEquals(2, ids.size()); Assert.assertTrue(ids.contains(student0.getEntityId())); Assert.assertTrue(ids.contains(student1.getEntityId())); }
protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; }
ContextValidator implements ApplicationContextAware { protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; } }
ContextValidator implements ApplicationContextAware { protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; } }
ContextValidator implements ApplicationContextAware { protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testGetValidIdsIncludeOrphans() { EntityDefinition def = createEntityDef(EntityNames.STUDENT); Entity orphanedStudent = createEntity(EntityNames.STUDENT, 14); Entity accessStudent1 = createEntity(EntityNames.STUDENT, 1); Entity accessStudent2 = createEntity(EntityNames.STUDENT, 2); Entity noAccessStudent = createEntity(EntityNames.STUDENT, 4); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("isOrphaned", "true"); metaData.put("createdBy", "staff1"); Mockito.when(orphanedStudent.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(orphanedStudent, accessStudent1, accessStudent2, noAccessStudent); Set<String> studentIds = new HashSet(Arrays.asList("student14", "student1", "student2", "student4")); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STUDENT), Mockito.any(NeutralQuery.class))).thenReturn(students); Set<String> results = contextValidator.getValidIdsIncludeOrphans(def, studentIds, true); Assert.assertEquals(3, results.size()); }
public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void getDoNotIncludeOwningOrphans() { EntityDefinition def = createEntityDef(EntityNames.STUDENT); Entity orphanNotByUser = createEntity(EntityNames.STUDENT, 14); Entity accessStudent1 = createEntity(EntityNames.STUDENT, 1); Entity accessStudent2 = createEntity(EntityNames.STUDENT, 2); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("isOrphaned", "true"); metaData.put("createdBy", "staff2"); Mockito.when(orphanNotByUser.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(orphanNotByUser, accessStudent1, accessStudent2); Set<String> studentIds = new HashSet(Arrays.asList("student14", "student1", "student2")); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STUDENT), Mockito.any(NeutralQuery.class))).thenReturn(students); Set<String> results = contextValidator.getValidIdsIncludeOrphans(def, studentIds, true); Assert.assertEquals(2, results.size()); }
public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testPreSplit() { List<DBObject> shards = new ArrayList<DBObject>(); shards.add(new BasicDBObject("_id", "shard0")); shards.add(new BasicDBObject("_id", "shard1")); BasicDBList listShards = new BasicDBList(); listShards.add(new BasicDBObject("shards", shards)); List<String> lShards = new ArrayList<String>(); lShards.add("shard0"); lShards.add("lShard1"); Mockito.when(db.command((DBObject) Matchers.any())).thenReturn(res); Mockito.when(res.get("shards")).thenReturn(listShards); String result = MongoCommander.preSplit(shardCollections, dbName, mockedMongoTemplate); assertNull(result); Mockito.verify(db, Mockito.times(1)).command(new BasicDBObject("enableSharding", dbName)); Mockito.verify(db, Mockito.times(2)).command(new BasicDBObject("listShards", 1)); Mockito.verify(db, Mockito.times(13)).command(Matchers.any(DBObject.class)); Mockito.verify(settings, Mockito.times(1)).update(Matchers.any(DBObject.class), Matchers.any(DBObject.class), Matchers.eq(true), Matchers.eq(false)); }
public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); }
MongoCommander { public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); } }
MongoCommander { public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); } private MongoCommander(); }
MongoCommander { public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); }
MongoCommander { public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }
@Test public void testStaff1() { setContext(staff1, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff1); assertTrue("staff1 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff1 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStaff2() { setContext(staff2, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff2); assertTrue("staff2 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff2 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStaff3() { setContext(staff3, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff3); assertTrue("staff3 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff3 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStaff4() { setContext(staff4, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff4); assertTrue("staff4 must see lea1", leas.contains(lea1.getEntityId())); assertTrue("staff4 must see lea4", leas.contains(lea4.getEntityId())); assertEquals("staff4 must only see two districts", 2, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testTeacher1() { setContext(teacher1, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher1); assertTrue("teacher1 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher1 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testTeacher2() { setContext(teacher2, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher2); assertTrue("teacher2 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher2 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testTeacher3() { setContext(teacher3, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher3); assertTrue("teacher3 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher3 must only see one district", 1, leas.size()); }
public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testTeacher3LocateSEOAs() { NeutralQuery staffQuery = new NeutralQuery(); staffQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, teacher3.getEntityId())); repo.deleteAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, staffQuery); Date now = new Date(); setupSEOAs(repo, now.getTime(), teacher3, school3.getEntityId()); Set<Entity> associations = helper.locateNonExpiredSEOAs(teacher3.getEntityId()); assertTrue("teacher3 should have 3 valid associations", associations.size() == 3); }
public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; }
EdOrgHelper { public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } }
EdOrgHelper { public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } }
EdOrgHelper { public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testParents() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(school3); assertTrue(edorgs.contains(sea1.getEntityId())); assertTrue(edorgs.contains(lea1.getEntityId())); assertTrue(edorgs.contains(lea2.getEntityId())); assertTrue(edorgs.contains(lea3.getEntityId())); assertFalse(edorgs.contains(school1.getEntityId())); assertFalse(edorgs.contains(school2.getEntityId())); assertFalse(edorgs.contains(school3.getEntityId())); assertEquals(4, edorgs.size()); }
public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testParentsWithCycle() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(leaCycle1); assertFalse("leaCycle1 should not be a child of leaCycle1", edorgs.contains(leaCycle1.getEntityId())); assertTrue("leaCycle2 should be a child of leaCycle1", edorgs.contains(leaCycle2.getEntityId())); assertTrue("leaCycle3 should be a child of leaCycle1", edorgs.contains(leaCycle3.getEntityId())); assertEquals(2, edorgs.size()); }
public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void parseJSTest() { IndexJSFileParser indexJSFileParser = new IndexJSFileParser(); Set<MongoIndex> indexes = indexJSFileParser.parse(INDEX_FILE); Map<String, MongoIndex> expectedIndexes = new HashMap<String, MongoIndex>(); DBObject userSessionIndex = new BasicDBObject(); userSessionIndex.put("body.expiration", 1); userSessionIndex.put("body.hardLogout", 1); userSessionIndex.put("body.appSession.token", 1); expectedIndexes.put("usersession", new MongoIndex("userSession", false, userSessionIndex)); DBObject tenantIndex = new BasicDBObject(); tenantIndex.put("body.tenantId", 1); expectedIndexes.put("tenant", new MongoIndex("tenant", true, tenantIndex)); assertEquals(4, indexes.size()); for (MongoIndex idx : indexes) { if (idx.getCollection().equalsIgnoreCase("realm")) { fail("Invalid index was parsed"); } else if (idx.getCollection().equalsIgnoreCase("usersession")) { assertEquals(idx, expectedIndexes.get("usersession")); } else if (idx.getCollection().equalsIgnoreCase("tenant")) { assertEquals(idx, expectedIndexes.get("tenant")); assertTrue(idx.isUnique()); } } }
@Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; }
IndexJSFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; } }
IndexJSFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; } }
IndexJSFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; } @Override Set<MongoIndex> parse(String fileName); static Map<String, Object> parseJson(String jsonString); }
IndexJSFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; } @Override Set<MongoIndex> parse(String fileName); static Map<String, Object> parseJson(String jsonString); }
@Test public void testParentsOfSea() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(sea1); assertEquals(0, edorgs.size()); }
public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStudent1() { Set<String> edorgs = helper.getDirectEdorgs(student1); assertEquals(1, edorgs.size()); assertTrue("student1 should see school1", edorgs.contains(school1.getEntityId())); assertFalse("student1 should not see school2", edorgs.contains(school2.getEntityId())); assertFalse("student1 should not see school3", edorgs.contains(school3.getEntityId())); }
public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStudent2() { Set<String> edorgs = helper.getDirectEdorgs(student2); assertEquals(1, edorgs.size()); assertFalse("student2 should not see school1", edorgs.contains(school1.getEntityId())); assertTrue("student2 should see school2", edorgs.contains(school2.getEntityId())); assertFalse("student2 should not see school3", edorgs.contains(school3.getEntityId())); }
public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStudent3() { Set<String> edorgs = helper.getDirectEdorgs(student3); assertEquals(1, edorgs.size()); assertFalse("student3 should not see school1", edorgs.contains(school1.getEntityId())); assertFalse("student3 should not see school2", edorgs.contains(school2.getEntityId())); assertTrue("student3 should see school3", edorgs.contains(school3.getEntityId())); }
public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testHeirarchicalEdorgs() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(school1); assertEquals(2, edorgs.size()); assertFalse("school1 should not see lea3", edorgs.contains(lea3.getEntityId())); assertFalse("school1 should not see lea2", edorgs.contains(lea2.getEntityId())); assertTrue("school1 should see lea1", edorgs.contains(lea1.getEntityId())); assertTrue("school1 should see sea1", edorgs.contains(sea1.getEntityId())); }
public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetChildLeaOfEdorgs() { List<String> edorgs = helper.getDirectChildLEAsOfEdOrg(lea2); assertEquals(1, edorgs.size()); assertFalse("lea1 should not be a child of lea2", edorgs.contains(lea1.getEntityId())); assertFalse("lea2 should not be a child of lea2", edorgs.contains(lea2.getEntityId())); assertTrue("lea3 should be a child of lea2", edorgs.contains(lea3.getEntityId())); }
public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); }
EdOrgHelper { public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } }
EdOrgHelper { public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } }
EdOrgHelper { public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetAllChildLeaOfEdorgs() { Set<String> edorgs = helper.getAllChildLEAsOfEdOrg(sea1); assertEquals(4, edorgs.size()); assertTrue("lea1 should be a child of sea1", edorgs.contains(lea1.getEntityId())); assertTrue("lea2 should be a child of sea1", edorgs.contains(lea2.getEntityId())); assertTrue("lea3 should be a child of sea1", edorgs.contains(lea3.getEntityId())); assertTrue("lea4 should be a child of sea1", edorgs.contains(lea4.getEntityId())); }
public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetAllChildLeaOfEdorgsWithCycle() { Set<String> edorgs = helper.getAllChildLEAsOfEdOrg(leaCycle1); assertEquals(2, edorgs.size()); assertFalse("leaCycle1 should not be a child of leaCycle1", edorgs.contains(leaCycle1.getEntityId())); assertTrue("leaCycle2 should be a child of leaCycle1", edorgs.contains(leaCycle2.getEntityId())); assertTrue("leaCycle3 should be a child of leaCycle1", edorgs.contains(leaCycle3.getEntityId())); }
public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetChildEdOrgsNameWithoutParents() { Set<String> children = helper.getChildEdOrgsName(Arrays.asList(lea2.getEntityId(), leaCycle1.getEntityId())); assertTrue("expected to see school2 in the list of children", children.contains(school2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see lea3 in the list of children", children.contains(lea3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school3 in the list of children", children.contains(school3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle2 in the list of children", children.contains(leaCycle2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle3 in the list of children", children.contains(leaCycle3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertEquals(5, children.size()); }
public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetChildEdOrgsNameWithParents() { Set<String> children = helper.getChildEdOrgsName(Arrays.asList(lea2.getEntityId(), leaCycle1.getEntityId()), true); assertTrue("expected to see lea2 in the list of children", children.contains(lea2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle1 in the list of children", children.contains(leaCycle1.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school2 in the list of children", children.contains(school2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see lea3 in the list of children", children.contains(lea3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school3 in the list of children", children.contains(school3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle2 in the list of children", children.contains(leaCycle2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle3 in the list of children", children.contains(leaCycle3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertEquals(7, children.size()); }
public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void parseTxtTest() { IndexTxtFileParser indexTxtFileParser = new IndexTxtFileParser(); Set<MongoIndex> indexes = indexTxtFileParser.parse(INDEX_TXT_FILE); assertEquals(2, indexes.size()); Map<String, MongoIndex> expectedIndex = new HashMap<String, MongoIndex>(); DBObject adminDelegationIndex = new BasicDBObject(); adminDelegationIndex.put("body.localEdOrgId", 1); expectedIndex.put("adminDelegation", new MongoIndex("adminDelegation", false, adminDelegationIndex, false)); DBObject applicationAuthorizationIndex = new BasicDBObject(); applicationAuthorizationIndex.put("body.appIds", 1); expectedIndex.put("applicationAuthorization", new MongoIndex("applicationAuthorization", true, applicationAuthorizationIndex, false)); for (MongoIndex index : indexes) { String collection = index.getCollection(); if (collection.equalsIgnoreCase("learningObjective")) { fail("Invalid index was parsed"); } else if (collection.equalsIgnoreCase("adminDelegation")) { assertEquals(index, expectedIndex.get("adminDelegation")); } else if (collection.equalsIgnoreCase("applicationAuthorization")) { assertEquals(index, expectedIndex.get("applicationAuthorization")); assertTrue(index.isUnique()); } } }
@Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); }
IndexTxtFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); } }
IndexTxtFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); } }
IndexTxtFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); } @Override Set<MongoIndex> parse(String fileName); static Set<String> loadIndexes(String indexFile); }
IndexTxtFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); } @Override Set<MongoIndex> parse(String fileName); static Set<String> loadIndexes(String indexFile); }
@Test public void testLoginRealmIdsForSEA() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea = buildEdOrg("LEA", sea, false); Entity seaStaff = buildStaff("SEA Staff", sea); Entity seaRealm = buildRealm(sea); Entity leaRealm = buildRealm(lea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, seaRealm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, leaRealm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testLoginRealmIdsForLEA() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea = buildEdOrg("LEA", sea, false); Entity leaStaff = buildStaff("LEA Staff", lea); Entity seaRealm = buildRealm(sea); Entity leaRealm = buildRealm(lea); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, seaRealm)); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(leaStaff, leaRealm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testSeaWithNoDirectRealm() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea1Realm = buildRealm(lea1); Entity lea2Realm = buildRealm(lea2); Entity seaStaff = buildStaff("SEA Staff", sea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea2Realm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testLeaWithNoDirectRealm() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea3 = buildEdOrg("LEA3", lea2, false); Entity lea1Realm = buildRealm(lea1); Entity lea3Realm = buildRealm(lea3); Entity seaRealm = buildRealm(sea); Entity leaStaff = buildStaff("LEA Staff", lea2); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(leaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, lea3Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, seaRealm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testSeaWithNoDirectRealmAndTwoAssociations() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea3 = buildEdOrg("LEA3", lea2, false); Entity lea1Realm = buildRealm(lea1); Entity lea3Realm = buildRealm(lea3); Entity seaStaff = buildStaff("SEA Staff", sea, lea2); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea3Realm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testSeaWithNoDirectRealmAndTwoRealmsOnSameTier() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", sea, false); Entity lea3 = buildEdOrg("LEA3", lea1, false); Entity lea1Realm = buildRealm(lea1); Entity lea2Realm = buildRealm(lea2); Entity lea3Realm = buildRealm(lea3); Entity seaStaff = buildStaff("SEA Staff", sea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea2Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea3Realm)); }
public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testGetAssociatedRealmIsTenantSpecific() { Entity sea = buildEdOrg("SEA1", null, injector.TENANT_ID, true); Entity lea1 = buildEdOrg("LEA1", sea, injector.TENANT_ID, false); Entity lea2 = buildEdOrg("LEA1", null, "Two", false); Entity lea2Realm = buildRealm(lea2, "Two"); Entity lea1Realm = buildRealm(lea1, injector.TENANT_ID); Entity staff = buildStaff("LEA One", lea1); injector.setCustomContext("LEA", "LEA One", lea1Realm.getEntityId(), Arrays.asList("Realm Administrator"), staff, (String) lea1Realm.getBody().get("edOrg")); Set<String> realmIds = helper.getAssociatedRealmIds(); assertTrue(realmIds != null); assertTrue(realmIds.contains(lea1Realm.getEntityId())); }
public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; }
RealmHelper { public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; } }
RealmHelper { public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; } }
RealmHelper { public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); }
RealmHelper { public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test @ExpectedException(value = AccessDeniedException.class) public void testDenyWritingOutsideOfEdOrgHierarchyCreate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); when(uriInfo.getPathSegments()).thenReturn(postPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); }
public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
@Test public void testValidWritingInEdOrgHierarchyCreate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(postPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); }
public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
@Test @ExpectedException(value = AccessDeniedException.class) public void testDenyUpdateWhenNoEdOrgMatchToExistingEntity() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_A); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); }
public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
@Test public void testPurgingSystemCollections() throws Exception { RangedWorkNote workNote = RangedWorkNote.createSimpleWorkNote(BATCHJOBID); Exchange ex = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(ex.getIn()).thenReturn(message); Mockito.when(message.getBody(RangedWorkNote.class)).thenReturn(workNote); NewBatchJob job = new NewBatchJob(); job.setProperty("tenantId", "SLI"); Mockito.when(mockBatchJobDAO.findBatchJobById(BATCHJOBID)).thenReturn(job); Set<String> collectionNames = new HashSet<String>(); collectionNames.add("system.js"); collectionNames.add("system.indexes"); Mockito.when(mongoTemplate.getCollectionNames()).thenReturn(collectionNames); purgeProcessor.process(ex); Mockito.verify(mongoTemplate, Mockito.never()).remove(Mockito.any(Query.class), Mockito.eq("system.js")); }
@Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } }
PurgeProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } } }
PurgeProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } } }
PurgeProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } } @Override void process(Exchange exchange); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); BatchJobDAO getBatchJobDAO(); AbstractMessageReport getMessageReport(); boolean isSandboxEnabled(); void setBatchJobDAO(BatchJobDAO batchJobDAO); void setMessageReport(AbstractMessageReport messageReport); void setSandboxEnabled(boolean sandboxEnabled); void setPurgeBatchSize(int purgeBatchSize); void setDeltaJournal(DeltaJournal deltaJournal); void setDeltasEnabled(boolean deltasEnabled); }
PurgeProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } } @Override void process(Exchange exchange); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); BatchJobDAO getBatchJobDAO(); AbstractMessageReport getMessageReport(); boolean isSandboxEnabled(); void setBatchJobDAO(BatchJobDAO batchJobDAO); void setMessageReport(AbstractMessageReport messageReport); void setSandboxEnabled(boolean sandboxEnabled); void setPurgeBatchSize(int purgeBatchSize); void setDeltaJournal(DeltaJournal deltaJournal); void setDeltasEnabled(boolean deltasEnabled); static final BatchJobStageType BATCH_JOB_STAGE; }
@Test @ExpectedException(value = AccessDeniedException.class) public void testDenyUpdateWhenNoEdOrgMatchToNewEntity() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); }
public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
@Test public void testValidUpdate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_A); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); }
public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }