protected ScimUser getAndReturnUser(int status, ScimUser user, String token) throws Exception {
    MockHttpServletRequestBuilder get =
        MockMvcRequestBuilders.get("/Users/" + user.getId())
            .header("Authorization", "Bearer " + token)
            .accept(APPLICATION_JSON);

    if (status == HttpStatus.OK.value()) {
      String json =
          getMockMvc()
              .perform(get)
              .andExpect(status().is(status))
              .andExpect(header().string("ETag", "\"" + user.getVersion() + "\""))
              .andExpect(jsonPath("$.userName").value(user.getPrimaryEmail()))
              .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
              .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()))
              .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
              .andReturn()
              .getResponse()
              .getContentAsString();
      return JsonUtils.readValue(json, ScimUser.class);
    } else {
      getMockMvc().perform(get).andExpect(status().is(status));
      return null;
    }
  }
  // TODO: add cases for username no existing external user with username not email
  @Test
  public void accept_invitation_with_external_user_that_does_not_have_email_as_their_username() {
    String userId = "user-id-001";
    String email = "*****@*****.**";
    String actualUsername = "******";
    ScimUser userBeforeAccept = new ScimUser(userId, email, "first", "last");
    userBeforeAccept.setPrimaryEmail(email);
    userBeforeAccept.setOrigin(Origin.SAML);

    when(scimUserProvisioning.verifyUser(eq(userId), anyInt())).thenReturn(userBeforeAccept);
    when(scimUserProvisioning.retrieve(eq(userId))).thenReturn(userBeforeAccept);

    BaseClientDetails clientDetails =
        new BaseClientDetails("client-id", null, null, null, null, "http://example.com/redirect");
    when(clientDetailsService.loadClientByClientId("acmeClientId")).thenReturn(clientDetails);

    Map<String, String> userData = new HashMap<>();
    userData.put(USER_ID, userBeforeAccept.getId());
    userData.put(EMAIL, userBeforeAccept.getPrimaryEmail());
    userData.put(REDIRECT_URI, "http://someother/redirect");
    userData.put(CLIENT_ID, "acmeClientId");
    when(expiringCodeStore.retrieveCode(anyString()))
        .thenReturn(
            new ExpiringCode(
                "code",
                new Timestamp(System.currentTimeMillis()),
                JsonUtils.writeValueAsString(userData)));

    ScimUser userAfterAccept =
        new ScimUser(
            userId,
            actualUsername,
            userBeforeAccept.getGivenName(),
            userBeforeAccept.getFamilyName());
    userAfterAccept.setPrimaryEmail(email);

    when(scimUserProvisioning.verifyUser(eq(userId), anyInt())).thenReturn(userAfterAccept);

    ScimUser acceptedUser = emailInvitationsService.acceptInvitation("code", "password").getUser();
    assertEquals(userAfterAccept.getUserName(), acceptedUser.getUserName());
    assertEquals(userAfterAccept.getName(), acceptedUser.getName());
    assertEquals(userAfterAccept.getPrimaryEmail(), acceptedUser.getPrimaryEmail());

    verify(scimUserProvisioning).verifyUser(eq(userId), anyInt());
  }
 private void assertJoe(ScimUser joe) {
   assertNotNull(joe);
   assertEquals(JOE_ID, joe.getId());
   assertEquals("Joe", joe.getGivenName());
   assertEquals("User", joe.getFamilyName());
   assertEquals("*****@*****.**", joe.getPrimaryEmail());
   assertEquals("joe", joe.getUserName());
   assertEquals("+1-222-1234567", joe.getPhoneNumbers().get(0).getValue());
   assertNull(joe.getGroups());
 }
  @Test
  public void testDeleteUserWithUaaAdminToken() throws Exception {
    ScimUser user = setUpScimUser();

    getMockMvc()
        .perform(
            (delete("/Users/" + user.getId()))
                .header("Authorization", "Bearer " + uaaAdminToken)
                .contentType(APPLICATION_JSON)
                .content(JsonUtils.writeValueAsBytes(user)))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.userName").value(user.getUserName()))
        .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
        .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
        .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()));
  }
  @Test
  public void updateModifiesExpectedData() {
    ScimUser jo = new ScimUser(null, "josephine", "Jo", "NewUser");
    jo.addEmail("*****@*****.**");
    jo.setUserType(UaaAuthority.UAA_ADMIN.getUserType());

    ScimUser joe = db.update(JOE_ID, jo);

    // Can change username
    assertEquals("josephine", joe.getUserName());
    assertEquals("*****@*****.**", joe.getPrimaryEmail());
    assertEquals("Jo", joe.getGivenName());
    assertEquals("NewUser", joe.getFamilyName());
    assertEquals(1, joe.getVersion());
    assertEquals(JOE_ID, joe.getId());
    assertNull(joe.getGroups());
  }
  @Test
  public void testUpdateUserInOtherZoneWithUaaAdminToken() throws Exception {
    IdentityZone identityZone = getIdentityZone();
    ScimUser user = setUpScimUser(identityZone);
    user.setName(new ScimUser.Name("changed", "name"));

    getMockMvc()
        .perform(
            put("/Users/" + user.getId())
                .header("Authorization", "Bearer " + uaaAdminToken)
                .header(IdentityZoneSwitchingFilter.HEADER, identityZone.getId())
                .header("If-Match", "\"" + user.getVersion() + "\"")
                .contentType(APPLICATION_JSON)
                .content(JsonUtils.writeValueAsBytes(user)))
        .andExpect(status().isOk())
        .andExpect(header().string("ETag", "\"1\""))
        .andExpect(jsonPath("$.userName").value(user.getUserName()))
        .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
        .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
        .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()));
  }
Ejemplo n.º 7
0
  @RequestMapping(
      value = "/invite_users",
      method = RequestMethod.POST,
      consumes = "application/json")
  public ResponseEntity<InvitationsResponse> inviteUsers(
      @RequestBody InvitationsRequest invitations,
      @RequestParam(value = "client_id", required = false) String clientId,
      @RequestParam(value = "redirect_uri") String redirectUri) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof OAuth2Authentication) {
      OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;

      if (clientId == null) {
        clientId = oAuth2Authentication.getOAuth2Request().getClientId();
      }
    }

    InvitationsResponse invitationsResponse = new InvitationsResponse();

    DomainFilter filter = new DomainFilter();
    List<IdentityProvider> activeProviders =
        providers.retrieveActive(IdentityZoneHolder.get().getId());
    ClientDetails client = clients.loadClientByClientId(clientId);
    for (String email : invitations.getEmails()) {
      try {
        List<IdentityProvider> providers = filter.filter(activeProviders, client, email);
        if (providers.size() == 1) {
          ScimUser user = findOrCreateUser(email, providers.get(0).getOriginKey());

          String accountsUrl = UaaUrlUtils.getUaaUrl("/invitations/accept");

          Map<String, String> data = new HashMap<>();
          data.put(InvitationConstants.USER_ID, user.getId());
          data.put(InvitationConstants.EMAIL, user.getPrimaryEmail());
          data.put(CLIENT_ID, clientId);
          data.put(REDIRECT_URI, redirectUri);
          data.put(ORIGIN, user.getOrigin());
          Timestamp expiry =
              new Timestamp(
                  System.currentTimeMillis() + (INVITATION_EXPIRY_DAYS * 24 * 60 * 60 * 1000));
          ExpiringCode code =
              expiringCodeStore.generateCode(JsonUtils.writeValueAsString(data), expiry, null);

          String invitationLink = accountsUrl + "?code=" + code.getCode();
          try {
            URL inviteLink = new URL(invitationLink);
            invitationsResponse
                .getNewInvites()
                .add(
                    InvitationsResponse.success(
                        user.getPrimaryEmail(), user.getId(), user.getOrigin(), inviteLink));
          } catch (MalformedURLException mue) {
            invitationsResponse
                .getFailedInvites()
                .add(
                    InvitationsResponse.failure(
                        email,
                        "invitation.exception.url",
                        String.format("Malformed url", invitationLink)));
          }
        } else if (providers.size() == 0) {
          invitationsResponse
              .getFailedInvites()
              .add(
                  InvitationsResponse.failure(
                      email, "provider.non-existent", "No authentication provider found."));
        } else {
          invitationsResponse
              .getFailedInvites()
              .add(
                  InvitationsResponse.failure(
                      email, "provider.ambiguous", "Multiple authentication providers found."));
        }
      } catch (ScimResourceConflictException x) {
        invitationsResponse
            .getFailedInvites()
            .add(
                InvitationsResponse.failure(
                    email,
                    "user.ambiguous",
                    "Multiple users with the same origin matched to the email address."));
      } catch (UaaException uaae) {
        invitationsResponse
            .getFailedInvites()
            .add(InvitationsResponse.failure(email, "invitation.exception", uaae.getMessage()));
      }
    }
    return new ResponseEntity<>(invitationsResponse, HttpStatus.OK);
  }