org.wso2.carbon.user.api.UserStoreException Java Examples

The following examples show how to use org.wso2.carbon.user.api.UserStoreException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserIdentityManagementAdminService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * User change the password of the user.
 *
 * @param newPassword
 * @throws IdentityMgtServiceException
 */
public void changeUserPassword(String newPassword, String oldPassword) throws IdentityMgtServiceException {

    String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
        UserStoreManager userStoreManager = getUserStore(userName);
        userName = UserCoreUtil.removeDomainFromName(userName);
        userStoreManager.updateCredential(userName, newPassword, oldPassword);
        log.info("Password changed for: " + userName);
    } catch (UserStoreException e) {
        String message = "Error while resetting the password for: " + userName;
        log.error(message, e);
        throw new IdentityMgtServiceException(message, e);
    }
}
 
Example #2
Source File: IdentityProviderManagementService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @return
 * @throws IdentityProviderManagementException
 */
public String[] getAllLocalClaimUris() throws IdentityProviderManagementException {

    try {
        String claimDialect = LOCAL_DEFAULT_CLAIM_DIALECT;
        ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext()
                .getUserRealm().getClaimManager().getAllClaimMappings(claimDialect);
        List<String> claimUris = new ArrayList<String>();
        for (ClaimMapping claimMap : claimMappings) {
            claimUris.add(claimMap.getClaim().getClaimUri());
        }
        String[] allLocalClaimUris = claimUris.toArray(new String[claimUris.size()]);
        if (ArrayUtils.isNotEmpty(allLocalClaimUris)) {
            Arrays.sort(allLocalClaimUris);
        }
        return allLocalClaimUris;
    } catch (UserStoreException e) {
        String message = "Error while reading system claims";
        log.error(message, e);
        throw new IdentityProviderManagementException(message, e);
    }
}
 
Example #3
Source File: StratosUserManagerUtils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Get the List of userRoles except the Internal/everyone role
 *
 * @param userStoreManager UserStoreManager
 * @param username         Username of the user
 * @return String[]
 * @throws UserManagerException
 */
private static String[] getRefinedListOfRolesOfUser(UserStoreManager userStoreManager, String username)
        throws UserManagerException {

    ArrayList<String> rolesWithoutEveryoneRole = new ArrayList<String>();

    try {
        String[] allUserRoles = userStoreManager.getRoleListOfUser(username);

        for (String role : allUserRoles) {
            if (!role.equals(INTERNAL_EVERYONE_ROLE)) {
                rolesWithoutEveryoneRole.add(role);
            }
        }
        String[] rolesWithoutEveryoneRoleArray = new String[rolesWithoutEveryoneRole.size()];
        return rolesWithoutEveryoneRole.toArray(rolesWithoutEveryoneRoleArray);

    } catch (UserStoreException e) {
        String msg = "Error in listing the roles of user " + username + " in User Store";
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }
}
 
Example #4
Source File: OAuthService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the OAuth request token for the given scope. In order for the Consumer to be able
 * to exchange the Request Token for an Access Token, the Consumer MUST obtain approval from the
 * User by directing the User to the Service Provider. The Consumer constructs an HTTP GET
 * request to the Service Provider's User Authorization URL with the following parameters.
 *
 * @param params             A container for the following attributes.
 * @param params:oauth_token (required) : Request token obtained from WSO2.
 * @param params:userName    : User who authorizes the token.
 * @param params:password    : Password of the user who authorizes the token.
 * @return oauth_token, oauth_verifier
 * @throws Exception
 */
public Parameters authorizeOauthRequestToken(Parameters params) throws IdentityException, AuthenticationException {
    String tenantUser = MultitenantUtils.getTenantAwareUsername(params.getAuthorizedbyUserName());
    String domainName = MultitenantUtils.getTenantDomain(params.getAuthorizedbyUserName());
    boolean isAuthenticated = false;
    try {
        isAuthenticated = IdentityTenantUtil
                .getRealm(domainName, params.getAuthorizedbyUserName()).getUserStoreManager()
                .authenticate(tenantUser, params.getAuthorizedbyUserPassword());
    } catch (UserStoreException e) {
        log.error("Error while authenticating the user", e);
        throw IdentityException.error("Error while authenticating the user");
    }
    if (isAuthenticated) {
        OAuthConsumerDAO dao = new OAuthConsumerDAO();
        String oauthVerifier = org.wso2.carbon.identity.oauth.OAuthUtil.getRandomNumber();
        Parameters token = dao.authorizeOAuthToken(params.getOauthToken(), tenantUser,
                oauthVerifier);
        token.setOauthToken(params.getOauthToken());
        token.setOauthTokenVerifier(oauthVerifier);
        return token;
    } else {
        throw new AuthenticationException("User Authentication Failed");
    }
}
 
Example #5
Source File: UserStoreCountService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private long getRoleCount(String filter) throws UserStoreCounterException {

        try {
            UserStoreManager userStoreManager = getUserStoreManager();
            if (!(userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager)) {
                if (log.isDebugEnabled()) {
                    log.debug(" Cannot get role count. Provided user store manager : "
                            + userStoreManager.getClass() + ", is not not an instance of : "
                            + org.wso2.carbon.user.core.UserStoreManager.class);
                }
                throw new UserStoreCounterException("Unsupported user store manager to retrieve role count");
            }
            return ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).countRoles(filter);
        } catch (UserStoreException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while retrieving role count with tenent Id " + tenantId + ", and the filter "
                        + filter);
            }
            String errorMsg = "Error occurred while retrieving role count";
            throw new UserStoreCounterException(errorMsg, e);
        }
    }
 
Example #6
Source File: DefaultRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method retrieves requested claim value from the user store
 *
 * @param username
 * @param userStoreManager
 * @param claimURI
 * @return claim value as a String
 * @throws FrameworkException
 */
private String getClaimValue(String username, UserStoreManager userStoreManager, String claimURI) throws
        FrameworkException {

    try {
        Map<String, String> values = userStoreManager.getUserClaimValues(username, new String[]{claimURI},
                UserCoreConstants.DEFAULT_PROFILE);
        if (log.isDebugEnabled()) {
            log.debug(String.format("%s claim value of user %s is set to: " + values.get(claimURI),
                    claimURI, username));
        }
        return values.get(claimURI);

    } catch (UserStoreException e) {
        throw new FrameworkException("Error occurred while retrieving claim: " + claimURI, e);
    }
}
 
Example #7
Source File: JsClaims.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a local claim directly at the userstore for the given user by given claim uri
 *
 * @param claimUri   Local claim URI
 * @param claimValue Claim value
 */
private void setLocalUserClaim(String claimUri, Object claimValue) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimUriMap = new HashMap<>();
        claimUriMap.put(claimUri, String.valueOf(claimValue));
        userRealm.getUserStoreManager().setUserClaimValues(usernameWithDomain, claimUriMap, null);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when setting claim : %s of user: %s to value: %s", claimUri,
                authenticatedUser, String.valueOf(claimValue)), e);
    }
}
 
Example #8
Source File: TestUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static void mockAPIMConfiguration() throws RegistryException,
        UserStoreException {
    ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);

    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);

    Map<String, Environment> apiGatewayEnvironments = new HashMap<String, Environment>();
    Environment env1 = new Environment();
    env1.setApiGatewayEndpoint("https://abc.com, http://abc.com");
    apiGatewayEnvironments.put("PROD", env1);
    // Mocking some commonly used configs
    PowerMockito.when(amConfig.getApiGatewayEnvironments()).thenReturn(apiGatewayEnvironments);
    PowerMockito.when(amConfig.getFirstProperty(APIConstants.API_GATEWAY_TYPE)).thenReturn(
            APIConstants.API_GATEWAY_TYPE_SYNAPSE);
    PowerMockito.when(amConfig.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS)).
            thenReturn("true", "false");

    ThrottleProperties throttleProperties = new ThrottleProperties();
    PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);

}
 
Example #9
Source File: DatabaseBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void doAddUserStore(UserStorePersistanceDTO userStorePersistanceDTO) throws
        IdentityUserStoreMgtException {

    String domainName = userStorePersistanceDTO.getUserStoreDTO().getDomainId();
    try {
        // Run pre user-store add listeners.
        triggerListenersOnUserStorePreAdd(domainName);
        boolean isValidDomain = xmlProcessorUtils.isValidDomain(domainName, true);
        validateForFederatedDomain(domainName);
        if (isValidDomain) {
            addUserStoreProperties(userStorePersistanceDTO.getUserStoreProperties(), domainName);
            addRealmToSecondaryUserStoreManager(userStorePersistanceDTO);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("The user store domain: " + domainName + "is not a valid domain name.");
            }
        }
    } catch (UserStoreException | XMLStreamException e) {
        throw new IdentityUserStoreMgtException("Error occured while adding the user store with the domain: " +
                domainName, e);
    }
}
 
Example #10
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store in which the user is in.
 *
 * @param username Full qualified username
 * @return
 */
public static boolean isUserStoreInUsernameCaseSensitive(String username) {

    boolean isUsernameCaseSensitive = true;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = IdentityTenantUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
        return isUserStoreInUsernameCaseSensitive(username, tenantId);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example #11
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyFailedDueToOMException()
        throws UserStoreException, RegistryException, XMLStreamException {
    Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
    PowerMockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(tenantID)).thenReturn(registry);
    PowerMockito.when(registry.resourceExists(RESOURCE_PATH)).thenReturn(true);
    PowerMockito.when(registry.get(RESOURCE_PATH)).thenReturn(throttlingPolicyResource);
    PowerMockito.when(throttlingPolicyResource.getContent()).thenReturn(THROTTLING_POLICY_DEFINITION.getBytes());
    PowerMockito.mockStatic(XMLInputFactory.class);
    XMLInputFactory factory = Mockito.mock(XMLInputFactory.class);
    PowerMockito.when(XMLInputFactory.newInstance()).thenReturn(factory);
    PowerMockito.doThrow(new OMException()).when(factory).createXMLStreamReader((ByteArrayInputStream)
            Mockito.anyObject());
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder,
            applicationId, THROTTLE_POLICY_KEY);
}
 
Example #12
Source File: UserStoreConfigServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void addUserStore(UserStoreDTO userStoreDTO) throws IdentityUserStoreMgtException {

    try {
        if (SecondaryUserStoreConfigurationUtil.isUserStoreRepositorySeparationEnabled() &&
                StringUtils.isNotBlank(userStoreDTO.getRepositoryClass())) {
            AbstractUserStoreDAOFactory userStoreDAOFactory = UserStoreConfigListenersHolder.
                    getInstance().getUserStoreDAOFactories().get(userStoreDTO.getRepositoryClass());
            userStoreDAOFactory.getInstance().addUserStore(userStoreDTO);
        } else {
            if (StringUtils.isNotBlank(userStoreDTO.getRepositoryClass())) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Repository separation of user-stores has been disabled. Adding user-store " +
                              userStoreDTO.getDomainId() + " with file-based configuration.");
                }
            }
            SecondaryUserStoreConfigurationUtil.getFileBasedUserStoreDAOFactory().addUserStore(userStoreDTO);
        }
    } catch (UserStoreException e) {
        String errorMessage = e.getMessage();
        throw new IdentityUserStoreMgtException(errorMessage, e);
    }
}
 
Example #13
Source File: DefaultClaimsRetriever.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getDefaultClaims(String endUserName) throws IdentityOAuth2Exception {

    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    try {
        tenantId = OAuth2Util.getTenantIdFromUserName(endUserName);
        // if no claims were requested, return all
        if(log.isDebugEnabled()){
            log.debug("No claims set requested. Returning all claims in the dialect");
        }
        ClaimManager claimManager =
                OAuthComponentServiceHolder.getRealmService().getTenantUserRealm(tenantId).getClaimManager();
        ClaimMapping[] claims = claimManager.getAllClaimMappings(dialectURI);
        return claimToString(claims);
    } catch (UserStoreException e) {
        throw new IdentityOAuth2Exception("Error while reading default claims for user : " + endUserName, e);
    }
}
 
Example #14
Source File: DeviceManagementProviderServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
        DeviceManagementException.class)
public void testGetAllDevicesOfRoleFailureFlow() throws DeviceManagementException, UserStoreException, NoSuchFieldException, IllegalAccessException {
    int tenantID = -1234;
    RealmService mockRealmService = Mockito.mock(RealmService.class, Mockito.CALLS_REAL_METHODS);

    Mockito.doThrow(new UserStoreException("Mocked Exception when obtaining Tenant Realm"))
            .when(mockRealmService).getTenantUserRealm(tenantID);
    RealmService currentRealm = DeviceManagementDataHolder.getInstance().getRealmService();
    DeviceManagementDataHolder.getInstance().setRealmService(mockRealmService);
    try {
        deviceMgtService.getAllDevicesOfRole("admin");
    } finally {
        DeviceManagementDataHolder.getInstance().setRealmService(currentRealm);
    }
}
 
Example #15
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Method to migrate encrypted password of SYSLOG_PROPERTIES registry resource
 *
 * @param migrateActiveTenantsOnly
 * @throws UserStoreException user store exception
 */
public void migrateSysLogPropertyPassword(boolean migrateActiveTenantsOnly)
        throws UserStoreException, RegistryException, CryptoException {
    try {
        //migrating super tenant configurations
        migrateSysLogPropertyPasswordForTenant(SUPER_TENANT_ID);
        log.info("Sys log property password migrated for tenant : " + SUPER_TENANT_DOMAIN_NAME);
    } catch (Exception e) {
        log.error("Error while migrating Sys log property password for tenant : " + SUPER_TENANT_DOMAIN_NAME, e);
    }
    Tenant[] tenants = MigrationServiceDataHolder.getRealmService().getTenantManager().getAllTenants();
    for (Tenant tenant : tenants) {
        if (migrateActiveTenantsOnly && !tenant.isActive()) {
            log.info("Tenant " + tenant.getDomain() + " is inactive. Skipping SYSLOG_PROPERTIES file migration. ");
            continue;
        }
        try {
            migrateSysLogPropertyPasswordForTenant(tenant.getId());
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
 
Example #16
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getMultiAttributeSeparator(String authenticatedUser, int tenantId) {
    String claimSeparator = null;
    String userDomain = IdentityUtil.extractDomainFromName(authenticatedUser);

    try {
        RealmConfiguration realmConfiguration = null;
        RealmService realmService = OAuthComponentServiceHolder.getRealmService();

        if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
            UserStoreManager userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId)
                    .getUserStoreManager();
            realmConfiguration = userStoreManager.getSecondaryUserStoreManager(userDomain).getRealmConfiguration();
        }

        if (realmConfiguration != null) {
            claimSeparator = realmConfiguration.getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
            if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                return claimSeparator;
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while getting the realm configuration, User store properties might not be " +
                  "returned", e);
    }
    return null;
}
 
Example #17
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger the listeners before userstore domain delete
 * @param domainName user store domain name
 * @throws UserStoreException throws when an error occured when triggering listeners.
 */
public static void triggerListnersOnUserStorePreDelete(String domainName) throws UserStoreException {

    List<UserStoreConfigListener> userStoreConfigListeners = UserStoreConfigListenersHolder.getInstance()
            .getUserStoreConfigListeners();
    for (UserStoreConfigListener userStoreConfigListener : userStoreConfigListeners) {
        userStoreConfigListener.onUserStorePreDelete(CarbonContext.getThreadLocalCarbonContext().getTenantId
                (), domainName);
    }
}
 
Example #18
Source File: MigrateData.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the list of tenants.
 *
 * @return list of tenants
 * @throws UserStoreException
 */
private List<Tenant> getTenantsArray() throws UserStoreException {
    TenantManager tenantManager = ServiceHolder.getRealmService().getTenantManager();
    List<Tenant> tenantsArray = new ArrayList<Tenant>(Arrays.asList(tenantManager.getAllTenants()));
    Tenant superTenant = new Tenant();
    superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    superTenant.setId(MultitenantConstants.SUPER_TENANT_ID);
    tenantsArray.add(superTenant);
    return tenantsArray;
}
 
Example #19
Source File: DeleteRoleWFRequestHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for delete role received without the mandatory " +
                "parameter 'username'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteRole(roleName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting role is aborted for role '" + roleName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example #20
Source File: GeoLocationBasedServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Path("alerts/history")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getGeoAlertsHistoryForGeoClusters(@QueryParam("from") long from, @QueryParam("to") long to) {
    String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS";
    String fromDate = String.valueOf(from);
    String toDate = String.valueOf(to);
    String query = "";
    if (from != 0 || to != 0) {
        query = "timeStamp : [" + fromDate + " TO " + toDate + "]";
    }
    try {
        List<SortByField> sortByFields = new ArrayList<>();
        SortByField sortByField = new SortByField("timeStamp", SortType.ASC);
        sortByFields.add(sortByField);

        // this is the user who initiates the request
        String authorizedUser = MultitenantUtils.getTenantAwareUsername(
                CarbonContext.getThreadLocalCarbonContext().getUsername());

        String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
        int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
        AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
        List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
                0,
                100,
                sortByFields);
        List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
                searchResults);
        return Response.ok().entity(events).build();

    } catch (AnalyticsException | UserStoreException e) {
        log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);
        throw DeviceMgtUtil.buildBadRequestException(
                Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT);
    }
}
 
Example #21
Source File: StandaloneAuthorizationManagerClient.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getRolesOfUser(String user) throws APIManagementException {
    try {
        return userStoreManager.getRoleListOfUser(user);
    } catch (UserStoreException e) {
        throw new APIManagementException("Error occurred while retrieving the role list of user '" +
                user + "'", e);
    }
}
 
Example #22
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{username}/roles")
@Override
public Response getRolesOfUser(@PathParam("username") String username, @QueryParam("domain") String domain) {
    if (domain != null && !domain.isEmpty()) {
        username = domain + '/' + username;
    }
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (!userStoreManager.isExistingUser(username)) {
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + username + " does not exist for role retrieval.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username +
                            " does not exist for role retrieval.").build()).build();
        }

        RoleList result = new RoleList();
        result.setList(getFilteredRoles(userStoreManager, username));
        return Response.status(Response.Status.OK).entity(result).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while trying to retrieve roles of the user '" + username + "'";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example #23
Source File: StandaloneAuthorizationManagerClient.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public StandaloneAuthorizationManagerClient() {
    try {
        this.userStoreManager = ServiceReferenceHolder.getUserRealm().getUserStoreManager();
        this.authorizationManager = ServiceReferenceHolder.getUserRealm().getAuthorizationManager();
    } catch (UserStoreException e) {
        throw new IllegalStateException("Error occurred while initializing Standalone " +
                "Authorization Manager Client", e);
    }
}
 
Example #24
Source File: JDBCIdentityDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException {

    super.remove(userName, userStoreManager);
    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).
            getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    try {
        int tenantId = userStoreManager.getTenantId();
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        String query;
        if (isUsernameCaseSensitive) {
            query = SQLQuery.DELETE_USER_DATA;
        } else {
            query = SQLQuery.DELETE_USER_DATA_CASE_INSENSITIVE;
        }
        prepStmt = connection.prepareStatement(query);
        prepStmt.setInt(1, tenantId);
        prepStmt.setString(2, userName);
        prepStmt.execute();
        IdentityDatabaseUtil.commitTransaction(connection);
    } catch (SQLException | UserStoreException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        throw IdentityException.error("Error while reading user identity data", e);
    } finally {
        IdentityDatabaseUtil.closeStatement(prepStmt);
        IdentityDatabaseUtil.closeConnection(connection);
    }
}
 
Example #25
Source File: APIPublisherUtilTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "test buildAPIConfig method and ensures an APIConfig is created")
public void buildApiConfigTest() throws UserStoreException, RegistryException {
    try {
        startTenantFlowAsTestTenant();
        ServletContext servletContext = new MockServletContext();
        APIResourceConfiguration apiDef = new APIResourceConfiguration();
        List<APIResource> resources = new ArrayList<>();
        apiDef.setResources(resources);
        APIConfig apiConfig = buildApiConfig(servletContext, apiDef);
        Assert.assertNotNull(apiConfig, "API configuration is null.");
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #26
Source File: FileBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void deletePersitedDomain(int tenantId, String domainName) throws UserStoreException {

        // Delete persisted domain name
        AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) CarbonContext.
                getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        userStoreManager.deletePersistedDomain(domainName);
        if (log.isDebugEnabled()) {
            log.debug("Removed persisted domain name: " + domainName + " of tenant:" + tenantId + " from " +
                    "UM_DOMAIN.");
        }
        //clear cache to make the modification effective
        UserCoreUtil.getRealmService().clearCachedUserRealm(tenantId);
        TenantCache.getInstance().clearCacheEntry(new TenantIdKey(tenantId));
    }
 
Example #27
Source File: ActivityProviderServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private Response validateAdminUser(){
    try {
        if (!DeviceMgtAPIUtils.isAdmin()) {
            return Response.status(Response.Status.UNAUTHORIZED).entity("Unauthorized operation! Only admin role can perform " +
                    "this operation.").build();
        }
        return null;
    } catch (UserStoreException e) {
        String msg
                = "Error occurred while validating the user have admin role!";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example #28
Source File: DeviceAccessAuthorizationServiceTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "Authorization by giving a device identifier, username and permission Allowed test case")
public void userAuthDevIdUserNamePermission() throws DeviceAccessAuthorizationException, UserStoreException,
        PermissionManagementException {
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
    Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(0), NON_ADMIN_ALLOWED_USER,
            new String[]{NON_ADMIN_PERMISSION}), "Non admin user with permissions attempt to access failed");
}
 
Example #29
Source File: CacheBackedLocalClaimDAO.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Remove attribute claim mappings related to tenant id and domain.
 *
 * @param tenantId        Tenant Id
 * @param userstoreDomain Domain name
 * @throws UserStoreException If an error occurred while removing local claims
 */
public void removeClaimMappingAttributes(int tenantId, String userstoreDomain) throws UserStoreException {

    if (StringUtils.isEmpty(userstoreDomain)) {
        String message = ClaimConstants.ErrorMessage.ERROR_CODE_EMPTY_TENANT_DOMAIN.getMessage();
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
        throw new UserStoreException(message);
    }
    localClaimDAO.deleteClaimMappingAttributes(tenantId, userstoreDomain);
    localClaimInvalidationCache.clearCacheEntry(tenantId);
}
 
Example #30
Source File: TestUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static ServiceReferenceHolder mockRegistryAndUserRealm(int tenantId) throws UserStoreException, 
                                                                                                RegistryException {
    ServiceReferenceHolder sh = getServiceReferenceHolder();
    
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tm = Mockito.mock(TenantManager.class);
    
    PowerMockito.when(sh.getRealmService()).thenReturn(realmService);
    PowerMockito.when(realmService.getTenantManager()).thenReturn(tm);
    
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    
    UserRegistry userReg = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceUserRegistry()).thenReturn(userReg);
    
    UserRegistry systemReg = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getConfigSystemRegistry()).thenReturn(systemReg);
    
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserRealm bootstrapRealm = Mockito.mock(UserRealm.class);
    
    PowerMockito.when(systemReg.getUserRealm()).thenReturn(userRealm);        
    PowerMockito.doNothing().when(ServiceReferenceHolder.class); 
    ServiceReferenceHolder.setUserRealm(userRealm);
    org.wso2.carbon.user.api.UserRealm userR = Mockito.mock(org.wso2.carbon.user.api.UserRealm.class);
    PowerMockito.when(realmService.getTenantUserRealm(-1234)).thenReturn(userR);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    PowerMockito.when(userR.getAuthorizationManager()).thenReturn(authManager);
    PowerMockito.when(realmService.getBootstrapRealm()).thenReturn(bootstrapRealm);
    ServiceReferenceHolder.setUserRealm(bootstrapRealm);

    PowerMockito.when(tm.getTenantId(Matchers.anyString())).thenReturn(tenantId);

    return sh;
}