PersonaServiceImpl implements PersonaService { @Override public boolean isAllowedToImpersonate(HawkularUser actual, Persona toImpersonate) { if (actual.equals(toImpersonate)) { return true; } if (toImpersonate instanceof HawkularUser) { return false; } Resource resource = resourceService.getById(toImpersonate.getIdAsUUID()); Set<Role> roles = getEffectiveRolesForResource(actual, resource); return roles != null && roles.size() > 0; }  Persona getById(UUID id); Persona get(String id); @Override Set<Role> getEffectiveRolesForResource(Persona persona, Resource resource); @Override @Produces Persona getCurrent(); @Override boolean isAllowedToImpersonate(HawkularUser actual, Persona toImpersonate);  }
@Test public void userCanImpersonateItself() { HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); assertTrue("User should be allowed to impersonate itself", personaService.isAllowedToImpersonate(jdoe, jdoe)); }
@Test public void userCanImpersonateOwnOrganization() { HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); Organization org1 = organizationService.createOrganization(UUID.randomUUID().toString(), "", jdoe); assertTrue("User should be allowed to impersonate org", personaService.isAllowedToImpersonate(jdoe, org1)); }
@Test public void userCanImpersonateSubOrganization() { HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); Organization org1 = organizationService.createOrganization(UUID.randomUUID().toString(), "Acme, Inc", jdoe); Organization org2 = organizationService.createOrganization(UUID.randomUUID().toString(), "IT Dep", org1); assertTrue("User should be allowed to impersonate sub org", personaService.isAllowedToImpersonate(jdoe, org2)); }
@Test public void userCannotImpersonateRandomOrganization() { HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); HawkularUser jsmith = userService.getOrCreateById(UUID.randomUUID().toString()); Organization org1 = organizationService.createOrganization(UUID.randomUUID().toString(), "Another org", jsmith); assertFalse("User should not be allowed to impersonate another org", personaService.isAllowedToImpersonate(jdoe, org1)); }
@Test public void userCannotImpersonateAnotherUser() { HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); HawkularUser jsmith = userService.getOrCreateById(UUID.randomUUID().toString()); assertFalse("User should not be allowed to impersonate another user", personaService.isAllowedToImpersonate(jdoe, jsmith)); }