Search in sources :

Example 41 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class UserPostSelfRegistrationHandler method executeUserRegistrationWorkflow.

/**
 * This method adds new role to the existing user roles
 * @param tenantDomain tenant domain extracted from the event
 * @param userName username extracted from the event
 * @throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException when unable to retrieve
 * userStoreManager instance
 */
private void executeUserRegistrationWorkflow(String tenantDomain, String userName) throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException {
    try {
        // Realm service is used for user management tasks
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        UserStoreManager userStoreManager;
        try {
            userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getUserStoreManager();
        } catch (UserStoreException e) {
            throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
        }
        // Start a tenant flow
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
        carbonContext.setTenantDomain(tenantDomain);
        if (userStoreManager.isExistingUser(userName)) {
            List<String> roleList = asList(userStoreManager.getRoleListOfUser(userName));
            // User should have selfSignup role. Checking whether the user is in the new role
            if (roleList.contains(SELF_SIGNUP_ROLE) && !roleList.contains(SUBSCRIBER_ROLE)) {
                WorkflowExecutor userSignUpWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
                // initiate a new signup workflow
                WorkflowDTO signUpWFDto = new WorkflowDTO();
                signUpWFDto.setWorkflowReference(userName);
                signUpWFDto.setStatus(WorkflowStatus.CREATED);
                signUpWFDto.setCreatedTime(System.currentTimeMillis());
                signUpWFDto.setTenantDomain(tenantDomain);
                signUpWFDto.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
                signUpWFDto.setExternalWorkflowReference(userSignUpWFExecutor.generateUUID());
                signUpWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
                signUpWFDto.setCallbackUrl(userSignUpWFExecutor.getCallbackURL());
                userSignUpWFExecutor.execute(signUpWFDto);
            }
        }
    } catch (UserStoreException | WorkflowException e) {
        throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
    } finally {
        Utils.clearArbitraryProperties();
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) RealmService(org.wso2.carbon.user.core.service.RealmService) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 42 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIUtilTest method testGetListOfRolesNonSuperTenant.

@Test
public void testGetListOfRolesNonSuperTenant() throws Exception {
    int tenantID = 1;
    String username = "Kelso";
    String[] roles = { "PUBLISHER", "ADMIN", "TEST-ROLE" };
    String tenantDomain = "Insta.com";
    String tenantAwareUsername = "Insta_User";
    PowerMockito.spy(APIUtil.class);
    PowerMockito.doReturn(null).when(APIUtil.class, "getValueFromCache", APIConstants.API_USER_ROLE_CACHE, username);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(username)).thenReturn(tenantDomain);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Mockito.when(realmService.getTenantUserRealm(tenantID)).thenReturn(userRealm);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(MultitenantUtils.getTenantAwareUsername(username)).thenReturn(tenantAwareUsername);
    Mockito.when(userStoreManager.getRoleListOfUser(tenantAwareUsername)).thenReturn(roles);
    PowerMockito.doNothing().when(APIUtil.class, "addToRolesCache", Mockito.any(), Mockito.any(), Mockito.any());
    Assert.assertEquals(roles, APIUtil.getListOfRoles(username));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 43 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class UserSignUpSimpleWorkflowExecutorTest method testFailuresToCompleteUserSignUpSimpleWorkflow.

@Test
public void testFailuresToCompleteUserSignUpSimpleWorkflow() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setRoles(roleMap);
    workflowDTO.setTenantDomain(tenantDomain);
    PowerMockito.when(SelfSignUpUtil.class, "getSignupConfiguration", tenantDomain).thenReturn(userRegistrationConfigDTO);
    PowerMockito.when(SelfSignUpUtil.class, "getRoleNames", userRegistrationConfigDTO).thenReturn(Collections.singletonList("Internal/" + signUpRole));
    Mockito.when(userStoreManager.isExistingUser(username)).thenReturn(true);
    // Test failure to complete workflow execution, when sign up roles are not existing in user realm
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
    try {
        userSignUpSimpleWorkflowExecutor.execute(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when error has been occurred while retrieving signup config
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
    try {
        userSignUpSimpleWorkflowExecutor.execute(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown retrieving sign up configuration");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) SelfSignUpUtil(org.wso2.carbon.apimgt.impl.utils.SelfSignUpUtil) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 44 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIConsumerImpl method searchPaginatedAPIs.

@Override
public Map<String, Object> searchPaginatedAPIs(String searchQuery, String organization, int start, int end, String sortBy, String sortOrder) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    Organization org = new Organization(organization);
    String userName = (userNameWithoutChange != null) ? userNameWithoutChange : username;
    String[] roles = APIUtil.getListOfRoles(userName);
    Map<String, Object> properties = APIUtil.getUserProperties(userName);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        DevPortalAPISearchResult searchAPIs = apiPersistenceInstance.searchAPIsForDevPortal(org, searchQuery, start, end, userCtx);
        if (log.isDebugEnabled()) {
            log.debug("searched Devportal APIs for query : " + searchQuery + " :-->: " + searchAPIs.toString());
        }
        SortedSet<Object> apiSet = new TreeSet<>(new APIAPIProductNameComparator());
        if (searchAPIs != null) {
            List<DevPortalAPIInfo> list = searchAPIs.getDevPortalAPIInfoList();
            List<Object> apiList = new ArrayList<>();
            for (DevPortalAPIInfo devPortalAPIInfo : list) {
                API mappedAPI = APIMapper.INSTANCE.toApi(devPortalAPIInfo);
                mappedAPI.setRating(APIUtil.getAverageRating(mappedAPI.getUuid()));
                apiList.add(mappedAPI);
            }
            apiSet.addAll(apiList);
            result.put("apis", apiSet);
            result.put("length", searchAPIs.getTotalAPIsCount());
            result.put("isMore", true);
        } else {
            result.put("apis", apiSet);
            result.put("length", 0);
            result.put("isMore", false);
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching the api ", e);
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) DevPortalAPIInfo(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPIInfo) ArrayList(java.util.ArrayList) DevPortalAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPISearchResult) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) APIAPIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIAPIProductNameComparator)

Example 45 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIConsumerImpl method searchPaginatedContent.

@Override
public Map<String, Object> searchPaginatedContent(String searchQuery, String organization, int start, int end) throws APIManagementException {
    ArrayList<Object> compoundResult = new ArrayList<Object>();
    Map<Documentation, API> docMap = new HashMap<Documentation, API>();
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    int totalLength = 0;
    String userame = (userNameWithoutChange != null) ? userNameWithoutChange : username;
    Organization org = new Organization(organization);
    Map<String, Object> properties = APIUtil.getUserProperties(userame);
    String[] roles = APIUtil.getFilteredUserRoles(userame);
    ;
    UserContext ctx = new UserContext(userame, org, properties, roles);
    try {
        DevPortalContentSearchResult sResults = apiPersistenceInstance.searchContentForDevPortal(org, searchQuery, start, end, ctx);
        if (sResults != null) {
            List<SearchContent> resultList = sResults.getResults();
            for (SearchContent item : resultList) {
                if (item instanceof DocumentSearchContent) {
                    // doc item
                    DocumentSearchContent docItem = (DocumentSearchContent) item;
                    Documentation doc = new Documentation(DocumentationType.valueOf(docItem.getDocType().toString()), docItem.getName());
                    doc.setSourceType(DocumentSourceType.valueOf(docItem.getSourceType().toString()));
                    doc.setVisibility(DocumentVisibility.valueOf(docItem.getVisibility().toString()));
                    doc.setId(docItem.getId());
                    API api = new API(new APIIdentifier(docItem.getApiProvider(), docItem.getApiName(), docItem.getApiVersion()));
                    api.setUuid(docItem.getApiUUID());
                    docMap.put(doc, api);
                } else {
                    DevPortalSearchContent publiserAPI = (DevPortalSearchContent) item;
                    API api = new API(new APIIdentifier(publiserAPI.getProvider(), publiserAPI.getName(), publiserAPI.getVersion()));
                    api.setUuid(publiserAPI.getId());
                    api.setContext(publiserAPI.getContext());
                    api.setContextTemplate(publiserAPI.getContext());
                    api.setStatus(publiserAPI.getStatus());
                    // need to retrieve from db
                    api.setRating(0);
                    apiSet.add(api);
                }
            }
            compoundResult.addAll(apiSet);
            compoundResult.addAll(docMap.entrySet());
            compoundResult.sort(new ContentSearchResultNameComparator());
            result.put("length", sResults.getTotalCount());
        } else {
            result.put("length", compoundResult.size());
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching content ", e);
    }
    result.put("apis", compoundResult);
    return result;
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) ArrayList(java.util.ArrayList) DevPortalContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalContentSearchResult) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator)

Aggregations

ArrayList (java.util.ArrayList)72 HashMap (java.util.HashMap)60 Test (org.testng.annotations.Test)36 UserStoreException (org.wso2.carbon.user.api.UserStoreException)36 SQLException (java.sql.SQLException)27 HashSet (java.util.HashSet)26 Map (java.util.Map)25 Connection (java.sql.Connection)23 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)23 PreparedStatement (java.sql.PreparedStatement)21 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)20 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)18 JSONObject (org.json.simple.JSONObject)17 UserStoreException (org.wso2.carbon.user.core.UserStoreException)17 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)16 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)16 RealmService (org.wso2.carbon.user.core.service.RealmService)15 API (org.wso2.carbon.apimgt.core.models.API)14 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)14 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)14