Search in sources :

Example 26 with User

use of org.wso2.carbon.identity.application.common.model.xsd.User 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 27 with User

use of org.wso2.carbon.identity.application.common.model.xsd.User in project carbon-apimgt by wso2.

the class APIExecutor method execute.

/**
 * This method will be called when the invoke() method of the default lifecycle implementation is called.
 * Execution logic should reside in this method since the default lifecycle implementation will determine
 * the execution output by looking at the output of this method.
 *
 * @param resource     The resource in which the lifecycle state is changed.
 * @param currentState Current lifecycle state.
 * @param targetState  The target lifecycle state.
 * @throws LifecycleException If exception occurs while running the executor.
 */
@Override
public void execute(Object resource, String currentState, String targetState) throws LifecycleException {
    API api = (API) resource;
    if (!currentState.equals(targetState)) {
        // todo:This place need to write how to handle Gateway publishing
        try {
            ApiDAO apiDAO = DAOFactory.getApiDAO();
            apiDAO.changeLifeCycleStatus(api.getId(), targetState);
        } catch (APIMgtDAOException e) {
            throw new LifecycleException("Couldn't create APIPublisher from user", e);
        }
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) API(org.wso2.carbon.apimgt.core.models.API) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO)

Example 28 with User

use of org.wso2.carbon.identity.application.common.model.xsd.User 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 29 with User

use of org.wso2.carbon.identity.application.common.model.xsd.User in project carbon-apimgt by wso2.

the class RestCallUtilImpl method rsaSignedFetchUserRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse rsaSignedFetchUserRequest(URI uri, String username, String userTenantDomain, String rsaSignedToken, MediaType acceptContentType) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("UserName must not be null");
    }
    if (userTenantDomain == null) {
        throw new IllegalArgumentException("User tenant domain must not be null");
    }
    if (rsaSignedToken == null) {
        throw new IllegalArgumentException("RSA signed token must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        JSONObject loginInfoJsonObj = new JSONObject();
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USER_TENANT_DOMAIN, userTenantDomain);
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.POST);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.RSA_SIGNED_TOKEN, rsaSignedToken);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(loginInfoJsonObj.toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 30 with User

use of org.wso2.carbon.identity.application.common.model.xsd.User in project carbon-apimgt by wso2.

the class ApiDAOImplIT method testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD.

@Test(description = "Tests getting the APIs when the user roles are contained in the API permission list " + "but without READ permissions")
public void testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    Set<String> rolesOfUser = new HashSet<>();
    rolesOfUser.add(SampleTestObjectCreator.DEVELOPER_ROLE_ID);
    // This user is not the provider of the API
    List<API> apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
    Assert.assertTrue(apiList.isEmpty());
    Map map = new HashMap();
    map.put(SampleTestObjectCreator.DEVELOPER_ROLE_ID, 0);
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI().permissionMap(map);
    API api1 = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api1);
    apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
    // Since the API has the role ID of the user but without READ permissions, it is not visible to this user
    Assert.assertTrue(apiList.size() == 0);
}
Also used : HashMap(java.util.HashMap) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)423 ArrayList (java.util.ArrayList)323 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)322 HashMap (java.util.HashMap)311 UserStoreException (org.wso2.carbon.user.api.UserStoreException)286 Test (org.junit.Test)272 Response (javax.ws.rs.core.Response)233 SQLException (java.sql.SQLException)166 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)158 PreparedStatement (java.sql.PreparedStatement)151 Connection (java.sql.Connection)148 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)134 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)130 Map (java.util.Map)115 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)114 User (org.wso2.charon3.core.objects.User)114 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)112 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)105 Request (org.wso2.msf4j.Request)105 UserStoreException (org.wso2.carbon.user.core.UserStoreException)103