Search in sources :

Example 1 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project core-util by WSO2Telco.

the class UserRoleProsser method getRolesByUserName.

public List<String> getRolesByUserName(String userName) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    List<String> currentUserRoleList = null;
    try {
        RealmConfiguration realmConfiguration = new RealmConfiguration();
        String[] currentUserRoles = realmService.getUserRealm(realmConfiguration).getUserStoreManager().getRoleListOfUser(userName);
        currentUserRoleList = Arrays.asList(currentUserRoles);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("unable to retrieve user roles for user " + userName + " : ", e);
    }
    if (currentUserRoleList != null && !currentUserRoleList.isEmpty()) {
        return currentUserRoleList;
    } else {
        return Collections.emptyList();
    }
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) RealmService(org.wso2.carbon.user.core.service.RealmService) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext)

Example 2 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project core-util by WSO2Telco.

the class BasicAuthenticator method isAuthenticatedUser.

public boolean isAuthenticatedUser(String userName, String password) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class, null);
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    try {
        UserRealm userRealm = null;
        userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
        if (userRealm == null) {
            log.error("invalid domain or unactivated tenant login");
            return false;
        }
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userName);
        if (userRealm.getUserStoreManager().authenticate(tenantAwareUsername, password)) {
            return true;
        } else {
            log.error("authentication failed. please check your username/password");
            return false;
        }
    } catch (CarbonException | UserStoreException e) {
        log.error("authentication failed for user : " + userName, e);
        return false;
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) CarbonException(org.wso2.carbon.CarbonException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Example 3 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project carbon-business-process by wso2.

the class AuthenticationHandler method authenticate.

/**
 * Checks whether a given userName:password combination authenticates correctly against carbon userStore
 * Upon successful authentication returns true, false otherwise
 *
 * @param userName
 * @param password
 * @return
 * @throws RestApiBasicAuthenticationException wraps and throws exceptions occur when trying to authenticate
 *                                             the user
 */
private boolean authenticate(String userName, String password) throws RestApiBasicAuthenticationException {
    boolean authStatus;
    try {
        IdentityService identityService = BPMNOSGIService.getIdentityService();
        authStatus = identityService.checkPassword(userName, password);
        if (!authStatus) {
            return false;
        }
    } catch (BPMNAuthenticationException e) {
        throw new RestApiBasicAuthenticationException(e.getMessage(), e);
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);
    String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
    RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
    TenantManager mgr = realmService.getTenantManager();
    int tenantId = 0;
    try {
        tenantId = mgr.getTenantId(tenantDomain);
        // tenantId == -1, means an invalid tenant.
        if (tenantId == -1) {
            if (log.isDebugEnabled()) {
                log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
            }
            return false;
        }
    } catch (UserStoreException e) {
        throw new RestApiBasicAuthenticationException("Identity exception thrown while getting tenant ID for user : " + userNameWithTenantDomain, e);
    }
    /* Upon successful authentication existing thread local carbon context
             * is updated to mimic the authenticated user */
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setUsername(tenantAwareUserName);
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomain);
    return true;
}
Also used : IdentityService(org.activiti.engine.IdentityService) RestApiBasicAuthenticationException(org.wso2.carbon.bpmn.rest.common.exception.RestApiBasicAuthenticationException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager)

Example 4 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project jaggery by wso2.

the class RhinoTopLevel method setInterval.

public static String setInterval(Context cx, final Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "setTimeout";
    int argsCount = args.length;
    if (argsCount < 2) {
        HostObjectUtil.invalidNumberOfArgs(EngineConstants.GLOBAL_OBJECT_NAME, functionName, argsCount, false);
    }
    Function function = null;
    long interval;
    if (args[0] instanceof Function) {
        function = (Function) args[0];
    } else if (args[0] instanceof String) {
        function = getFunction(cx, thisObj, (String) args[0], functionName);
    } else {
        HostObjectUtil.invalidArgsError(EngineConstants.GLOBAL_OBJECT_NAME, EngineConstants.GLOBAL_OBJECT_NAME, "1", "string|function", args[0], false);
    }
    if (!(args[1] instanceof Number)) {
        HostObjectUtil.invalidArgsError(EngineConstants.GLOBAL_OBJECT_NAME, EngineConstants.GLOBAL_OBJECT_NAME, "2", "number", args[1], false);
    }
    if (function == null) {
        String error = "Callback cannot be null in " + functionName;
        log.error(error);
        throw new ScriptException(error);
    }
    final JaggeryContext context = getJaggeryContext();
    final Object[] params = Arrays.copyOfRange(args, 2, args.length);
    final Function callback = function;
    final ContextFactory factory = cx.getFactory();
    interval = ((Number) args[1]).longValue();
    String uuid = UUID.randomUUID().toString();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    final int tenantId = carbonContext.getTenantId();
    final String tenantDomain = carbonContext.getTenantDomain();
    final String applicationName = carbonContext.getApplicationName();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    ScheduledFuture future = timerExecutor.scheduleAtFixedRate(new Runnable() {

        private boolean firstTime = true;

        @Override
        public void run() {
            // set the context classloader
            Thread currentThread = Thread.currentThread();
            ClassLoader originalClassLoader = currentThread.getContextClassLoader();
            Thread.currentThread().setContextClassLoader(contextClassLoader);
            // child inherits context properties form the parent thread.
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantId(tenantId);
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setApplicationName(applicationName);
            try {
                Context cx = RhinoEngine.enterContext(factory);
                RhinoEngine.putContextProperty(EngineConstants.JAGGERY_CONTEXT, context);
                callback.call(cx, thisObj, thisObj, params);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
                RhinoEngine.exitContext();
                currentThread.setContextClassLoader(originalClassLoader);
            }
        }
    }, interval, interval, TimeUnit.MILLISECONDS);
    Map<String, ScheduledFuture> tasks = intervals.get(context.getTenantDomain());
    if (tasks == null) {
        tasks = new HashMap<String, ScheduledFuture>();
        intervals.put(context.getTenantDomain(), tasks);
    }
    tasks.put(uuid, future);
    return uuid;
}
Also used : PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Example 5 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project jaggery by wso2.

the class RhinoTopLevel method setTimeout.

public static String setTimeout(Context cx, final Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "setTimeout";
    int argsCount = args.length;
    if (argsCount < 2) {
        HostObjectUtil.invalidNumberOfArgs(EngineConstants.GLOBAL_OBJECT_NAME, functionName, argsCount, false);
    }
    Function function = null;
    long timeout;
    if (args[0] instanceof Function) {
        function = (Function) args[0];
    } else if (args[0] instanceof String) {
        function = getFunction(cx, thisObj, (String) args[0], functionName);
    } else {
        HostObjectUtil.invalidArgsError(EngineConstants.GLOBAL_OBJECT_NAME, EngineConstants.GLOBAL_OBJECT_NAME, "1", "string|function", args[0], false);
    }
    if (!(args[1] instanceof Number)) {
        HostObjectUtil.invalidArgsError(EngineConstants.GLOBAL_OBJECT_NAME, EngineConstants.GLOBAL_OBJECT_NAME, "2", "number", args[1], false);
    }
    if (function == null) {
        String error = "Callback cannot be null in " + functionName;
        log.error(error);
        throw new ScriptException(error);
    }
    final JaggeryContext context = getJaggeryContext();
    final Object[] params = Arrays.copyOfRange(args, 2, args.length);
    final Function callback = function;
    final ContextFactory factory = cx.getFactory();
    timeout = ((Number) args[1]).longValue();
    final String uuid = UUID.randomUUID().toString();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    final int tenantId = carbonContext.getTenantId();
    final String tenantDomain = carbonContext.getTenantDomain();
    final String applicationName = carbonContext.getApplicationName();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    ScheduledFuture future = timerExecutor.schedule(new Callable<Void>() {

        public Void call() throws Exception {
            // set the context classloader
            Thread currentThread = Thread.currentThread();
            ClassLoader originalClassLoader = currentThread.getContextClassLoader();
            Thread.currentThread().setContextClassLoader(contextClassLoader);
            // child inherits context properties form the parent thread.
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantId(tenantId);
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setApplicationName(applicationName);
            try {
                Context ctx = RhinoEngine.enterContext(factory);
                RhinoEngine.putContextProperty(EngineConstants.JAGGERY_CONTEXT, context);
                callback.call(ctx, thisObj, thisObj, params);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                clearTimeout(uuid);
                PrivilegedCarbonContext.endTenantFlow();
                RhinoEngine.exitContext();
                currentThread.setContextClassLoader(originalClassLoader);
            }
            return null;
        }
    }, timeout, TimeUnit.MILLISECONDS);
    Map<String, ScheduledFuture> tasks = timeouts.get(context.getTenantDomain());
    if (tasks == null) {
        tasks = new HashMap<String, ScheduledFuture>();
        timeouts.put(context.getTenantDomain(), tasks);
    }
    tasks.put(uuid, future);
    return uuid;
}
Also used : PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Aggregations

PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)28 RealmService (org.wso2.carbon.user.core.service.RealmService)15 CarbonContext (org.wso2.carbon.context.CarbonContext)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 UserRealm (org.wso2.carbon.user.core.UserRealm)6 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)6 ArrayList (java.util.ArrayList)5 Registry (org.wso2.carbon.registry.core.Registry)5 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 List (java.util.List)3 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)3 APIConstants (org.wso2.carbon.apimgt.impl.APIConstants)3 APIUtil (org.wso2.carbon.apimgt.impl.utils.APIUtil)3 ServiceReferenceHolder (org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder)3 RestApiConstants (org.wso2.carbon.apimgt.rest.api.common.RestApiConstants)3