Search in sources :

Example 26 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class CarbonUserManagerBasedPeopleQueryEvaluator method getRoleNameListForUser.

public List<String> getRoleNameListForUser(String userName) {
    String tUserName = userName;
    List<String> matchingRoleNames = new ArrayList<String>();
    if (StringUtils.isNotEmpty(tUserName)) {
        tUserName = tUserName.trim();
        if (cachingEnabled) {
            Cache<String, List<String>> roleNameListForUserCache = getRoleNameListForUserCache();
            if (roleNameListForUserCache != null && roleNameListForUserCache.containsKey(tUserName)) {
                return roleNameListForUserCache.get(tUserName);
            }
        }
        if (isExistingUser(tUserName)) {
            try {
                matchingRoleNames.addAll(Arrays.asList(getUserRealm().getUserStoreManager().getRoleListOfUser(tUserName)));
                if (cachingEnabled) {
                    getRoleNameListForUserCache().put(tUserName, matchingRoleNames);
                    Cache<String, Boolean> roleNameListCache = getRoleNameListCache();
                    if (roleNameListCache != null) {
                        for (String roleName : matchingRoleNames) {
                            roleNameListCache.put(roleName, true);
                        }
                    }
                }
            } catch (UserStoreException ex) {
                throw new HumanTaskRuntimeException("Error occurred while calling" + " to realm service for operation isExistingRole", ex);
            }
        }
    }
    return matchingRoleNames;
}
Also used : ArrayList(java.util.ArrayList) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ArrayList(java.util.ArrayList) List(java.util.List) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)

Example 27 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class JobProcessorImpl method executeDeadline.

private void executeDeadline(long taskId, String name) throws HumanTaskException {
    // TODO what if two deadlines fired at the same time???
    // TODO do the needful for deadlines. i.e create notifications and re-assign
    log.info("ON DEADLINE: " + " : now: " + new Date());
    TaskDAO task = HumanTaskServiceComponent.getHumanTaskServer().getDaoConnectionFactory().getConnection().getTask(taskId);
    // Setting the tenant id and tenant domain
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(task.getTenantId());
    String tenantDomain = null;
    try {
        tenantDomain = HumanTaskServiceComponent.getRealmService().getTenantManager().getDomain(task.getTenantId());
    } catch (UserStoreException e) {
        log.error(" Cannot find the tenant domain " + e.toString());
    }
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
    TaskConfiguration taskConf = (TaskConfiguration) HumanTaskServiceComponent.getHumanTaskServer().getTaskStoreManager().getHumanTaskStore(task.getTenantId()).getTaskConfiguration(QName.valueOf(task.getName()));
    TDeadline deadline = taskConf.getDeadline(name);
    EvaluationContext evalCtx = new ExpressionEvaluationContext(task, taskConf);
    List<TEscalation> validEscalations = new ArrayList<TEscalation>();
    boolean reassingnmentAdded = false;
    for (TEscalation escalation : deadline.getEscalationArray()) {
        if (!escalation.isSetCondition()) {
            // We only need the first Re-assignment and we ignore all other re-assignments
            if (escalation.isSetReassignment() && !reassingnmentAdded) {
                reassingnmentAdded = true;
            } else if (escalation.isSetReassignment()) {
                continue;
            }
            validEscalations.add(escalation);
            continue;
        }
        if (evaluateCondition(escalation.getCondition().newCursor().getTextValue(), escalation.getCondition().getExpressionLanguage() == null ? taskConf.getExpressionLanguage() : escalation.getCondition().getExpressionLanguage(), evalCtx)) {
            if (escalation.isSetReassignment() && !reassingnmentAdded) {
                reassingnmentAdded = true;
            } else if (escalation.isSetReassignment()) {
                continue;
            }
            validEscalations.add(escalation);
        }
    }
    // We may do this in the above for loop as well
    for (TEscalation escalation : validEscalations) {
        if (log.isDebugEnabled()) {
            log.debug("Escalation: " + escalation.getName());
        }
        if (escalation.isSetLocalNotification() || escalation.isSetNotification()) {
            QName qName;
            if (escalation.isSetLocalNotification()) {
                qName = escalation.getLocalNotification().getReference();
            } else {
                qName = new QName(taskConf.getName().getNamespaceURI(), escalation.getNotification().getName());
            }
            HumanTaskBaseConfiguration notificationConfiguration = HumanTaskServiceComponent.getHumanTaskServer().getTaskStoreManager().getHumanTaskStore(task.getTenantId()).getActiveTaskConfiguration(qName);
            if (notificationConfiguration == null) {
                log.error("Fatal Error, notification definition not found for name " + qName.toString());
                return;
            }
            TaskCreationContext taskContext = new TaskCreationContext();
            taskContext.setTaskConfiguration(notificationConfiguration);
            taskContext.setTenantId(task.getTenantId());
            taskContext.setPeopleQueryEvaluator(HumanTaskServiceComponent.getHumanTaskServer().getTaskEngine().getPeopleQueryEvaluator());
            Map<String, Element> tempBodyParts = new HashMap<String, Element>();
            Map<String, Element> tempHeaderParts = new HashMap<String, Element>();
            QName tempName = null;
            TToParts toParts = escalation.getToParts();
            if (toParts == null) {
                // get the input message of the task
                MessageDAO msg = task.getInputMessage();
                tempName = msg.getName();
                for (Map.Entry<String, Element> partEntry : msg.getBodyParts().entrySet()) {
                    tempBodyParts.put(partEntry.getKey(), partEntry.getValue());
                }
                for (Map.Entry<String, Element> partEntry : msg.getHeaderParts().entrySet()) {
                    tempHeaderParts.put(partEntry.getKey(), partEntry.getValue());
                }
                taskContext.setMessageBodyParts(tempBodyParts);
                taskContext.setMessageHeaderParts(tempHeaderParts);
                taskContext.setMessageName(tempName);
            } else {
                for (TToPart toPart : toParts.getToPartArray()) {
                    if (!notificationConfiguration.isValidPart(toPart.getName())) {
                        // This validation should be done at the deployment time
                        String errMsg = "The part: " + toPart.getName() + " is not available" + " in the corresponding WSDL message";
                        log.error(errMsg);
                        throw new RuntimeException(errMsg);
                    }
                    String expLang = toPart.getExpressionLanguage() == null ? taskConf.getExpressionLanguage() : toPart.getExpressionLanguage();
                    Node nodePart = HumanTaskServerHolder.getInstance().getHtServer().getTaskEngine().getExpressionLanguageRuntime(expLang).evaluateAsPart(toPart.newCursor().getTextValue(), toPart.getName(), evalCtx);
                    tempBodyParts.put(toPart.getName(), (Element) nodePart);
                }
            }
            taskContext.setMessageBodyParts(tempBodyParts);
            taskContext.setMessageHeaderParts(tempHeaderParts);
            taskContext.setMessageName(tempName);
            HumanTaskServerHolder.getInstance().getHtServer().getTaskEngine().getDaoConnectionFactory().getConnection().createTask(taskContext);
        } else {
            // if re-assignment
            if (escalation.getReassignment().getPotentialOwners().isSetFrom()) {
                escalation.getReassignment().getPotentialOwners().getFrom().getArgumentArray();
                String roleName = null;
                for (TArgument argument : escalation.getReassignment().getPotentialOwners().getFrom().getArgumentArray()) {
                    if ("role".equals(argument.getName())) {
                        roleName = argument.newCursor().getTextValue().trim();
                    }
                }
                if (roleName == null) {
                    String errMsg = "Value for argument name 'role' is expected.";
                    log.error(errMsg);
                    throw new Scheduler.JobProcessorException(errMsg);
                }
                if (!isExistingRole(roleName, task.getTenantId())) {
                    log.warn("Role name " + roleName + " does not exist for tenant id" + task.getTenantId());
                }
                List<OrganizationalEntityDAO> orgEntities = new ArrayList<OrganizationalEntityDAO>();
                OrganizationalEntityDAO orgEntity = HumanTaskServiceComponent.getHumanTaskServer().getDaoConnectionFactory().getConnection().createNewOrgEntityObject(roleName, OrganizationalEntityDAO.OrganizationalEntityType.GROUP);
                orgEntities.add(orgEntity);
                task.replaceOrgEntitiesForLogicalPeopleGroup(GenericHumanRoleDAO.GenericHumanRoleType.POTENTIAL_OWNERS, orgEntities);
            } else {
                String errMsg = "From element is expected inside the assignment";
                log.error(errMsg);
                throw new Scheduler.JobProcessorException(errMsg);
            }
        }
    }
}
Also used : Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) TaskConfiguration(org.wso2.carbon.humantask.core.store.TaskConfiguration) HumanTaskBaseConfiguration(org.wso2.carbon.humantask.core.store.HumanTaskBaseConfiguration) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ExpressionEvaluationContext(org.wso2.carbon.humantask.core.engine.runtime.ExpressionEvaluationContext) QName(javax.xml.namespace.QName) ExpressionEvaluationContext(org.wso2.carbon.humantask.core.engine.runtime.ExpressionEvaluationContext) EvaluationContext(org.wso2.carbon.humantask.core.engine.runtime.api.EvaluationContext)

Example 28 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project product-iots by wso2.

the class DeviceTypeServiceImpl method createDownloadFile.

private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) throws DeviceManagementException, JWTClientException, APIManagerException, UserStoreException {
    // create new device id
    String deviceId = shortUUID();
    if (apiApplicationKey == null) {
        String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
        applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
        APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
        String[] tags = { DeviceTypeConstants.DEVICE_TYPE };
        apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true, "3600");
    }
    JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
    String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
    AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
    // create token
    String accessToken = accessTokenInfo.getAccessToken();
    String refreshToken = accessTokenInfo.getRefreshToken();
    boolean status = register(deviceId, deviceName);
    if (!status) {
        String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
        throw new DeviceManagementException(msg);
    }
    ZipUtil ziputil = new ZipUtil();
    ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
    return zipFile;
}
Also used : AccessTokenInfo(org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagementProviderService(org.wso2.carbon.apimgt.application.extension.APIManagementProviderService) JWTClient(org.wso2.carbon.identity.jwt.client.extension.JWTClient) ZipUtil(org.wso2.iot.sampledevice.api.util.ZipUtil) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive)

Example 29 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method checkWithBackUpCodes.

/**
 * If user forgets the mobile, then user can use the back up codes to authenticate the user.
 *
 * @param context           the AuthenticationContext
 * @param userToken         the userToken
 * @param authenticatedUser the name of authenticatedUser
 * @throws AuthenticationFailedException
 */
private void checkWithBackUpCodes(AuthenticationContext context, String userToken, AuthenticatedUser authenticatedUser) throws AuthenticationFailedException {
    String savedOTPString = null;
    String username = context.getProperty(SMSOTPConstants.USER_NAME).toString();
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    UserRealm userRealm = getUserRealm(username);
    try {
        if (userRealm != null) {
            savedOTPString = userRealm.getUserStoreManager().getUserClaimValue(tenantAwareUsername, SMSOTPConstants.SAVED_OTP_LIST, null);
        }
        if (StringUtils.isEmpty(savedOTPString)) {
            if (log.isDebugEnabled()) {
                log.debug("The claim " + SMSOTPConstants.SAVED_OTP_LIST + " does not contain any values");
            }
            throw new AuthenticationFailedException("The claim " + SMSOTPConstants.SAVED_OTP_LIST + " does not contain any values");
        } else if (savedOTPString.contains(userToken)) {
            if (log.isDebugEnabled()) {
                log.debug("Found saved backup SMS OTP for user :" + authenticatedUser);
            }
            context.setSubject(authenticatedUser);
            savedOTPString = savedOTPString.replaceAll(userToken, "").replaceAll(",,", ",");
            userRealm.getUserStoreManager().setUserClaimValue(tenantAwareUsername, SMSOTPConstants.SAVED_OTP_LIST, savedOTPString, null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("User entered OTP :" + userToken + " does not match with any of the saved backup codes");
            }
            throw new AuthenticationFailedException("Verification Error due to Code " + userToken + " mismatch.");
        }
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Cannot find the user claim for OTP list for user : " + authenticatedUser, e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 30 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPUtils method updateUserAttribute.

/**
 * Update the mobile number (user attribute) in user's profile.
 *
 * @param username  the Username
 * @param attribute the Attribute
 * @throws SMSOTPException
 */
public static void updateUserAttribute(String username, Map<String, String> attribute, String tenantDomain) throws SMSOTPException {
    try {
        // updating user attributes is independent from tenant association.not tenant association check needed here.
        UserRealm userRealm;
        // user is always in the super tenant.
        userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
        if (userRealm == null) {
            throw new SMSOTPException("The specified tenant domain " + tenantDomain + " does not exist.");
        }
        // check whether user already exists in the system.
        SMSOTPUtils.verifyUserExists(username, tenantDomain);
        UserStoreManager userStoreManager = userRealm.getUserStoreManager();
        userStoreManager.setUserClaimValues(username, attribute, null);
    } catch (UserStoreException | AuthenticationFailedException e) {
        throw new SMSOTPException("Exception occurred while connecting to User Store: Authentication is failed. ", e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)21 UserRealm (org.wso2.carbon.user.api.UserRealm)10 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)6 RealmService (org.wso2.carbon.user.core.service.RealmService)6 ArrayList (java.util.ArrayList)5 SMSOTPException (org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException)5 ActivitiException (org.activiti.engine.ActivitiException)4 HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)4 UserRealm (org.wso2.carbon.user.core.UserRealm)4 UserStoreException (org.wso2.carbon.user.core.UserStoreException)4 IOException (java.io.IOException)3 List (java.util.List)3 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)3 BPMNAuthenticationException (org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException)3 BPMNForbiddenException (org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException)3 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)3 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2