Search in sources :

Example 31 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class SpannerUpateMissingEntrySample method main.

public static void main(String[] args) {
    // Prepare sample connection details
    SpannerEntryManagerSample sqlEntryManagerSample = new SpannerEntryManagerSample();
    // Create SQL entry manager
    SpannerEntryManager sqlEntryManager = sqlEntryManagerSample.createSpannerEntryManager();
    String sessionId = UUID.randomUUID().toString();
    final String sessionDn = "uniqueIdentifier=" + sessionId + ",ou=session,o=jans";
    final SimpleSessionState simpleSessionState = new SimpleSessionState();
    simpleSessionState.setDn(sessionDn);
    simpleSessionState.setId(sessionId);
    simpleSessionState.setLastUsedAt(new Date());
    try {
        sqlEntryManager.merge(simpleSessionState);
        System.out.println("Updated");
    } catch (EntryPersistenceException ex) {
        LOG.info("Failed to update, root case exception: {}", ex.getCause().getClass(), ex);
    }
}
Also used : SimpleSessionState(io.jans.orm.cloud.spanner.model.SimpleSessionState) SpannerEntryManagerSample(io.jans.orm.cloud.spanner.persistence.SpannerEntryManagerSample) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) Date(java.util.Date) SpannerEntryManager(io.jans.orm.cloud.spanner.impl.SpannerEntryManager)

Example 32 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class LdapBatchJobSample method main.

public static void main(String[] args) {
    // Prepare sample connection details
    LdapEntryManagerSample ldapEntryManagerSample = new LdapEntryManagerSample();
    // Create LDAP entry manager
    final LdapEntryManager ldapEntryManager = ldapEntryManagerSample.createLdapEntryManager();
    BatchOperation<SimpleTokenLdap> tokenLdapBatchOperation = new ProcessBatchOperation<SimpleTokenLdap>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleTokenLdap> objects) {
            for (SimpleTokenLdap simpleTokenLdap : objects) {
                try {
                    CustomAttribute customAttribute = getUpdatedAttribute(ldapEntryManager, simpleTokenLdap.getDn(), "exp", simpleTokenLdap.getAttribute("exp"));
                    simpleTokenLdap.setCustomAttributes(Arrays.asList(new CustomAttribute[] { customAttribute }));
                    ldapEntryManager.merge(simpleTokenLdap);
                    processedCount++;
                } catch (EntryPersistenceException ex) {
                    LOG.error("Failed to update entry", ex);
                }
            }
            LOG.info("Total processed: " + processedCount);
        }
    };
    final Filter filter1 = Filter.createPresenceFilter("exp");
    ldapEntryManager.findEntries("o=jans", SimpleTokenLdap.class, filter1, SearchScope.SUB, new String[] { "exp" }, tokenLdapBatchOperation, 0, 0, 100);
    BatchOperation<SimpleSession> sessionBatchOperation = new ProcessBatchOperation<SimpleSession>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleSession> objects) {
            for (SimpleSession simpleSession : objects) {
                try {
                    CustomAttribute customAttribute = getUpdatedAttribute(ldapEntryManager, simpleSession.getDn(), "jansLastAccessTime", simpleSession.getAttribute("jansLastAccessTime"));
                    simpleSession.setCustomAttributes(Arrays.asList(new CustomAttribute[] { customAttribute }));
                    ldapEntryManager.merge(simpleSession);
                    processedCount++;
                } catch (EntryPersistenceException ex) {
                    LOG.error("Failed to update entry", ex);
                }
            }
            LOG.info("Total processed: " + processedCount);
        }
    };
    final Filter filter2 = Filter.createPresenceFilter("jansLastAccessTime");
    ldapEntryManager.findEntries("o=jans", SimpleSession.class, filter2, SearchScope.SUB, new String[] { "jansLastAccessTime" }, sessionBatchOperation, 0, 0, 100);
    BatchOperation<SimpleClient> clientBatchOperation = new ProcessBatchOperation<SimpleClient>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleClient> objects) {
            for (SimpleClient simpleClient : objects) {
                processedCount++;
            }
            LOG.info("Total processed: " + processedCount);
        }
    };
    final Filter filter3 = Filter.createPresenceFilter("exp");
    List<SimpleClient> result3 = ldapEntryManager.findEntries("o=jans", SimpleClient.class, filter3, SearchScope.SUB, new String[] { "exp" }, clientBatchOperation, 0, 0, 1000);
    LOG.info("Result count (without collecting results): " + result3.size());
    BatchOperation<SimpleClient> clientBatchOperation2 = new DefaultBatchOperation<SimpleClient>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleClient> objects) {
            for (SimpleClient simpleClient : objects) {
                processedCount++;
            }
            LOG.info("Total processed: " + processedCount);
        }
    };
    final Filter filter4 = Filter.createPresenceFilter("exp");
    List<SimpleClient> result4 = ldapEntryManager.findEntries("o=jans", SimpleClient.class, filter4, SearchScope.SUB, new String[] { "exp" }, clientBatchOperation2, 0, 0, 1000);
    LOG.info("Result count (with collecting results): " + result4.size());
}
Also used : SimpleTokenLdap(io.jans.orm.ldap.model.SimpleTokenLdap) CustomAttribute(io.jans.orm.model.base.CustomAttribute) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) DefaultBatchOperation(io.jans.orm.model.DefaultBatchOperation) LdapEntryManager(io.jans.orm.ldap.impl.LdapEntryManager) Filter(io.jans.orm.search.filter.Filter) ProcessBatchOperation(io.jans.orm.model.ProcessBatchOperation) List(java.util.List) SimpleClient(io.jans.orm.ldap.model.SimpleClient) SimpleSession(io.jans.orm.ldap.model.SimpleSession)

Example 33 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class Fido2DeviceService method findAllFido2Devices.

public List<GluuFido2Device> findAllFido2Devices(GluuCustomPerson person) {
    try {
        String baseDnForU2fDevices = getDnForFido2Device(null, person.getInum());
        Filter inumFilter = Filter.createEqualityFilter(OxTrustConstants.PERSON_INUM, person.getInum());
        return ldapEntryManager.findEntries(baseDnForU2fDevices, GluuFido2Device.class, inumFilter);
    } catch (EntryPersistenceException e) {
        log.warn("No fido2 devices enrolled for " + person.getDisplayName());
        return new ArrayList<>();
    }
}
Also used : Filter(io.jans.orm.search.filter.Filter) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException)

Example 34 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class GroupService method isMemberOrOwner.

public boolean isMemberOrOwner(String groupDN, String personDN) {
    Filter ownerFilter = Filter.createEqualityFilter(OxTrustConstants.owner, personDN);
    Filter memberFilter = Filter.createEqualityFilter(OxTrustConstants.member, personDN);
    Filter searchFilter = Filter.createORFilter(ownerFilter, memberFilter);
    boolean isMemberOrOwner = false;
    try {
        isMemberOrOwner = persistenceEntryManager.findEntries(groupDN, GluuGroup.class, searchFilter, 1).size() > 0;
    } catch (EntryPersistenceException ex) {
        log.error("Failed to determine if person '{}' memeber or owner of group '{}'", personDN, groupDN, ex);
    }
    return isMemberOrOwner;
}
Also used : Filter(io.jans.orm.search.filter.Filter) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) GluuGroup(io.jans.scim.model.GluuGroup)

Example 35 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class AuthorizeAction method checkPermissionGranted.

public void checkPermissionGranted() throws IOException {
    if ((clientId == null) || clientId.isEmpty()) {
        log.debug("Permission denied. client_id should be not empty.");
        permissionDenied();
        return;
    }
    Client client = null;
    try {
        client = clientService.getClient(clientId);
    } catch (EntryPersistenceException ex) {
        log.debug("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
        permissionDenied();
        return;
    }
    if (client == null) {
        log.debug("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
        permissionDenied();
        return;
    }
    // Fix the list of scopes in the authorization page. Jans Auth #739
    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
    allowedScope = io.jans.as.model.util.StringUtils.implode(grantedScopes, " ");
    SessionId session = getSession();
    List<io.jans.as.model.common.Prompt> prompts = io.jans.as.model.common.Prompt.fromString(prompt, " ");
    try {
        redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, session != null ? session.getSessionAttributes().get(SESSION_USER_CODE) : null, (HttpServletRequest) externalContext.getRequest());
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        permissionDenied();
        return;
    }
    try {
        session = sessionIdService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
    } catch (AcrChangedException e) {
        log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
        if (e.isForceReAuthentication()) {
            session = handleAcrChange(session, prompts);
        } else {
            log.error("ACR is changed, please provide a supported and enabled acr value");
            permissionDenied();
            return;
        }
    }
    if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
        Map<String, String> parameterMap = externalContext.getRequestParameterMap();
        Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
        String redirectTo = "/login.xhtml";
        boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
        if (useExternalAuthenticator) {
            List<String> acrValuesList = sessionIdService.acrValuesList(this.acrValues);
            if (acrValuesList.isEmpty()) {
                acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
            }
            CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
            if (customScriptConfiguration == null) {
                log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
                permissionDenied();
                return;
            }
            String acr = customScriptConfiguration.getName();
            requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
            requestParameterMap.put("auth_step", Integer.toString(1));
            String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
            if (StringHelper.isNotEmpty(tmpRedirectTo)) {
                log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
                redirectTo = tmpRedirectTo;
            }
        }
        // Store Remote IP
        String remoteIp = networkService.getRemoteIp();
        requestParameterMap.put(Constants.REMOTE_IP, remoteIp);
        // User Code used in Device Authz flow
        if (session != null && session.getSessionAttributes().containsKey(SESSION_USER_CODE)) {
            String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
            requestParameterMap.put(SESSION_USER_CODE, userCode);
        }
        // Create unauthenticated session
        SessionId unauthenticatedSession = sessionIdService.generateUnauthenticatedSessionId(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
        unauthenticatedSession.setSessionAttributes(requestParameterMap);
        unauthenticatedSession.addPermission(clientId, false);
        // Copy ACR script parameters
        if (appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
            authenticationService.copyAuthenticatorExternalAttributes(session, unauthenticatedSession);
        }
        // #1030, fix for flow 4 - transfer previous session permissions to new session
        if (session != null && session.getPermissionGrantedMap() != null && session.getPermissionGrantedMap().getPermissionGranted() != null) {
            for (Map.Entry<String, Boolean> entity : session.getPermissionGrantedMap().getPermissionGranted().entrySet()) {
                unauthenticatedSession.addPermission(entity.getKey(), entity.getValue());
            }
            // #1030, remove previous session
            sessionIdService.remove(session);
        }
        // always persist is prompt is not none
        boolean persisted = sessionIdService.persistSessionId(unauthenticatedSession, !prompts.contains(io.jans.as.model.common.Prompt.NONE));
        if (persisted && log.isTraceEnabled()) {
            log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
        }
        this.sessionId = unauthenticatedSession.getId();
        cookieService.createSessionIdCookie(unauthenticatedSession, false);
        cookieService.creatRpOriginIdCookie(redirectUri);
        identity.setSessionId(unauthenticatedSession);
        Map<String, Object> loginParameters = new HashMap<String, Object>();
        if (requestParameterMap.containsKey(io.jans.as.model.authorize.AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(io.jans.as.model.authorize.AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(io.jans.as.model.authorize.AuthorizeRequestParam.LOGIN_HINT));
        }
        boolean enableRedirect = StringHelper.toBoolean(System.getProperty("gluu.enable-redirect", "false"), false);
        if (!enableRedirect && redirectTo.toLowerCase().endsWith("xhtml")) {
            if (redirectTo.toLowerCase().endsWith("postlogin.xhtml")) {
                authenticator.authenticateWithOutcome();
            } else {
                authenticator.prepareAuthenticationForStep(unauthenticatedSession);
                facesService.renderView(redirectTo);
            }
        } else {
            facesService.redirectWithExternal(redirectTo, loginParameters);
        }
        return;
    }
    String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
    if (StringUtils.isBlank(userCode) && StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST);
        externalContext.setResponseContentType(MediaType.APPLICATION_JSON);
        externalContext.getResponseOutputWriter().write(errorResponseFactory.getErrorAsJson(io.jans.as.model.authorize.AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
        facesContext.responseComplete();
    }
    if (log.isTraceEnabled()) {
        log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
    }
    if (prompts.contains(io.jans.as.model.common.Prompt.SELECT_ACCOUNT)) {
        Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
        facesService.redirect("/selectAccount.xhtml", requestParameterMap);
        return;
    }
    if (prompts.contains(io.jans.as.model.common.Prompt.NONE) && prompts.size() > 1) {
        invalidRequest();
        return;
    }
    ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, session, (HttpServletRequest) externalContext.getRequest(), (HttpServletResponse) externalContext.getResponse());
    final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
    final boolean hasConsentPrompt = prompts.contains(io.jans.as.model.common.Prompt.CONSENT);
    if (!hasConsentPrompt && !forceAuthorization) {
        final boolean isTrusted = isTrue(appConfiguration.getTrustedClientEnabled()) && client.getTrustedClient();
        final boolean canGrantAccess = isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.equals(client.getSubjectType()) && hasOnlyOpenidScope();
        // There is no need to present the consent page:
        // If Client is a Trusted Client.
        // If a client is configured for pairwise identifiers, and the openid scope is the only scope requested.
        // Also, we should make sure that the claims request is not enabled.
        final boolean isPairwiseWithOnlyOpenIdScope = client.getSubjectType() == SubjectType.PAIRWISE && grantedScopes.size() == 1 && grantedScopes.contains(DefaultScope.OPEN_ID.toString()) && scope.equals(DefaultScope.OPEN_ID.toString()) && claims == null && request == null;
        if (isTrusted || canGrantAccess || isPairwiseWithOnlyOpenIdScope) {
            permissionGranted(session);
            return;
        }
        final User user = sessionIdService.getUser(session);
        ClientAuthorization clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
        if (clientAuthorization != null && clientAuthorization.getScopes() != null && Arrays.asList(clientAuthorization.getScopes()).containsAll(io.jans.as.model.util.StringUtils.spaceSeparatedToList(scope))) {
            permissionGranted(session);
            return;
        }
    }
    if (externalConsentGatheringService.isEnabled()) {
        if (consentGatherer.isConsentGathered()) {
            log.trace("Consent-gathered flow passed successfully");
            permissionGranted(session);
            return;
        }
        log.trace("Starting external consent-gathering flow");
        boolean result = consentGatherer.configure(session.getUserDn(), clientId, state);
        if (!result) {
            log.error("Failed to initialize external consent-gathering flow.");
            permissionDenied();
            return;
        }
    }
}
Also used : User(io.jans.as.common.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) AcrChangedException(io.jans.as.server.model.exception.AcrChangedException) ExternalContext(javax.faces.context.ExternalContext) Client(io.jans.as.common.model.registration.Client) SessionId(io.jans.as.server.model.common.SessionId) ClientAuthorization(io.jans.as.server.model.ldap.ClientAuthorization) ExternalPostAuthnContext(io.jans.as.server.service.external.context.ExternalPostAuthnContext) Prompt(io.jans.as.model.common.Prompt) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Aggregations

EntryPersistenceException (io.jans.orm.exception.EntryPersistenceException)61 SearchException (io.jans.orm.exception.operation.SearchException)33 AuthenticationException (io.jans.orm.exception.AuthenticationException)31 EntryDeleteException (io.jans.orm.exception.EntryDeleteException)30 MappingException (io.jans.orm.exception.MappingException)30 Filter (io.jans.orm.search.filter.Filter)24 AttributeData (io.jans.orm.model.AttributeData)16 DateTimeParseException (java.time.format.DateTimeParseException)15 PropertyAnnotation (io.jans.orm.reflect.property.PropertyAnnotation)13 ParsedKey (io.jans.orm.impl.model.ParsedKey)12 ArrayList (java.util.ArrayList)11 Date (java.util.Date)10 SearchScopeException (io.jans.orm.exception.operation.SearchScopeException)9 JsonObject (com.couchbase.client.java.document.json.JsonObject)8 ConnectionException (io.jans.orm.exception.operation.ConnectionException)8 ParseException (java.text.ParseException)8 DateTimeException (java.time.DateTimeException)7 List (java.util.List)7 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)6 EntryData (io.jans.orm.model.EntryData)6