Search in sources :

Example 66 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class OwnerReplacementTest method doTest.

private void doTest(KeycloakSession session1, BiFunction<KeycloakSession, RealmModel, String> realm1ObjectIdProducer, TriConsumer<KeycloakSession, RealmModel, String> testLookupRealm1ObjectInRealm2, TetraConsumer<KeycloakSession, RealmModel, RealmModel, String> updaterRealm1ObjectInRealm2, TriConsumer<KeycloakSession, RealmModel, String> testUpdateFailed, TetraConsumer<KeycloakSession, RealmModel, RealmModel, String> removeRealm1ObjectInRealm2, TriConsumer<KeycloakSession, RealmModel, String> testRemoveFailed) {
    // Transaction 1 - Lookup object of realm1
    AtomicReference<String> realm1ObjectId = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
        RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
        realm1ObjectId.set(realm1ObjectIdProducer.apply(session, realm1));
    });
    // Transaction 2
    KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
        RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
        RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm("foo");
        testLookupRealm1ObjectInRealm2.accept(session, realm2, realm1ObjectId.get());
        updaterRealm1ObjectInRealm2.accept(session, realm1, realm2, realm1ObjectId.get());
    });
    // Transaction 3
    KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
        RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
        testUpdateFailed.accept(session, realm1, realm1ObjectId.get());
    });
    // Transaction 4
    try {
        KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
            RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
            RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm("foo");
            removeRealm1ObjectInRealm2.accept(session, realm1, realm2, realm1ObjectId.get());
        });
    } catch (ModelException e) {
    // This is fine. Attempt to remove on incorrect object can throw an exception in some cases, which will enforce transaction rollback
    }
    // Transaction 5
    KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
        RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
        testRemoveFailed.accept(session, realm1, realm1ObjectId.get());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) RealmProvider(org.keycloak.models.RealmProvider) ModelException(org.keycloak.models.ModelException) KeycloakSession(org.keycloak.models.KeycloakSession) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 67 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class JpaUserFederatedStorageProvider method getGrantedConsentEntity.

private FederatedUserConsentEntity getGrantedConsentEntity(String userId, String clientId, LockModeType lockMode) {
    StorageId clientStorageId = new StorageId(clientId);
    String queryName = clientStorageId.isLocal() ? "userFederatedConsentByUserAndClient" : "userFederatedConsentByUserAndExternalClient";
    TypedQuery<FederatedUserConsentEntity> query = em.createNamedQuery(queryName, FederatedUserConsentEntity.class);
    query.setLockMode(lockMode);
    query.setParameter("userId", userId);
    if (clientStorageId.isLocal()) {
        query.setParameter("clientId", clientId);
    } else {
        query.setParameter("clientStorageProvider", clientStorageId.getProviderId());
        query.setParameter("externalClientId", clientStorageId.getExternalId());
    }
    List<FederatedUserConsentEntity> results = query.getResultList();
    if (results.size() > 1) {
        throw new ModelException("More results found for user [" + userId + "] and client [" + clientId + "]");
    } else if (results.size() == 1) {
        return results.get(0);
    } else {
        return null;
    }
}
Also used : ModelException(org.keycloak.models.ModelException) StorageId(org.keycloak.storage.StorageId) FederatedUserConsentEntity(org.keycloak.storage.jpa.entity.FederatedUserConsentEntity)

Example 68 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class JpaUserProvider method getGrantedConsentEntity.

private UserConsentEntity getGrantedConsentEntity(String userId, String clientId, LockModeType lockMode) {
    StorageId clientStorageId = new StorageId(clientId);
    String queryName = clientStorageId.isLocal() ? "userConsentByUserAndClient" : "userConsentByUserAndExternalClient";
    TypedQuery<UserConsentEntity> query = em.createNamedQuery(queryName, UserConsentEntity.class);
    query.setParameter("userId", userId);
    if (clientStorageId.isLocal()) {
        query.setParameter("clientId", clientId);
    } else {
        query.setParameter("clientStorageProvider", clientStorageId.getProviderId());
        query.setParameter("externalClientId", clientStorageId.getExternalId());
    }
    query.setLockMode(lockMode);
    List<UserConsentEntity> results = query.getResultList();
    if (results.size() > 1) {
        throw new ModelException("More results found for user [" + userId + "] and client [" + clientId + "]");
    } else if (results.size() == 1) {
        return results.get(0);
    } else {
        return null;
    }
}
Also used : ModelException(org.keycloak.models.ModelException) StorageId(org.keycloak.storage.StorageId) UserConsentEntity(org.keycloak.models.jpa.entities.UserConsentEntity)

Example 69 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class JpaUserProvider method updateConsent.

@Override
public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
    String clientId = consent.getClient().getId();
    UserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.PESSIMISTIC_WRITE);
    if (consentEntity == null) {
        throw new ModelException("Consent not found for client [" + clientId + "] and user [" + userId + "]");
    }
    updateGrantedConsentEntity(consentEntity, consent);
}
Also used : ModelException(org.keycloak.models.ModelException) UserConsentEntity(org.keycloak.models.jpa.entities.UserConsentEntity)

Example 70 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class UpdatePassword method processAction.

@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();
    KeycloakSession session = context.getSession();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    event.event(EventType.UPDATE_PASSWORD);
    String passwordNew = formData.getFirst("password-new");
    String passwordConfirm = formData.getFirst("password-confirm");
    EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR).client(authSession.getClient()).user(authSession.getAuthenticatedUser());
    if (Validation.isBlank(passwordNew)) {
        Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).addError(new FormMessage(Validation.FIELD_PASSWORD, Messages.MISSING_PASSWORD)).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
        context.challenge(challenge);
        errorEvent.error(Errors.PASSWORD_MISSING);
        return;
    } else if (!passwordNew.equals(passwordConfirm)) {
        Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).addError(new FormMessage(Validation.FIELD_PASSWORD_CONFIRM, Messages.NOTMATCH_PASSWORD)).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
        context.challenge(challenge);
        errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
        return;
    }
    if (getId().equals(authSession.getClientNote(Constants.KC_ACTION_EXECUTING)) && "on".equals(formData.getFirst("logout-sessions"))) {
        session.sessions().getUserSessionsStream(realm, user).filter(s -> !Objects.equals(s.getId(), authSession.getParentSession().getId())).collect(// collect to avoid concurrent modification as backchannelLogout removes the user sessions.
        Collectors.toList()).forEach(s -> AuthenticationManager.backchannelLogout(session, realm, s, session.getContext().getUri(), context.getConnection(), context.getHttpRequest().getHttpHeaders(), true));
    }
    try {
        session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false));
        context.success();
    } catch (ModelException me) {
        errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
        Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).setError(me.getMessage(), me.getParameters()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
        context.challenge(challenge);
        return;
    } catch (Exception ape) {
        errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
        Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).setError(ape.getMessage()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
        context.challenge(challenge);
        return;
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) ModelException(org.keycloak.models.ModelException) KeycloakSession(org.keycloak.models.KeycloakSession) FormMessage(org.keycloak.models.utils.FormMessage) ModelException(org.keycloak.models.ModelException)

Aggregations

ModelException (org.keycloak.models.ModelException)74 RealmModel (org.keycloak.models.RealmModel)20 NamingException (javax.naming.NamingException)13 UserModel (org.keycloak.models.UserModel)13 ClientModel (org.keycloak.models.ClientModel)11 ComponentModel (org.keycloak.component.ComponentModel)10 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)10 IOException (java.io.IOException)9 Consumes (javax.ws.rs.Consumes)9 NotFoundException (javax.ws.rs.NotFoundException)8 BasicAttribute (javax.naming.directory.BasicAttribute)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 RoleModel (org.keycloak.models.RoleModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 ReadOnlyException (org.keycloak.storage.ReadOnlyException)7 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 AttributeInUseException (javax.naming.directory.AttributeInUseException)5