Search in sources :

Example 26 with Person

use of org.alfresco.rest.api.tests.client.data.Person in project alfresco-remote-api by Alfresco.

the class TestPeople method testListPeopleWithCapabilities.

@Test
public void testListPeopleWithCapabilities() throws Exception {
    String personGuestId = "guest@" + account3.getId();
    publicApiClient.setRequestContext(new RequestContext(account3.getId(), account3Admin, "admin"));
    // Are capabilities left absent when not required?
    {
        PublicApiClient.ListResponse<Person> resp = listPeople(Collections.emptyMap(), 200);
        assertNull(resp.getList().get(0).getCapabilities());
    }
    // Are capabilities populated when requested?
    {
        // Test user admin, non-guest and mutable account
        Map<String, String> parameters = Collections.singletonMap("include", "capabilities");
        PublicApiClient.ListResponse<Person> resp = listPeople(parameters, 200);
        Person personAdmin = resp.getList().stream().filter(p -> p.getUserName().equals(account3Admin)).findFirst().get();
        assertNotNull(personAdmin.getCapabilities());
        assertTrue(personAdmin.getCapabilities().get("isAdmin").booleanValue());
        assertFalse(personAdmin.getCapabilities().get("isGuest").booleanValue());
        assertTrue(personAdmin.getCapabilities().get("isMutable").booleanValue());
        // Test user non-admin, guest and non-mutable account
        System.out.println(resp.getList());
        Person personGuest = resp.getList().stream().filter(p -> p.getUserName().equals(personGuestId)).findFirst().get();
        assertNotNull(personGuest.getCapabilities());
        assertFalse(personGuest.getCapabilities().get("isAdmin").booleanValue());
        assertTrue(personGuest.getCapabilities().get("isGuest").booleanValue());
        assertFalse(personGuest.getCapabilities().get("isMutable").booleanValue());
    }
}
Also used : Pair(org.alfresco.rest.api.tests.client.Pair) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) MutableAuthenticationService(org.alfresco.service.cmr.security.MutableAuthenticationService) Date(java.util.Date) Renditions(org.alfresco.rest.api.Renditions) Client(org.alfresco.rest.api.model.Client) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) PersonService(org.alfresco.service.cmr.security.PersonService) ContentModel(org.alfresco.model.ContentModel) After(org.junit.After) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) NodeService(org.alfresco.service.cmr.repository.NodeService) HttpStatus(org.apache.commons.httpclient.HttpStatus) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) Company(org.alfresco.rest.api.tests.client.data.Company) Set(java.util.Set) UUID(java.util.UUID) ContentLimitProvider(org.alfresco.repo.content.ContentLimitProvider) Collectors(java.util.stream.Collectors) ContentService(org.alfresco.service.cmr.repository.ContentService) Serializable(java.io.Serializable) List(java.util.List) JSONAble(org.alfresco.rest.api.tests.client.data.JSONAble) JSONObject(org.json.simple.JSONObject) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) Assert.assertFalse(org.junit.Assert.assertFalse) NamespaceService(org.alfresco.service.namespace.NamespaceService) Person(org.alfresco.rest.api.tests.client.data.Person) AssociationRef(org.alfresco.service.cmr.repository.AssociationRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) PreferenceService(org.alfresco.service.cmr.preference.PreferenceService) RestApiUtil(org.alfresco.rest.api.tests.util.RestApiUtil) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ClassPathResource(org.springframework.core.io.ClassPathResource) HashMap(java.util.HashMap) LoginTicketResponse(org.alfresco.rest.api.model.LoginTicketResponse) Rendition(org.alfresco.rest.api.model.Rendition) ArrayList(java.util.ArrayList) People(org.alfresco.rest.api.tests.client.PublicApiClient.People) GUID(org.alfresco.util.GUID) ResetPasswordServiceImplTest.getWorkflowIdAndKeyFromUrl(org.alfresco.repo.security.authentication.ResetPasswordServiceImplTest.getWorkflowIdAndKeyFromUrl) QName(org.alfresco.service.namespace.QName) ThumbnailService(org.alfresco.service.cmr.thumbnail.ThumbnailService) LinkedList(java.util.LinkedList) EmailUtil(org.alfresco.util.email.EmailUtil) Before(org.junit.Before) PasswordReset(org.alfresco.rest.api.model.PasswordReset) EmptyStackException(java.util.EmptyStackException) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) HttpServletResponse(javax.servlet.http.HttpServletResponse) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) File(java.io.File) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Assert.assertNull(org.junit.Assert.assertNull) LoginTicket(org.alfresco.rest.api.model.LoginTicket) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) ResetPasswordServiceImpl(org.alfresco.repo.security.authentication.ResetPasswordServiceImpl) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Map(java.util.Map) HashMap(java.util.HashMap) Person(org.alfresco.rest.api.tests.client.data.Person) Test(org.junit.Test)

Example 27 with Person

use of org.alfresco.rest.api.tests.client.data.Person in project alfresco-remote-api by Alfresco.

the class TestPeople method testCreatePerson.

@Test
public void testCreatePerson() throws Exception {
    publicApiClient.setRequestContext(new RequestContext(account1.getId(), account1Admin, "admin"));
    Person person = new Person();
    person.setUserName("myUserName00@" + account1.getId());
    person.setFirstName("Firstname");
    person.setLastName("Lastname");
    person.setDescription("my description");
    person.setEmail("email@example.com");
    person.setSkypeId("my.skype.id");
    person.setGoogleId("google");
    person.setInstantMessageId("jabber@im.example.com");
    person.setJobTitle("International Man of Mystery");
    person.setLocation("location");
    person.setCompany(new Company("Org", "addr1", "addr2", "addr3", "AB1 1BA", "111 12312123", "222 345345345", "company.email@example.com"));
    person.setMobile("5657 567567 34543");
    person.setTelephone("1234 5678 9012");
    person.setUserStatus("userStatus");
    person.setEnabled(true);
    person.setEmailNotificationsEnabled(true);
    person.setPassword("password");
    Person p = people.create(person);
    assertEquals("myUserName00@" + account1.getId(), p.getId());
    assertEquals("Firstname", p.getFirstName());
    assertEquals("Lastname", p.getLastName());
    assertEquals("my description", p.getDescription());
    assertEquals("email@example.com", p.getEmail());
    assertEquals("my.skype.id", p.getSkypeId());
    assertEquals("google", p.getGoogleId());
    assertEquals("jabber@im.example.com", p.getInstantMessageId());
    assertEquals("International Man of Mystery", p.getJobTitle());
    assertEquals("location", p.getLocation());
    // Check embedded "company" document
    org.alfresco.rest.api.model.Company co = p.getCompany();
    assertEquals("Org", co.getOrganization());
    assertEquals("addr1", co.getAddress1());
    assertEquals("addr2", co.getAddress2());
    assertEquals("addr3", co.getAddress3());
    assertEquals("AB1 1BA", co.getPostcode());
    assertEquals("111 12312123", co.getTelephone());
    assertEquals("222 345345345", co.getFax());
    assertEquals("company.email@example.com", co.getEmail());
    assertEquals("5657 567567 34543", p.getMobile());
    assertEquals("1234 5678 9012", p.getTelephone());
    assertEquals("userStatus", p.getUserStatus());
    assertEquals(true, p.isEnabled());
    assertEquals(true, p.isEmailNotificationsEnabled());
    // -ve tests
    // create person with username too long
    person.setUserName("myUserName11111111111111111111111111111111111111111111111111111111111111111111111111111111@" + account1.getId());
    people.create(person, 400);
    // create person with invalid characters ("/", "\", "\n", "\r")
    {
        char[] invalidCharacters = { '/', '\\', '\n', '\r' };
        for (char invalidCharacter : invalidCharacters) {
            person.setUserName("myUser" + invalidCharacter + "Name@" + account1.getId());
            people.create(person, 400);
        }
    }
    // check for reserved authority prefixes
    person.setUserName("GROUP_EVERYONE");
    people.create(person, 400);
    person.setUserName("GROUP_mygroup");
    people.create(person, 400);
    person.setUserName("ROLE_ANYTHING");
    people.create(person, 400);
    // lower case
    person.setUserName("role_whatever");
    people.create(person, 400);
}
Also used : Company(org.alfresco.rest.api.tests.client.data.Company) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Person(org.alfresco.rest.api.tests.client.data.Person) Test(org.junit.Test)

Example 28 with Person

use of org.alfresco.rest.api.tests.client.data.Person in project alfresco-remote-api by Alfresco.

the class TestPeople method testPagingAndDefaultSorting.

/**
 * Tests the capability paginate the list of people verifies default
 * sorting, skip = 1, count = 3
 *
 * @throws Exception
 */
@Test
public void testPagingAndDefaultSorting() throws Exception {
    publicApiClient.setRequestContext(new RequestContext(account4.getId(), account4Admin, "admin"));
    // paging
    int skipCount = 1;
    int maxItems = 3;
    int totalResults = 5;
    PublicApiClient.Paging paging = getPaging(skipCount, maxItems, totalResults, totalResults);
    PublicApiClient.ListResponse<Person> resp = listPeople(paging, null, false, 200);
    List<Person> expectedList = new LinkedList<>();
    expectedList.add((Person) personAlice);
    expectedList.add((Person) personAliceD);
    expectedList.add((Person) personBen);
    checkList(expectedList, paging.getExpectedPaging(), resp);
}
Also used : PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Person(org.alfresco.rest.api.tests.client.data.Person) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 29 with Person

use of org.alfresco.rest.api.tests.client.data.Person in project alfresco-remote-api by Alfresco.

the class TestPeople method testResetPassword.

/**
 * Tests reset password.
 * <p>POST:</p>
 * <ul>
 * <li> {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/people/<userId>/request-password-reset} </li>
 * <li> {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/people/<userId>/reset-password} </li>
 * </ul>
 */
@Test
public void testResetPassword() throws Exception {
    // As Admin, create a user
    setRequestContext(account1.getId(), account1Admin, "admin");
    Person person = new Person();
    person.setUserName("john.doe@" + account1.getId());
    person.setFirstName("John");
    person.setLastName("Doe");
    person.setEmail("john.doe@alfresco.com");
    person.setEnabled(true);
    person.setEmailNotificationsEnabled(true);
    person.setPassword("password");
    people.create(person);
    // un-authenticated API
    setRequestContext(account1.getId(), null, null);
    // Just try to login, to test the new created user credential
    LoginTicket loginRequest = new LoginTicket();
    loginRequest.setUserId(person.getUserName());
    loginRequest.setPassword(person.getPassword());
    // Authenticate and create a ticket
    HttpResponse response = post("tickets", RestApiUtil.toJsonAsString(loginRequest), null, null, "authentication", 201);
    LoginTicketResponse loginResponse = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), LoginTicketResponse.class);
    assertNotNull(loginResponse.getId());
    assertNotNull(loginResponse.getUserId());
    /**
     * Reset Password
     */
    // First make the service to send a synchronous email
    ResetPasswordServiceImpl passwordService = applicationContext.getBean("resetPasswordService", ResetPasswordServiceImpl.class);
    passwordService.setSendEmailAsynchronously(false);
    // Get the 'mail' bean in a test mode.
    EmailUtil emailUtil = new EmailUtil(applicationContext);
    try {
        // Un-authenticated API
        setRequestContext(account1.getId(), null, null);
        // Reset email (just in case other tests didn't clean up...)
        emailUtil.reset();
        // Request reset password
        Client client = new Client().setClient("share");
        post(getRequestResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(client), 202);
        assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
        MimeMessage msg = emailUtil.getLastEmail();
        assertNotNull("There should be an email.", msg);
        assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
        // Check the recipient is the person who requested the reset password
        assertEquals(person.getEmail(), msg.getAllRecipients()[0].toString());
        // There should be a subject
        assertNotNull("There should be a subject.", msg.getSubject());
        // Check the reset password url.
        String resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
        assertNotNull("Wrong email is sent.", resetPasswordUrl);
        // Get the workflow id and key
        org.alfresco.util.Pair<String, String> pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
        assertNotNull("Workflow Id can't be null.", pair.getFirst());
        assertNotNull("Workflow Key can't be null.", pair.getSecond());
        // Reset the email helper, to get rid of the request reset password email
        emailUtil.reset();
        // Un-authenticated APIs as we are still using the 'setRequestContext(account1.getId(), null, null)' set above.
        // Reset the password
        PasswordReset passwordReset = new PasswordReset().setPassword("changed").setId(pair.getFirst()).setKey(pair.getSecond());
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordReset), 202);
        assertEquals("A reset password confirmation email should have been sent.", 1, emailUtil.getSentCount());
        msg = emailUtil.getLastEmail();
        assertNotNull("There should be an email.", msg);
        assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
        assertEquals(person.getEmail(), msg.getAllRecipients()[0].toString());
        // There should be a subject
        assertNotNull("There should be a subject.", msg.getSubject());
        // Try to login with old credential
        post("tickets", RestApiUtil.toJsonAsString(loginRequest), null, null, "authentication", 403);
        // Set the new password
        loginRequest.setPassword(passwordReset.getPassword());
        response = post("tickets", RestApiUtil.toJsonAsString(loginRequest), null, null, "authentication", 201);
        loginResponse = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), LoginTicketResponse.class);
        assertNotNull(loginResponse.getId());
        assertNotNull(loginResponse.getUserId());
        /*
             * Negative tests
             */
        // First, reset the email helper
        emailUtil.reset();
        // Try reset with the used workflow
        // Note: we still return 202 response for security reasons
        passwordReset.setPassword("changedAgain");
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordReset), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
        // Request reset password - Invalid user (user does not exist)
        post(getRequestResetPasswordUrl(System.currentTimeMillis() + "noUser"), RestApiUtil.toJsonAsString(client), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
        // As Admin disable the user
        setRequestContext(account1.getId(), account1Admin, "admin");
        Map<String, String> params = Collections.singletonMap("fields", "enabled");
        Person updatedPerson = people.update(person.getUserName(), qjson("{`enabled`:" + false + "}"), params, 200);
        assertFalse(updatedPerson.isEnabled());
        // Un-authenticated API
        setRequestContext(account1.getId(), null, null);
        // Request reset password - Invalid user (user is disabled)
        post(getRequestResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(client), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
        // Client is not specified
        client = new Client();
        post(getRequestResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(client), 400);
        // Reset password
        // First, reset the email helper and enable the user
        emailUtil.reset();
        // As Admin enable the user
        setRequestContext(account1.getId(), account1Admin, "admin");
        params = Collections.singletonMap("fields", "enabled");
        updatedPerson = people.update(person.getUserName(), qjson("{`enabled`:" + true + "}"), params, 200);
        assertTrue(updatedPerson.isEnabled());
        // Un-authenticated API
        setRequestContext(account1.getId(), null, null);
        client = new Client().setClient("share");
        post(getRequestResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(client), 202);
        assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
        resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
        // Check the reset password url.
        assertNotNull("Wrong email is sent.", resetPasswordUrl);
        // Get the workflow id and key
        pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
        assertNotNull("Workflow Id can't be null.", pair.getFirst());
        assertNotNull("Workflow Key can't be null.", pair.getSecond());
        // Reset the email helper, to get rid of the request reset password email
        emailUtil.reset();
        // Invalid request - password is not provided
        PasswordReset passwordResetInvalid = new PasswordReset().setId(pair.getFirst()).setKey(pair.getSecond());
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordResetInvalid), 400);
        // Invalid request - workflow id is not provided
        passwordResetInvalid.setPassword("changedAgain").setId(null);
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordResetInvalid), 400);
        // Invalid request - workflow key is not provided
        passwordResetInvalid.setId(pair.getFirst()).setKey(null);
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordResetInvalid), 400);
        // Invalid request - Invalid workflow id
        // Note: we still return 202 response for security reasons
        passwordResetInvalid = new PasswordReset().setPassword("changedAgain").setId(// Invalid Id
        "activiti$" + System.currentTimeMillis()).setKey(pair.getSecond());
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordResetInvalid), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
        // Invalid request - Invalid workflow key
        // Note: we still return 202 response for security reasons
        passwordResetInvalid = new PasswordReset().setPassword("changedAgain").setId(pair.getFirst()).setKey(// Invalid Key
        GUID.generate());
        post(getResetPasswordUrl(person.getUserName()), RestApiUtil.toJsonAsString(passwordResetInvalid), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
        // Invalid request (not the same user) - The given user id 'user1' does not match the person's user id who requested the password reset.
        // Note: we still return 202 response for security reasons
        passwordResetInvalid = new PasswordReset().setPassword("changedAgain").setId(pair.getFirst()).setKey(pair.getSecond());
        post(getResetPasswordUrl(user1), RestApiUtil.toJsonAsString(passwordResetInvalid), 202);
        assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
    } finally {
        passwordService.setSendEmailAsynchronously(true);
        emailUtil.reset();
    }
}
Also used : HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) EmailUtil(org.alfresco.util.email.EmailUtil) ResetPasswordServiceImpl(org.alfresco.repo.security.authentication.ResetPasswordServiceImpl) LoginTicket(org.alfresco.rest.api.model.LoginTicket) LoginTicketResponse(org.alfresco.rest.api.model.LoginTicketResponse) MimeMessage(javax.mail.internet.MimeMessage) PasswordReset(org.alfresco.rest.api.model.PasswordReset) Client(org.alfresco.rest.api.model.Client) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) Person(org.alfresco.rest.api.tests.client.data.Person) Test(org.junit.Test)

Example 30 with Person

use of org.alfresco.rest.api.tests.client.data.Person in project alfresco-remote-api by Alfresco.

the class TestPeople method testUpdatePersonWithRestrictedResponseFields.

@Test
public void testUpdatePersonWithRestrictedResponseFields() throws PublicApiException {
    final String personId = account3.createUser().getId();
    publicApiClient.setRequestContext(new RequestContext(account3.getId(), account3Admin, "admin"));
    String updatedFirstName = "Updated firstName";
    Map<String, String> params = new HashMap<>();
    params.put("fields", "id,firstName");
    HttpResponse response = people.update("people", personId, null, null, "{\n" + "  \"firstName\": \"" + updatedFirstName + "\"\n" + "}", params, "Expected 200 response when updating " + personId, 200);
    Person updatedPerson = Person.parsePerson((JSONObject) response.getJsonResponse().get("entry"));
    assertNotNull(updatedPerson.getId());
    assertEquals(updatedFirstName, updatedPerson.getFirstName());
    assertNull(updatedPerson.getEmail());
}
Also used : HashMap(java.util.HashMap) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Person(org.alfresco.rest.api.tests.client.data.Person) Test(org.junit.Test)

Aggregations

Person (org.alfresco.rest.api.tests.client.data.Person)30 RequestContext (org.alfresco.rest.api.tests.client.RequestContext)25 Test (org.junit.Test)24 PublicApiClient (org.alfresco.rest.api.tests.client.PublicApiClient)10 HashMap (java.util.HashMap)9 LinkedList (java.util.LinkedList)8 HttpResponse (org.alfresco.rest.api.tests.client.HttpResponse)8 NodeRef (org.alfresco.service.cmr.repository.NodeRef)7 ArrayList (java.util.ArrayList)6 PublicApiException (org.alfresco.rest.api.tests.client.PublicApiException)6 JSONObject (org.json.simple.JSONObject)6 Map (java.util.Map)5 TestNetwork (org.alfresco.rest.api.tests.RepoService.TestNetwork)5 Serializable (java.io.Serializable)4 List (java.util.List)4 Company (org.alfresco.rest.api.tests.client.data.Company)4 QName (org.alfresco.service.namespace.QName)4 Date (java.util.Date)3 Iterator (java.util.Iterator)3 MimeMessage (javax.mail.internet.MimeMessage)3