org.wso2.carbon.identity.core.util.IdentityTenantUtil Java Examples

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityTenantUtil. 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: OpenIDRememberMeTokenCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the RememberMe token from cache
 *
 * @param rememberMe
 * @return <code>OpenIDRememberMeDO</code>
 * @throws IdentityProviderException
 */
public synchronized OpenIDRememberMeDO getTokenData(OpenIDRememberMeDO rememberMe)
        throws IdentityProviderException {

    String username = rememberMe.getUserName();
    int tenantId = IdentityTenantUtil.getTenantIdOfUser(rememberMe.getUserName());
    if (log.isDebugEnabled()) {
        log.debug("Loading RememberMe token in cache for " + username + " with tenant ID " + tenantId);
    }
    OpenIDIdentityCacheKey key = new OpenIDIdentityCacheKey(tenantId, username);
    OpenIDIdentityCacheEntry entry = rememberMeCache.getValueFromCache(key);
    if (entry == null) {
        return null;
    }
    rememberMe.setToken(entry.getCacheEntry());
    Timestamp timestamp = new Timestamp(entry.getDate().getTime());
    rememberMe.setTimestamp(timestamp);

    return rememberMe;
}
 
Example #2
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @return
 * @throws OAuthSystemException
 */
public synchronized boolean hasUserApproved(AuthenticatedUser user, String appName, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    OpenIDUserRPDO rpDO;
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    rpDO = dao.getOpenIDUserRP(user.getAuthenticatedSubjectIdentifier(), appName, tenantId);
    if (rpDO != null && rpDO.isTrustedAlways()) {
        return true;
    }

    return false;
}
 
Example #3
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @throws OAuthSystemException
 */
public void putUserRPToStore(AuthenticatedUser user, String appName, boolean trustedAlways, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDO repDO = new OpenIDUserRPDO();
    repDO.setDefaultProfileName(DEFAULT_PROFILE_NAME);
    repDO.setRpUrl(appName);
    repDO.setUserName(user.getAuthenticatedSubjectIdentifier());
    repDO.setTrustedAlways(trustedAlways);
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    dao.createOrUpdate(repDO, tenantId);
}
 
Example #4
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example #5
Source File: LoginContextManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private static String getTenantDomain(HttpServletRequest request) {

        String tenantDomain;
        if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("Tenant Qualified URL mode enabled. Retrieving tenantDomain from thread local context.");
            }
            tenantDomain = IdentityTenantUtil.getTenantDomainFromContext();
        } else {
            tenantDomain = request.getParameter("tenantDomain");
        }

        if (log.isDebugEnabled()) {
            log.debug("Service Provider tenant domain: " + tenantDomain);
        }
        return tenantDomain;
    }
 
Example #6
Source File: DefaultRequestCoordinatorTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "tenantDomainProvider")
public void testTenantDomainInAuthenticationContext(boolean isTenantQualifiedUrlModeEnabled,
                                                    String tenantDomainInThreadLocal,
                                                    String tenantDomainInRequestParam,
                                                    String expected) throws Exception {

    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlModeEnabled);
    when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantDomainInThreadLocal);

    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getParameter(TYPE)).thenReturn("oauth");
    when(request.getParameter(LOGOUT)).thenReturn("true");
    when(request.getParameter(TENANT_DOMAIN)).thenReturn(tenantDomainInRequestParam);

    HttpServletResponse response = mock(HttpServletResponse.class);

    AuthenticationContext context = requestCoordinator.initializeFlow(request, response);

    assertEquals(context.getTenantDomain(), expected);
}
 
Example #7
Source File: DefaultRequestPathBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "spRoleMappingDataProvider")
public void testGetServiceProviderMappedUserRoles(Map<String, String> spRoleMappings,
                                                  List<String> localUserRoles,
                                                  String multiAttributeSeparator,
                                                  String expectedRoles) throws Exception {
    Util.mockMultiAttributeSeparator(multiAttributeSeparator);
    SequenceConfig sequenceConfig = Util.mockSequenceConfig(spRoleMappings);
    mockStatic(ApplicationMgtSystemConfig.class);
    mockStatic(IdentityTenantUtil.class);
    when(ApplicationMgtSystemConfig.getInstance()).thenReturn(applicationMgtSystemConfig);
    when(applicationMgtSystemConfig.getApplicationDAO()).thenReturn(applicationDAO);
    when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService);
    when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockRealmConfiguration);
    String mappedRoles = requestPathBasedSequenceHandler.getServiceProviderMappedUserRoles(sequenceConfig, localUserRoles);
    assertEquals(mappedRoles, expectedRoles);
}
 
Example #8
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "spRoleMappingDataProvider")
public void testGetServiceProviderMappedUserRoles(Map<String, String> spRoleMappings,
                                                  List<String> localUserRoles,
                                                  String multiAttributeSeparator,
                                                  String expectedRoles) throws Exception {
    Util.mockMultiAttributeSeparator(multiAttributeSeparator);
    mockStatic(ApplicationMgtSystemConfig.class);
    mockStatic(IdentityTenantUtil.class);
    when(ApplicationMgtSystemConfig.getInstance()).thenReturn(applicationMgtSystemConfig);
    when(applicationMgtSystemConfig.getApplicationDAO()).thenReturn(applicationDAO);
    when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService);
    when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockRealmConfiguration);
    SequenceConfig sequenceConfig = Util.mockSequenceConfig(spRoleMappings);
    String mappedRoles = stepBasedSequenceHandler.getServiceProviderMappedUserRoles(sequenceConfig, localUserRoles);
    assertEquals(mappedRoles, expectedRoles, "Service Provider Mapped Role do not have the expect value.");
}
 
Example #9
Source File: IdentityProviderManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param idPName
 * @param tenantDomain
 * @param ignoreFileBasedIdps
 * @return
 * @throws IdentityProviderManagementException
 */
public IdentityProvider getIdPByName(String idPName, String tenantDomain,
                                     boolean ignoreFileBasedIdps) throws IdentityProviderManagementException {

    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
    if (StringUtils.isEmpty(idPName)) {
        String msg = "Invalid argument: Identity Provider Name value is empty";
        throw new IdentityProviderManagementException(msg);
    }

    IdentityProvider identityProvider = dao.getIdPByName(null, idPName, tenantId, tenantDomain);

    if (!ignoreFileBasedIdps) {

        if (identityProvider == null) {
            identityProvider = new FileBasedIdPMgtDAO().getIdPByName(idPName, tenantDomain);
        }

        if (identityProvider == null) {
            identityProvider = IdPManagementServiceComponent.getFileBasedIdPs().get(
                    IdentityApplicationConstants.DEFAULT_IDP_CONFIG);
        }
    }

    return identityProvider;
}
 
Example #10
Source File: PolicySearchCacheInvalidationClusteringMessage.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ConfigurationContext configurationContext) throws ClusteringFault {

    if (log.isDebugEnabled()) {
        log.debug("Received PolicySearchCacheInvalidationClusteringMessage.");
    }
    // We need to clear our local policy search cache of the corresponding tenant based on the received cluster
    // message from other node.
    int tenantIdInThreadLocalContext = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try{
        // Clear local cache for the tenant domain included with the cluster message.
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);

        EntitlementEngine.getInstance().getPolicySearch().getPolicySearchCache().clearCache();
        if (log.isDebugEnabled()) {
            log.debug("Local policy search cache is cleared for the tenant: "
                    + IdentityTenantUtil.getTenantDomain(tenantId) + ".");
        }
    } finally {
        // Switch back to the original tenant domain used in this thread local context.
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInThreadLocalContext, true);
    }
}
 
Example #11
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath");
    APIManagerConfiguration config = new APIManagerConfiguration();
    initializeDatabase(dbConfigPath);
    config.load(dbConfigPath);
    ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(new APIManagerConfigurationServiceImpl
            (config));
    List<Notifier> notifierList = new ArrayList<>();
    SubscriptionsNotifier subscriptionsNotifier = new SubscriptionsNotifier();
    notifierList.add(subscriptionsNotifier);
    ServiceReferenceHolder.getInstance().getNotifiersMap().put(subscriptionsNotifier.getType(), notifierList);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    keyManager = Mockito.mock(KeyManager.class);
    APIMgtDBUtil.initialize();
    apiMgtDAO = ApiMgtDAO.getInstance();
    IdentityTenantUtil.setRealmService(new TestRealmService());
    String identityConfigPath = System.getProperty("IdentityConfigurationPath");
    IdentityConfigParser.getInstance(identityConfigPath);
    OAuthServerConfiguration oAuthServerConfiguration = OAuthServerConfiguration.getInstance();
    ServiceReferenceHolder.getInstance().setOauthServerConfiguration(oAuthServerConfiguration);

}
 
Example #12
Source File: ClaimMetadataManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void removeClaimDialect(ClaimDialect claimDialect, String tenantDomain) throws ClaimMetadataException {

    if (claimDialect == null || StringUtils.isBlank(claimDialect.getClaimDialectURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_CLAIM_DIALECT.getCode(),
                "Claim dialect URI cannot be empty");
    }

    // TODO : validate claim dialect already exists?

    // TODO : validate tenant domain?
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

    // Add listener

    this.claimDialectDAO.removeClaimDialect(claimDialect, tenantId);
    // When deleting a claim dialect the relevant external claim deletion is handled by the DB through
    // ON DELETE CASCADE. Here we are removing the relevant cache entry.
    externalClaimDAO.removeExternalClaimCache(claimDialect.getClaimDialectURI(), tenantId);
    // Add listener

}
 
Example #13
Source File: PolicySearchCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Invalidate {@link PolicySearchCache}. It will send the cluster message to clean the {@link PolicySearchCache}
 * in all the nodes.
 */
public void invalidateCache() {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (log.isDebugEnabled()) {
        log.debug("Trigger invalidate policy search cache to tenant :  " + IdentityTenantUtil.getTenantDomain(tenantId));
    }

    // Update local policy search cache of this node.
    clearCache();

    // Send out a cluster message to notify other nodes.
    if (isClusteringEnabled()) {
        sendClusterMessage(new PolicySearchCacheInvalidationClusteringMessage(tenantId), true);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Clustering not enabled. Not sending cluster message to other nodes.");
        }
    }
}
 
Example #14
Source File: IdentityProviderNameResolverListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public boolean doPreUpdateIdPByResourceId(String resourceId, IdentityProvider identityProvider, String
        tenantDomain) throws IdentityProviderManagementException {

    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
    IdentityProvider idp = dao.getIdPByResourceId(resourceId, tenantId, tenantDomain);
    if (idp != null) {
        String oldIdPName = idp.getIdentityProviderName();

        // invoking the pre listeners
        Collection<IdentityProviderMgtListener> listeners = IdPManagementServiceComponent.getIdpMgtListeners();
        for (IdentityProviderMgtListener listener : listeners) {
            if (listener.isEnable() && !listener.doPreUpdateIdP(oldIdPName, identityProvider, tenantDomain)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #15
Source File: IdentityProviderManager.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the public service url given the default context and the url picked from the configuration based on
 * the 'tenant_context.enable_tenant_qualified_urls' mode set in deployment.toml.
 *
 * @param defaultUrlContext default url context path
 * @param urlFromConfig     url picked from the file configuration
 * @return absolute public url of the service if 'enable_tenant_qualified_urls' is 'true', else returns the url
 * from the file config
 * @throws IdentityProviderManagementServerException when fail to build the absolute public url
 */
private String resolveAbsoluteURL(String defaultUrlContext, String urlFromConfig) throws IdentityProviderManagementServerException {

    if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && StringUtils.isNotBlank(urlFromConfig)) {
        if (log.isDebugEnabled()) {
            log.debug("Resolved URL:" + urlFromConfig + " from file configuration for default url context: " +
                    defaultUrlContext);
        }
        return urlFromConfig;
    }

    try {
        return ServiceURLBuilder.create().addPath(defaultUrlContext).build().getAbsolutePublicURL();
    } catch (URLBuilderException e) {
        throw IdentityProviderManagementException.error(IdentityProviderManagementServerException.class,
                "Error while building URL: " + defaultUrlContext, e);
    }
}
 
Example #16
Source File: DefaultServiceURLBuilderTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "getRelativePublicURLData")
public void testGetRelativePublicURL(String protocol, String hostName, int port, String proxyContextPath,
                                     String tenantNameFromContext, boolean enableTenantURLSupport,
                                     String expected, String urlPath) {

    when(CarbonUtils.getManagementTransport()).thenReturn(protocol);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME)).thenReturn(hostName);
    when(CarbonUtils.getTransportProxyPort(mockAxisConfiguration, protocol)).thenReturn(port);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
            .PROXY_CONTEXT_PATH)).thenReturn(proxyContextPath);
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(enableTenantURLSupport);
    when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantNameFromContext);
    when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn("carbon.super");

    String relativePublicUrl = null;
    try {
        relativePublicUrl = ServiceURLBuilder.create().addPath(urlPath).build().getRelativePublicURL();
    } catch (URLBuilderException e) {
        //Mock behaviour, hence ignored
    }
    assertEquals(relativePublicUrl, expected);
}
 
Example #17
Source File: IdPManagementDAO.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get all identity provider's Basic information along with additionally requested information depends on the
 * requiredAttributes for a given matching filter.
 *
 * @param tenantId           Tenant Id of the identity provider.
 * @param expressionNode     List of filter value for IdP search.
 * @param limit              Limit per page.
 * @param offset             Offset value.
 * @param sortOrder          Order of IdP ASC/DESC.
 * @param sortBy             The attribute need to sort.
 * @param requiredAttributes Required attributes which needs to be return.
 * @return Identity Provider's Basic Information array along with requested attribute information.
 * @throws IdentityProviderManagementServerException Error when getting list of Identity Providers.
 * @throws IdentityProviderManagementClientException Error when append the filer string.
 */
List<IdentityProvider> getIdPsSearch(int tenantId, List<ExpressionNode> expressionNode, int limit, int offset,
                                     String sortOrder, String sortBy, List<String> requiredAttributes)
        throws IdentityProviderManagementServerException, IdentityProviderManagementClientException {

    FilterQueryBuilder filterQueryBuilder = new FilterQueryBuilder();
    appendFilterQuery(expressionNode, filterQueryBuilder);
    String sortedOrder = sortBy + " " + sortOrder;
    try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(false);
         ResultSet resultSet = getIdpQueryResultSet(dbConnection, sortedOrder, tenantId, offset, limit,
                 filterQueryBuilder, requiredAttributes)) {
        return populateIdentityProviderList(resultSet, dbConnection, requiredAttributes, tenantId);
    } catch (SQLException e) {
        String message = "Error occurred while retrieving Identity Provider for tenant: " +
                IdentityTenantUtil.getTenantDomain(tenantId);
        throw IdPManagementUtil.handleServerException(IdPManagementConstants.ErrorMessage
                .ERROR_CODE_CONNECTING_DATABASE, message, e);
    }
}
 
Example #18
Source File: IdentityProviderManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves Identity provider information about a given tenant by realm identifier
 *
 * @param realmId      Unique realm identifier of the Identity provider of whose information is
 *                     requested
 * @param tenantDomain Tenant domain whose information is requested
 * @throws IdentityProviderManagementException Error when getting Identity Provider
 *                                                information by IdP home realm identifier
 */
public IdentityProvider getIdPByRealmId(String realmId, String tenantDomain)
        throws IdentityProviderManagementException {

    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
    if (StringUtils.isEmpty(realmId)) {
        String msg = "Invalid argument: Identity Provider Home Realm Identifier value is empty";
        throw new IdentityProviderManagementException(msg);
    }
    IdentityProvider identityProvider = dao.getIdPByRealmId(realmId, tenantId, tenantDomain);

    if (identityProvider == null) {
        identityProvider = new FileBasedIdPMgtDAO().getIdPByRealmId(realmId, tenantDomain);
    }

    return identityProvider;
}
 
Example #19
Source File: XMPPConfigurator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * To get XMPP Settings
 *
 * @param userId
 * @return XmppSettingsDTO instance containing XMPP properties
 */
public XMPPSettingsDTO getXmppSettings(String userId) {
    XMPPSettingsDTO xmppSettingsDTO = null;
    try {
        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
        XMPPSettingsDO xmppSettingsDO =
                persistenceManager.getXmppSettings(IdentityTenantUtil.getRegistry(), userId);
        xmppSettingsDTO = new XMPPSettingsDTO();
        xmppSettingsDTO.setXmppServer(xmppSettingsDO.getXmppServer());
        xmppSettingsDTO.setXmppUserName(xmppSettingsDO.getXmppUserName());
        xmppSettingsDTO.setUserCode(xmppSettingsDO.getUserCode());
        xmppSettingsDTO.setXmppEnabled(xmppSettingsDO.isXmppEnabled());
        xmppSettingsDTO.setPINEnabled(xmppSettingsDO.isPINEnabled());

    } catch (Exception e) {
        log.error("Error when instantiating the Persistence Manager.", e);
    }

    return xmppSettingsDTO;
}
 
Example #20
Source File: IdentityMgtEventListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void sendEmail(String userName, int tenantId, String notification) {
    UserRecoveryDTO dto;
    String tenantDomain = IdentityTenantUtil.getTenantDomain(tenantId);

    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        dto = new UserRecoveryDTO(userName);
    } else {
        UserDTO userDTO = new UserDTO(UserCoreUtil.addTenantDomainToEntry(userName, tenantDomain));
        userDTO.setTenantId(tenantId);
        dto = new UserRecoveryDTO(userDTO);
    }
    dto.setNotification(notification);
    dto.setNotificationType(EMAIL_NOTIFICATION_TYPE);
    try {
        IdentityMgtServiceComponent.getRecoveryProcessor().recoverWithNotification(dto);
    } catch (IdentityException e) {
        //proceed with the rest of the flow even if the email is not sent
        log.error("Email notification sending failed for user:" + userName + " for " + notification);
    }
}
 
Example #21
Source File: ClaimMetadataManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void addLocalClaim(LocalClaim localClaim, String tenantDomain) throws ClaimMetadataException {

    if (localClaim == null || StringUtils.isBlank(localClaim.getClaimURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_LOCAL_CLAIM_URI);
    } else if (localClaim.getMappedAttributes().isEmpty()) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_MAPPED_ATTRIBUTES_IN_LOCAL_CLAIM.getCode(),
                String.format(ERROR_CODE_EMPTY_MAPPED_ATTRIBUTES_IN_LOCAL_CLAIM.getMessage(), localClaim
                        .getClaimDialectURI(), localClaim.getClaimURI()));
    }

    // TODO : validate tenant domain?
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

    if (isExistingLocalClaimURI(localClaim.getClaimURI(), tenantId)) {
        throw new ClaimMetadataClientException(ERROR_CODE_EXISTING_LOCAL_CLAIM_URI.getCode(),
                String.format(ERROR_CODE_EXISTING_LOCAL_CLAIM_URI.getMessage(), localClaim.getClaimURI()));
    }

    // Add listener

    this.localClaimDAO.addLocalClaim(localClaim, tenantId);

    // Add listener
}
 
Example #22
Source File: ClaimMetadataManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void renameClaimDialect(ClaimDialect oldClaimDialect, ClaimDialect newClaimDialect, String tenantDomain)
        throws ClaimMetadataException {

    if (oldClaimDialect == null || StringUtils.isBlank(oldClaimDialect.getClaimDialectURI())
            || newClaimDialect == null || StringUtils.isBlank(newClaimDialect.getClaimDialectURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_CLAIM_DIALECT);
    }

    // TODO : Validate oldClaimDialectURI is valid????

    // TODO : validate tenant domain?
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

    // Add listener

    this.claimDialectDAO.renameClaimDialect(oldClaimDialect, newClaimDialect, tenantId);
    externalClaimDAO.removeExternalClaimCache(oldClaimDialect.getClaimDialectURI(), tenantId);
    // Add listener

}
 
Example #23
Source File: ApplicationTemplateApiModelToTemplate.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
@Override
public Template apply(ApplicationTemplateModel applicationTemplate) {

    // Set the additional properties specific to the Application Template as properties map in the template object.
    Map<String, String> propertiesMap = new HashMap<>();
    if (StringUtils.isNotEmpty(applicationTemplate.getAuthenticationProtocol())) {
        propertiesMap.put(ApplicationManagementConstants.TemplateProperties.INBOUND_PROTOCOL,
                applicationTemplate.getAuthenticationProtocol());
    }
    if (applicationTemplate.getTypes() != null) {
        propertiesMap.put(ApplicationManagementConstants.TemplateProperties.TYPES, String.join(",",
                applicationTemplate.getTypes()));
    }
    if (applicationTemplate.getCategory() != null) {
        propertiesMap.put(ApplicationManagementConstants.TemplateProperties.CATEGORY, applicationTemplate
                .getCategory().value());
    }
    if (applicationTemplate.getDisplayOrder() != null) {
        propertiesMap.put(ApplicationManagementConstants.TemplateProperties.DISPLAY_ORDER, Integer
                .toString(applicationTemplate.getDisplayOrder()));
    }

    Template template = new Template();
    template.setTemplateType(TemplateMgtConstants.TemplateType.APPLICATION_TEMPLATE);
    template.setTemplateName(applicationTemplate.getName());
    template.setDescription(applicationTemplate.getDescription());
    template.setImageUrl(applicationTemplate.getImage());
    template.setTenantId(IdentityTenantUtil.getTenantId(getTenantDomainFromContext()));
    template.setPropertiesMap(propertiesMap);
    template.setTemplateScript(createApplicationTemplateScript(applicationTemplate.getApplication()));
    return template;
}
 
Example #24
Source File: User.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This method will retrieve the 'CaseInsensitiveUsername' property from the respective userstore and set that
 * value.
 */
protected void updateCaseSensitivity() {

    if (StringUtils.isNotEmpty(tenantDomain) && StringUtils.isNotEmpty(userStoreDomain)
            && IdentityTenantUtil.getRealmService() != null) {
        this.isUsernameCaseSensitive = IdentityUtil
                .isUserStoreCaseSensitive(userStoreDomain, IdentityTenantUtil.getTenantId(tenantDomain));
    }
}
 
Example #25
Source File: User.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof User)) {
        return false;
    }

    User user = (User) o;

    if (!tenantDomain.equals(user.tenantDomain)) {
        return false;
    }

    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreCaseSensitive(userStoreDomain,
            IdentityTenantUtil.getTenantId(tenantDomain));

    if (isUsernameCaseSensitive) {
        if (!userName.equals(user.userName)) {
            return false;
        }
    } else {
        if (!userName.equalsIgnoreCase(user.userName)) {
            return false;
        }
    }

    if (!userStoreDomain.equals(user.userStoreDomain)) {
        return false;
    }

    return true;
}
 
Example #26
Source File: IdentityProviderService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void addOpenID(String openID) {
    try {

        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
        String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();
        persistenceManager.doOpenIdSignUp(IdentityTenantUtil.getRegistry()
                , AdminServicesUtil.getUserRealm(), openID, userName);

    } catch (Exception e) {
        log.error("Error instantiating a Persistence Manager.", e);
    }
}
 
Example #27
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param userName
 * @return
 * @throws IdentityProviderException
 */
public OpenIDProviderInfoDTO getOpenIDProviderInfo(String userName, String openid)
        throws IdentityProviderException {

    OpenIDProviderInfoDTO providerInfo = new OpenIDProviderInfoDTO();
    String domain = null;
    UserRealm realm = null;

    try {
        domain = MultitenantUtils.getDomainNameFromOpenId(openid);
        realm = IdentityTenantUtil.getRealm(domain, userName);
    } catch (IdentityException e) {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring IdentityException", e);
        }
    }
    if (realm == null) {
        return providerInfo;
    }

    providerInfo.setSubDomain(domain);
    String tenantFreeUsername = MultitenantUtils.getTenantAwareUsername(userName);

    providerInfo.setOpenIDProviderServerUrl(OpenIDUtil.getOpenIDServerURL());
    providerInfo.setOpenID(OpenIDUtil.getOpenIDUserPattern() + "/" + tenantFreeUsername);

    return providerInfo;
}
 
Example #28
Source File: ClaimMetadataManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void addExternalClaim(ExternalClaim externalClaim, String tenantDomain) throws ClaimMetadataException {

    if (externalClaim == null || StringUtils.isBlank(externalClaim.getClaimURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_EXTERNAL_CLAIM_URI);
    }

    if (StringUtils.isBlank(externalClaim.getClaimDialectURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_EXTERNAL_DIALECT_URI);
    }

    if (StringUtils.isBlank(externalClaim.getMappedLocalClaim())) {
        throw new ClaimMetadataClientException(ERROR_CODE_MAPPED_TO_EMPTY_LOCAL_CLAIM_URI);
    }

    if (ClaimConstants.LOCAL_CLAIM_DIALECT_URI.equalsIgnoreCase(externalClaim.getClaimDialectURI())) {
        throw new ClaimMetadataClientException(ERROR_CODE_INVALID_EXTERNAL_CLAIM_DIALECT);
    }

    // TODO : validate tenant domain?
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

    if (isExistingExternalClaimURI(externalClaim.getClaimDialectURI(), externalClaim.getClaimURI(), tenantId)) {
        throw new ClaimMetadataClientException(ERROR_CODE_EXISTING_EXTERNAL_CLAIM_URI.getCode(),
                String.format(ERROR_CODE_EXISTING_EXTERNAL_CLAIM_URI.getMessage(), externalClaim.getClaimURI(),
                        externalClaim.getClaimDialectURI()));
    }

    // Add listener

    this.externalClaimDAO.addExternalClaim(externalClaim, tenantId);

    // Add listener
}
 
Example #29
Source File: ClaimMetadataManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void removeExternalClaim(String externalClaimDialectURI, String externalClaimURI, String tenantDomain)
        throws ClaimMetadataException {

    if (StringUtils.isBlank(externalClaimDialectURI)) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_EXTERNAL_DIALECT_URI.getCode(),
                "External claim dialect URI cannot be empty");
    }

    if (StringUtils.isBlank(externalClaimURI)) {
        throw new ClaimMetadataClientException(ERROR_CODE_EMPTY_EXTERNAL_CLAIM_URI);
    }

    if (ClaimConstants.LOCAL_CLAIM_DIALECT_URI.equalsIgnoreCase(externalClaimDialectURI)) {
        throw new ClaimMetadataClientException(ERROR_CODE_INVALID_EXTERNAL_CLAIM_DIALECT);
    }


    // TODO : validate claim URI already exists?

    // TODO : validate tenant domain?
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

    // Add listener

    this.externalClaimDAO.removeExternalClaim(externalClaimDialectURI, externalClaimURI, tenantId);

    // Add listener
}
 
Example #30
Source File: DeviceStoreDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Remove all registered device from store.
 *
 * @param username
 * @param tenantDomain
 * @param userStoreDomain
 * @throws FIDOAuthenticatorServerException
 */
public void removeRegistration(String username, String tenantDomain, String userStoreDomain, Timestamp timestamp )
        throws FIDOAuthenticatorServerException {

    if (log.isDebugEnabled()) {
        log.debug("removeRegistration inputs {username: " + username + ", tenantDomain: " + tenantDomain +
                  ", userStoreDomain : " + userStoreDomain + "}");
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = connection.prepareStatement(FIDOAuthenticatorConstants.SQLQueries.REMOVE_REGISTRATION_QUERY);
        preparedStatement.setInt(1, IdentityTenantUtil.getTenantId(tenantDomain));
        preparedStatement.setString(2, userStoreDomain);
        preparedStatement.setString(3, username);
        preparedStatement.setTimestamp(4,timestamp);
        preparedStatement.executeUpdate();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        throw new FIDOAuthenticatorServerException(
                "Error executing remove registrations SQL : " +
                FIDOAuthenticatorConstants.SQLQueries.REMOVE_REGISTRATION_QUERY, e
        );
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }
}