@Test
 public void test_cannot_delete_uaa_zone_users() throws Exception {
   ScimUser user = new ScimUser(null, "*****@*****.**", "Jo", "User");
   user.addEmail("*****@*****.**");
   user.setOrigin(UAA);
   ScimUser created = db.createUser(user, "j7hyqpassX");
   assertEquals("*****@*****.**", created.getUserName());
   assertNotNull(created.getId());
   assertEquals(UAA, created.getOrigin());
   assertThat(
       jdbcTemplate.queryForObject(
           "select count(*) from users where origin=? and identity_zone_id=?",
           new Object[] {UAA, IdentityZone.getUaa().getId()},
           Integer.class),
       is(3));
   IdentityProvider loginServer =
       new IdentityProvider().setOriginKey(UAA).setIdentityZoneId(IdentityZone.getUaa().getId());
   db.onApplicationEvent(new EntityDeletedEvent<>(loginServer));
   assertThat(
       jdbcTemplate.queryForObject(
           "select count(*) from users where origin=? and identity_zone_id=?",
           new Object[] {UAA, IdentityZone.getUaa().getId()},
           Integer.class),
       is(3));
 }
 @Test
 public void test_cannot_delete_uaa_provider_users_in_other_zone() throws Exception {
   String id = generator.generate();
   IdentityZone zone = MultitenancyFixture.identityZone(id, id);
   IdentityZoneHolder.set(zone);
   ScimUser user = new ScimUser(null, "*****@*****.**", "Jo", "User");
   user.addEmail("*****@*****.**");
   user.setOrigin(UAA);
   ScimUser created = db.createUser(user, "j7hyqpassX");
   assertEquals("*****@*****.**", created.getUserName());
   assertNotNull(created.getId());
   assertEquals(UAA, created.getOrigin());
   assertEquals(zone.getId(), created.getZoneId());
   assertThat(
       jdbcTemplate.queryForObject(
           "select count(*) from users where origin=? and identity_zone_id=?",
           new Object[] {UAA, zone.getId()},
           Integer.class),
       is(1));
   IdentityProvider loginServer =
       new IdentityProvider().setOriginKey(UAA).setIdentityZoneId(zone.getId());
   db.onApplicationEvent(new EntityDeletedEvent<>(loginServer));
   assertThat(
       jdbcTemplate.queryForObject(
           "select count(*) from users where origin=? and identity_zone_id=?",
           new Object[] {UAA, zone.getId()},
           Integer.class),
       is(1));
 }
  @Test
  public void testUpdateUserPasswordDoesntChange() throws Exception {
    String username = "******" + new RandomValueStringGenerator().generate() + "@test.org";
    ScimUser scimUser = new ScimUser(null, username, "User", "Example");
    ScimUser.Email email = new ScimUser.Email();
    email.setValue(username);
    scimUser.setEmails(Arrays.asList(email));
    scimUser.setSalt("salt");
    scimUser = db.createUser(scimUser, "password");
    assertNotNull(scimUser);
    assertEquals("salt", scimUser.getSalt());
    scimUser.setSalt("newsalt");

    String passwordHash =
        jdbcTemplate.queryForObject(
            "select password from users where id=?", new Object[] {scimUser.getId()}, String.class);
    assertNotNull(passwordHash);

    db.changePassword(scimUser.getId(), null, "password");
    assertEquals(
        passwordHash,
        jdbcTemplate.queryForObject(
            "select password from users where id=?",
            new Object[] {scimUser.getId()},
            String.class));

    db.changePassword(scimUser.getId(), "password", "password");
    assertEquals(
        passwordHash,
        jdbcTemplate.queryForObject(
            "select password from users where id=?",
            new Object[] {scimUser.getId()},
            String.class));
  }
 @Test
 public void validateOriginAndExternalIDDuringCreateAndUpdate() {
   String origin = "test";
   String externalId = "testId";
   ScimUser user = new ScimUser(null, "*****@*****.**", "Jo", "User");
   user.setOrigin(origin);
   user.setExternalId(externalId);
   user.addEmail("*****@*****.**");
   ScimUser created = db.createUser(user, "j7hyqpassX");
   assertEquals("*****@*****.**", created.getUserName());
   assertNotNull(created.getId());
   assertNotSame(user.getId(), created.getId());
   Map<String, Object> map =
       template.queryForMap("select * from users where id=?", created.getId());
   assertEquals(user.getUserName(), map.get("userName"));
   assertEquals(user.getUserType(), map.get(UaaAuthority.UAA_USER.getUserType()));
   assertNull(created.getGroups());
   assertEquals(origin, created.getOrigin());
   assertEquals(externalId, created.getExternalId());
   String origin2 = "test2";
   String externalId2 = "testId2";
   created.setOrigin(origin2);
   created.setExternalId(externalId2);
   ScimUser updated = db.update(created.getId(), created);
   assertEquals(origin2, updated.getOrigin());
   assertEquals(externalId2, updated.getExternalId());
 }
 @Test
 public void canDeleteExistingUser() {
   String tmpUserId = createUserForDelete();
   db.setDeactivateOnDelete(false);
   db.delete(tmpUserId, 0);
   assertEquals(0, template.queryForList("select * from users where id=?", tmpUserId).size());
   assertEquals(0, db.query("username eq \"" + tmpUserId + "\"").size());
 }
 @Test
 public void testUpdatedVersionedUserVerified() {
   String tmpUserIdString = createUserForDelete();
   ScimUser user = db.retrieve(tmpUserIdString);
   assertFalse(user.isVerified());
   user = db.verifyUser(tmpUserIdString, user.getVersion());
   assertTrue(user.isVerified());
   removeUser(tmpUserIdString);
 }
 @Test
 public void testUserVerifiedThroughUpdate() {
   String tmpUserIdString = createUserForDelete();
   ScimUser user = db.retrieve(tmpUserIdString);
   assertFalse(user.isVerified());
   user.setVerified(true);
   user = db.update(tmpUserIdString, user);
   assertTrue(user.isVerified());
   removeUser(tmpUserIdString);
 }
 @Test
 public void countUsersAcrossAllZones() {
   IdentityZoneHolder.clear();
   int beginningCount = db.getTotalCount();
   canCreateUserInDefaultIdentityZone();
   IdentityZoneHolder.clear();
   assertEquals(beginningCount + 1, db.getTotalCount());
   canCreateUserInOtherIdentityZone();
   IdentityZoneHolder.clear();
   assertEquals(beginningCount + 2, db.getTotalCount());
 }
  @Test
  public void test_can_delete_zone_users() throws Exception {
    String id = generator.generate();
    IdentityZone zone = MultitenancyFixture.identityZone(id, id);
    IdentityZoneHolder.set(zone);
    ScimUser user = new ScimUser(null, "*****@*****.**", "Jo", "User");
    user.addEmail("*****@*****.**");
    user.setOrigin(UAA);
    ScimUser created = db.createUser(user, "j7hyqpassX");
    assertEquals("*****@*****.**", created.getUserName());
    assertNotNull(created.getId());
    assertEquals(UAA, created.getOrigin());
    assertEquals(zone.getId(), created.getZoneId());
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from users where origin=? and identity_zone_id=?",
            new Object[] {UAA, zone.getId()},
            Integer.class),
        is(1));
    addApprovalAndMembership(created.getId(), created.getOrigin());
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from authz_approvals where user_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(1));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from group_membership where member_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(1));

    db.onApplicationEvent(new EntityDeletedEvent<>(zone));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from users where origin=? and identity_zone_id=?",
            new Object[] {UAA, zone.getId()},
            Integer.class),
        is(0));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from authz_approvals where user_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(0));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from group_membership where member_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(0));
  }
  @Test
  public void test_can_delete_provider_users_in_default_zone() throws Exception {
    ScimUser user = new ScimUser(null, "*****@*****.**", "Jo", "User");
    user.addEmail("*****@*****.**");
    user.setOrigin(LOGIN_SERVER);
    ScimUser created = db.createUser(user, "j7hyqpassX");
    assertEquals("*****@*****.**", created.getUserName());
    assertNotNull(created.getId());
    assertEquals(LOGIN_SERVER, created.getOrigin());
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from users where origin=? and identity_zone_id=?",
            new Object[] {LOGIN_SERVER, IdentityZone.getUaa().getId()},
            Integer.class),
        is(1));
    addApprovalAndMembership(created.getId(), created.getOrigin());
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from authz_approvals where user_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(1));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from group_membership where member_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(1));

    IdentityProvider loginServer =
        new IdentityProvider()
            .setOriginKey(LOGIN_SERVER)
            .setIdentityZoneId(IdentityZone.getUaa().getId());
    db.onApplicationEvent(new EntityDeletedEvent<>(loginServer));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from users where origin=? and identity_zone_id=?",
            new Object[] {LOGIN_SERVER, IdentityZone.getUaa().getId()},
            Integer.class),
        is(0));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from authz_approvals where user_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(0));
    assertThat(
        jdbcTemplate.queryForObject(
            "select count(*) from group_membership where member_id=?",
            new Object[] {created.getId()},
            Integer.class),
        is(0));
  }
 @Test(expected = OptimisticLockingFailureException.class)
 public void testUpdatedIncorrectVersionUserVerified() {
   String tmpUserIdString = createUserForDelete();
   try {
     ScimUser user = db.retrieve(tmpUserIdString);
     assertFalse(user.isVerified());
     user = db.verifyUser(tmpUserIdString, user.getVersion() + 50);
     assertTrue(user.isVerified());
   } finally {
     removeUser(tmpUserIdString);
   }
 }
 @Test(expected = ScimResourceAlreadyExistsException.class)
 public void cannotDeactivateExistingUserAndThenCreateHimAgain() {
   String tmpUserId = createUserForDelete();
   ScimUser deletedUser = db.delete(tmpUserId, 0);
   deletedUser.setActive(true);
   try {
     db.createUser(deletedUser, "foobarspam1234");
   } catch (ScimResourceAlreadyExistsException e) {
     removeUser(tmpUserId);
     throw e;
   }
 }
 @Test(expected = ScimResourceNotFoundException.class)
 public void testUserVerifiedInvalidUserId() {
   String tmpUserIdString = createUserForDelete();
   try {
     ScimUser user = db.retrieve(tmpUserIdString);
     assertFalse(user.isVerified());
     user = db.verifyUser("-1-1-1", -1);
     assertTrue(user.isVerified());
   } finally {
     removeUser(tmpUserIdString);
   }
 }
  @Test
  public void canAddNonExistentGroupThroughEvent() throws Exception {
    String[] externalAuthorities = new String[] {"extTest1", "extTest2", "extTest3"};
    String[] userAuthorities = new String[] {"usrTest1", "usrTest2", "usrTest3"};
    String origin = "testOrigin";
    String email = "*****@*****.**";
    String firstName = "FirstName";
    String lastName = "LastName";
    String password = "";
    String externalId = null;
    String userId = new RandomValueStringGenerator().generate();
    String username = new RandomValueStringGenerator().generate();
    UaaUser user =
        getUaaUser(
            userAuthorities,
            origin,
            email,
            firstName,
            lastName,
            password,
            externalId,
            userId,
            username);
    ScimUserBootstrap bootstrap = new ScimUserBootstrap(db, gdb, mdb, Arrays.asList(user));
    bootstrap.afterPropertiesSet();

    List<ScimUser> users =
        db.query("userName eq \"" + username + "\" and origin eq \"" + origin + "\"");
    assertEquals(1, users.size());
    userId = users.get(0).getId();
    user =
        getUaaUser(
            userAuthorities,
            origin,
            email,
            firstName,
            lastName,
            password,
            externalId,
            userId,
            username);
    bootstrap.onApplicationEvent(
        new ExternalGroupAuthorizationEvent(user, getAuthorities(externalAuthorities)));

    users = db.query("userName eq \"" + username + "\" and origin eq \"" + origin + "\"");
    assertEquals(1, users.size());
    ScimUser created = users.get(0);
    Set<ScimGroup> groups = mdb.getGroupsWithMember(created.getId(), true);
    String[] expected = merge(externalAuthorities, userAuthorities);
    String[] actual = getGroupNames(groups);
    assertThat(actual, IsArrayContainingInAnyOrder.arrayContainingInAnyOrder(expected));
  }
 @Test
 public void canDeactivateExistingUser() {
   String tmpUserId = createUserForDelete();
   ScimUser deletedUser = db.delete(tmpUserId, 0);
   assertEquals(
       1,
       template
           .queryForList("select * from users where id=? and active=?", tmpUserId, false)
           .size());
   assertFalse(deletedUser.isActive());
   assertEquals(1, db.query("username eq \"" + tmpUserId + "\" and active eq false").size());
   removeUser(tmpUserId);
 }
 @Test
 public void testCreateUserCheckSalt() throws Exception {
   ScimUser scimUser = new ScimUser("user-id-3", "*****@*****.**", "User", "Example");
   ScimUser.Email email = new ScimUser.Email();
   email.setValue("*****@*****.**");
   scimUser.setEmails(Arrays.asList(email));
   scimUser.setPassword("password");
   scimUser.setSalt("salt");
   scimUser = db.create(scimUser);
   assertNotNull(scimUser);
   assertEquals("salt", scimUser.getSalt());
   scimUser.setSalt("newsalt");
   scimUser = db.update(scimUser.getId(), scimUser);
   assertNotNull(scimUser);
   assertEquals("newsalt", scimUser.getSalt());
 }
  @Test
  public void testCreateUserWithDuplicateUsername() throws Exception {
    addUser(
        "cba09242-aa43-4247-9aa0-b5c75c281f94",
        "*****@*****.**",
        "password",
        "*****@*****.**",
        "first",
        "user",
        "90438",
        defaultIdentityProviderId,
        "uaa");
    ScimUser scimUser = new ScimUser("user-id-2", "*****@*****.**", "User", "Example");
    ScimUser.Email email = new ScimUser.Email();
    email.setValue("*****@*****.**");
    scimUser.setEmails(Arrays.asList(email));
    scimUser.setPassword("password");

    try {
      db.create(scimUser);
      fail("Should have thrown an exception");
    } catch (ScimResourceAlreadyExistsException e) {
      Map<String, Object> userDetails = new HashMap<>();
      userDetails.put("active", true);
      userDetails.put("verified", false);
      userDetails.put("user_id", "cba09242-aa43-4247-9aa0-b5c75c281f94");
      assertEquals(HttpStatus.CONFLICT, e.getStatus());
      assertEquals("Username already in use: [email protected]", e.getMessage());
      assertEquals(userDetails, e.getExtraInfo());
    }
  }
  @Test
  // (expected = ScimResourceAlreadyExistsException.class)
  public void canDeleteExistingUserAndThenCreateHimAgain() {
    String tmpUserId = createUserForDelete();
    db.setDeactivateOnDelete(false);
    ScimUser deletedUser = db.delete(tmpUserId, 0);
    assertEquals(0, template.queryForList("select * from users where id=?", tmpUserId).size());

    deletedUser.setActive(true);
    ScimUser user = db.createUser(deletedUser, "foobarspam1234");
    assertNotNull(user);
    assertNotNull(user.getId());
    assertNotSame(tmpUserId, user.getId());
    assertEquals(1, db.query("username eq \"" + tmpUserId + "\"").size());
    removeUser(user.getId());
  }
  @Test
  public void testCreateUserWithDuplicateUsernameInOtherIdp() throws Exception {
    addUser(
        "cba09242-aa43-4247-9aa0-b5c75c281f94",
        "*****@*****.**",
        "password",
        "*****@*****.**",
        "first",
        "user",
        "90438",
        defaultIdentityProviderId,
        "uaa");

    String origin = "test-origin";
    createOtherIdentityProvider(origin, IdentityZone.getUaa().getId());

    ScimUser scimUser = new ScimUser(null, "*****@*****.**", "User", "Example");
    ScimUser.Email email = new ScimUser.Email();
    email.setValue("*****@*****.**");
    scimUser.setEmails(Arrays.asList(email));
    scimUser.setPassword("password");
    scimUser.setOrigin(origin);
    String userId2 = db.create(scimUser).getId();
    assertNotNull(userId2);
    assertNotEquals("cba09242-aa43-4247-9aa0-b5c75c281f94", userId2);
  }
 @Test
 public void canChangePasswordWithCorrectOldPassword() throws Exception {
   db.changePassword(JOE_ID, "joespassword", "koala123$marissa");
   String storedPassword =
       template.queryForObject("SELECT password from users where ID=?", String.class, JOE_ID);
   assertTrue(BCrypt.checkpw("koala123$marissa", storedPassword));
 }
 @Test
 public void addUsersWithSameUsername() throws Exception {
   String origin = "testOrigin";
   String email = "*****@*****.**";
   String firstName = "FirstName";
   String lastName = "LastName";
   String password = "";
   String externalId = null;
   String userId = new RandomValueStringGenerator().generate();
   String username = new RandomValueStringGenerator().generate();
   UaaUser user =
       getUaaUser(
           new String[0],
           origin,
           email,
           firstName,
           lastName,
           password,
           externalId,
           userId,
           username);
   ScimUserBootstrap bootstrap = new ScimUserBootstrap(db, gdb, mdb, Arrays.asList(user));
   bootstrap.afterPropertiesSet();
   user = user.modifySource("newOrigin", "");
   bootstrap.addUser(user);
   assertEquals(2, db.retrieveAll().size());
 }
 @Test
 public void canRetrieveUsersWithGroupsFilter() {
   List<ScimUser> users = db.query("groups.display co \"uaa.user\"");
   assertEquals(2 + existingUserCount, users.size());
   for (int i = 0; i < users.size(); i++) {
     assertNotNull(users.get(i));
   }
 }
 @Test
 public void canCreateUserWithExclamationMarkInUsername() {
   String userName = "******";
   ScimUser user = new ScimUser(null, userName, "Jo", "User");
   user.addEmail(userName);
   ScimUser created = db.createUser(user, "j7hyqpassX");
   assertEquals(userName, created.getUserName());
 }
 @Test(expected = InvalidScimResourceException.class)
 public void updateWithBadUsernameIsError() {
   ScimUser jo = new ScimUser(null, "jo$ephine", "Jo", "NewUser");
   jo.addEmail("*****@*****.**");
   jo.setVersion(1);
   ScimUser joe = db.update(JOE_ID, jo);
   assertEquals("joe", joe.getUserName());
 }
 @Test(expected = OptimisticLockingFailureException.class)
 public void updateWithWrongVersionIsError() {
   ScimUser jo = new ScimUser(null, "josephine", "Jo", "NewUser");
   jo.addEmail("*****@*****.**");
   jo.setVersion(1);
   ScimUser joe = db.update(JOE_ID, jo);
   assertEquals("joe", joe.getUserName());
 }
 @Test
 public void updateWithEmptyPhoneNumberWorks() {
   ScimUser jo = new ScimUser(null, "josephine", "Jo", "NewUser");
   PhoneNumber emptyNumber = new PhoneNumber();
   jo.addEmail("*****@*****.**");
   jo.setPhoneNumbers(Arrays.asList(emptyNumber));
   ScimUser joe = db.update(JOE_ID, jo);
 }
 @Test
 public void canAddUsers() throws Exception {
   UaaUser joe = new UaaUser("joe", "password", "*****@*****.**", "Joe", "User");
   UaaUser mabel = new UaaUser("mabel", "password", "*****@*****.**", "Mabel", "User");
   ScimUserBootstrap bootstrap = new ScimUserBootstrap(db, gdb, mdb, Arrays.asList(joe, mabel));
   bootstrap.afterPropertiesSet();
   Collection<ScimUser> users = db.retrieveAll();
   assertEquals(2, users.size());
 }
 @Test
 public void testCreatedUserNotVerified() {
   String tmpUserIdString = createUserForDelete();
   boolean verified = template.queryForObject(verifyUserSqlFormat, Boolean.class, tmpUserIdString);
   assertFalse(verified);
   ScimUser user = db.retrieve(tmpUserIdString);
   assertFalse(user.isVerified());
   removeUser(tmpUserIdString);
 }
 @Test
 public void testCreatedUserNotVerified() {
   String tmpUserIdString = createUserForDelete();
   boolean verified =
       jdbcTemplate.queryForObject(VERIFY_USER_SQL_FORMAT, Boolean.class, tmpUserIdString);
   assertFalse(verified);
   ScimUser user = db.retrieve(tmpUserIdString);
   assertFalse(user.isVerified());
   removeUser(tmpUserIdString);
 }
 @Test
 public void testUpdatedUserVerified() {
   String tmpUserIdString = createUserForDelete();
   boolean verified = template.queryForObject(verifyUserSqlFormat, Boolean.class, tmpUserIdString);
   assertFalse(verified);
   db.verifyUser(tmpUserIdString, -1);
   verified = template.queryForObject(verifyUserSqlFormat, Boolean.class, tmpUserIdString);
   assertTrue(verified);
   removeUser(tmpUserIdString);
 }