Search in sources :

Example 1 with Users

use of org.wso2.ei.dashboard.core.rest.model.Users in project carbon-apimgt by wso2.

the class APIPublisherImpl method searchAPIs.

/**
 * @param limit  Limit
 * @param offset Offset
 * @param query  Search query
 * @return List of APIS.
 * @throws APIManagementException If failed to formatApiSearch APIs.
 */
@Override
public List<API> searchAPIs(Integer limit, Integer offset, String query) throws APIManagementException {
    List<API> apiResults;
    String user = getUsername();
    Set<String> roles = new HashSet<>();
    try {
        // TODO: Need to validate users roles against results returned
        if (!"admin".equals(user)) {
            // Whenever call identity provider should convert pseudo name to actual name
            String userId = getIdentityProvider().getIdOfUser(user);
            roles = new HashSet<>(getIdentityProvider().getRoleIdsOfUser(userId));
        }
        if (query != null && !query.isEmpty()) {
            String[] attributes = query.split(ATTRIBUTE_DELIMITER);
            Map<String, String> attributeMap = new HashMap<>();
            boolean isFullTextSearch = false;
            String searchAttribute, searchValue;
            if (!query.contains(KEY_VALUE_DELIMITER)) {
                isFullTextSearch = true;
            } else {
                log.debug("Search query: " + query);
                for (String attribute : attributes) {
                    searchAttribute = attribute.split(KEY_VALUE_DELIMITER)[0];
                    searchValue = attribute.split(KEY_VALUE_DELIMITER)[1];
                    log.debug(searchAttribute + KEY_VALUE_DELIMITER + searchValue);
                    attributeMap.put(searchAttribute, searchValue);
                }
            }
            if (isFullTextSearch) {
                apiResults = getApiDAO().searchAPIs(roles, user, query, offset, limit);
            } else {
                log.debug("Attributes:", attributeMap.toString());
                apiResults = getApiDAO().attributeSearchAPIs(roles, user, attributeMap, offset, limit);
            }
        } else {
            apiResults = getApiDAO().getAPIs(roles, user);
        }
        return apiResults;
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while Searching the API with query " + query;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (IdentityProviderException e) {
        String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + user + "'s information";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) HashSet(java.util.HashSet)

Example 2 with Users

use of org.wso2.ei.dashboard.core.rest.model.Users in project carbon-apimgt by wso2.

the class BrokerManager method loadUsers.

/**
 * Loads the users from users.yaml during broker startup
 */
private static void loadUsers() throws ConfigurationException {
    Path usersYamlFile;
    String usersFilePath = System.getProperty(BrokerSecurityConstants.SYSTEM_PARAM_USERS_CONFIG);
    if (usersFilePath == null || usersFilePath.trim().isEmpty()) {
        // use current path.
        usersYamlFile = Paths.get("", BrokerSecurityConstants.USERS_FILE_NAME).toAbsolutePath();
    } else {
        usersYamlFile = Paths.get(usersFilePath).toAbsolutePath();
    }
    ConfigProvider configProvider = ConfigProviderFactory.getConfigProvider(usersYamlFile, null);
    UsersFile usersFile = configProvider.getConfigurationObject(BrokerSecurityConstants.USERS_CONFIG_NAMESPACE, UsersFile.class);
    if (usersFile != null) {
        List<User> users = usersFile.getUsers();
        for (User user : users) {
            UserStoreManager.addUser(user);
        }
    }
}
Also used : Path(java.nio.file.Path) User(org.wso2.broker.core.security.authentication.user.User) BrokerConfigProvider(org.wso2.broker.common.BrokerConfigProvider) ConfigProvider(org.wso2.carbon.config.provider.ConfigProvider) UsersFile(org.wso2.broker.core.security.authentication.user.UsersFile)

Example 3 with Users

use of org.wso2.ei.dashboard.core.rest.model.Users in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetIdOfUser.

@Test
public void testGetIdOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user")).thenReturn("invalid_user");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("John")).thenReturn("John");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user_giving_null_response")).thenReturn("invalid_user_giving_null_response");
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserName = "John";
    final String validUserSearchQuery = "userName Eq " + validUserName;
    final String expectedUserId = "cfbde56e-8422-498e-b6dc-85a6f1f8b058";
    String invalidUserName = "invalid_user";
    final String invalidUserSearchQuery = "userName Eq " + invalidUserName;
    String userReturningNullResponse = "invalid_user_giving_null_response";
    final String userReturningNullResponseSearchQuery = "userName Eq " + userReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"id\":\"cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"userName\":\"John\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(validUserSearchQuery)).thenReturn(createdResponse);
    try {
        String userId = idpImpl.getIdOfUser(validUserName);
        Assert.assertEquals(userId, expectedUserId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the user cannot be found - When the request did not return a 200 OK response
    String errorResponse = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response createdResponseNoSuchUser = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponse.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(invalidUserSearchQuery)).thenReturn(createdResponseNoSuchUser);
    try {
        idpImpl.getIdOfUser(invalidUserName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + invalidUserName + ". Error : User not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchUsers(userReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getIdOfUser(userReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + userReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 4 with Users

use of org.wso2.ei.dashboard.core.rest.model.Users in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleIdsOfUser.

@Test
public void testGetRoleIdsOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleIds = new ArrayList<>();
    roleIds.add(roleId1);
    roleIds.add(roleId2);
    roleIds.add(roleId3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleIdsOfUser(validUserId);
    Assert.assertEquals(roleIds.size(), roles.size());
    roles.forEach(roleId -> Assert.assertTrue(roleIds.contains(roleId)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role Ids of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 5 with Users

use of org.wso2.ei.dashboard.core.rest.model.Users in project carbon-apimgt by wso2.

the class UserSignUpWorkflowExecutor method updateRolesOfUser.

/**
 * Method updates Roles users with list of roles
 *
 * @param userName
 * @param tenantDomain
 * @param roleList
 * @throws Exception
 */
protected static void updateRolesOfUser(String userName, List<String> roleList, String tenantDomain) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Adding roles to " + userName + "in " + tenantDomain + " Domain");
    }
    RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
    int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    UserStoreManager manager = realm.getUserStoreManager();
    if (manager.isExistingUser(userName)) {
        // check whether given roles exist
        for (String role : roleList) {
            if (!manager.isExistingRole(role)) {
                log.error("Could not find role " + role + " in the user store");
                throw new Exception("Could not find role " + role + " in the user store");
            }
        }
        manager.updateRoleListOfUser(userName, null, roleList.toArray(new String[0]));
    } else {
        log.error("User does not exist. Unable to approve user " + userName);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

ArrayList (java.util.ArrayList)42 Test (org.testng.annotations.Test)42 HashMap (java.util.HashMap)36 UserStoreException (org.wso2.carbon.user.api.UserStoreException)23 CharonException (org.wso2.charon3.core.exceptions.CharonException)19 UserStoreException (org.wso2.carbon.user.core.UserStoreException)15 Connection (java.sql.Connection)14 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)14 SQLException (java.sql.SQLException)13 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)13 FlaggedName (org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName)12 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)12 User (org.wso2.charon3.core.objects.User)12 SetEnvironment (org.wso2.carbon.automation.engine.annotations.SetEnvironment)11 RealmConfiguration (org.wso2.carbon.user.api.RealmConfiguration)10 ResultSet (java.sql.ResultSet)9 IdentityException (org.wso2.carbon.identity.base.IdentityException)9 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)9 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)9 ExtractableResponse (io.restassured.response.ExtractableResponse)7