Search in sources :

Example 1 with ModelException

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

the class UserResource method resetPassword.

/**
 * Set up a new password for the user.
 *
 * @param cred The representation must contain a rawPassword with the plain-text password
 */
@Path("reset-password")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void resetPassword(CredentialRepresentation cred) {
    auth.users().requireManage(user);
    if (cred == null || cred.getValue() == null) {
        throw new BadRequestException("No password provided");
    }
    if (Validation.isBlank(cred.getValue())) {
        throw new BadRequestException("Empty password not allowed");
    }
    try {
        session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false));
    } catch (IllegalStateException ise) {
        throw new BadRequestException("Resetting to N old passwords is not allowed.");
    } catch (ReadOnlyException mre) {
        throw new BadRequestException("Can't reset password as account is read only");
    } catch (ModelException e) {
        logger.warn("Could not update user password.", e);
        Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
        throw new ErrorResponseException(e.getMessage(), MessageFormat.format(messages.getProperty(e.getMessage(), e.getMessage()), e.getParameters()), Status.BAD_REQUEST);
    }
    if (cred.isTemporary() != null && cred.isTemporary()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    } else {
        // Remove a potentially existing UPDATE_PASSWORD action when explicitly assigning a non-temporary password.
        user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
Also used : ModelException(org.keycloak.models.ModelException) BadRequestException(javax.ws.rs.BadRequestException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Properties(java.util.Properties) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 2 with ModelException

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

the class UsersResource method createUser.

/**
 * Create a new user
 *
 * Username must be unique.
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(final UserRepresentation rep) {
    // first check if user has manage rights
    try {
        auth.users().requireManage();
    } catch (ForbiddenException exception) {
        if (!canCreateGroupMembers(rep)) {
            throw exception;
        }
    }
    String username = rep.getUsername();
    if (realm.isRegistrationEmailAsUsername()) {
        username = rep.getEmail();
    }
    if (ObjectUtil.isBlank(username)) {
        return ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
    }
    // Double-check duplicated username and email here due to federation
    if (session.users().getUserByUsername(realm, username) != null) {
        return ErrorResponse.exists("User exists with same username");
    }
    if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
        try {
            if (session.users().getUserByEmail(realm, rep.getEmail()) != null) {
                return ErrorResponse.exists("User exists with same email");
            }
        } catch (ModelDuplicateException e) {
            return ErrorResponse.exists("User exists with same email");
        }
    }
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(USER_API, rep.toAttributes());
    try {
        Response response = UserResource.validateUserProfile(profile, null, session);
        if (response != null) {
            return response;
        }
        UserModel user = profile.create();
        UserResource.updateUserFromRep(profile, user, rep, session, false);
        RepresentationToModel.createFederatedIdentities(rep, session, realm, user);
        RepresentationToModel.createGroups(rep, realm, user);
        RepresentationToModel.createCredentials(rep, session, realm, user, true);
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().commit();
        }
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.exists("User exists with same username or email");
    } catch (PasswordPolicyNotMetException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
    } catch (ModelException me) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        logger.warn("Could not create user", me);
        return ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 3 with ModelException

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

the class InfinispanUserSessionProvider method getUserSessionsStream.

protected Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserSessionPredicate predicate, boolean offline) {
    if (offline && loadOfflineSessionsFromDatabase) {
        // fetch the offline user-sessions from the persistence provider
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        if (predicate.getUserId() != null) {
            UserModel user = session.users().getUserById(realm, predicate.getUserId());
            if (user != null) {
                return persister.loadUserSessionsStream(realm, user, true, 0, null);
            }
        }
        if (predicate.getBrokerUserId() != null) {
            String[] idpAliasSessionId = predicate.getBrokerUserId().split("\\.");
            Map<String, String> attributes = new HashMap<>();
            attributes.put(UserModel.IDP_ALIAS, idpAliasSessionId[0]);
            attributes.put(UserModel.IDP_USER_ID, idpAliasSessionId[1]);
            UserProvider userProvider = session.getProvider(UserProvider.class);
            UserModel userModel = userProvider.searchForUserStream(realm, attributes, 0, null).findFirst().orElse(null);
            return userModel != null ? persister.loadUserSessionsStream(realm, userModel, true, 0, null) : Stream.empty();
        }
        if (predicate.getBrokerSessionId() != null) {
            // currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way
            throw new ModelException("Dynamic database lookup for offline user-sessions by broker session ID is currently only supported for preloaded sessions. " + "Set preloadOfflineSessionsFromDatabase option to \"true\" in " + UserSessionSpi.NAME + " SPI in " + InfinispanUserSessionProviderFactory.PROVIDER_ID + " provider to enable the lookup.");
        }
    }
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
    cache = CacheDecorators.skipCacheLoaders(cache);
    // and then mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
    return StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false).map(Mappers.userSessionEntity()).map(entity -> this.wrap(realm, entity, offline));
}
Also used : UserModel(org.keycloak.models.UserModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ModelException(org.keycloak.models.ModelException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserProvider(org.keycloak.models.UserProvider) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 4 with ModelException

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

the class MapUserProvider method updateConsent.

@Override
public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
    LOG.tracef("updateConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace());
    MapUserEntity user = getEntityByIdOrThrow(realm, userId);
    MapUserConsentEntity userConsentEntity = user.getUserConsent(consent.getClient().getId()).orElseThrow(() -> new ModelException("Consent not found for client [" + consent.getClient().getId() + "] and user [" + userId + "]"));
    userConsentEntity.setGrantedClientScopesIds(consent.getGrantedClientScopes().stream().map(ClientScopeModel::getId).collect(Collectors.toSet()));
    userConsentEntity.setLastUpdatedDate(Time.currentTimeMillis());
}
Also used : ModelException(org.keycloak.models.ModelException) ClientScopeModel(org.keycloak.models.ClientScopeModel)

Example 5 with ModelException

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

the class MapUserConsentEntity method toModel.

public static UserConsentModel toModel(RealmModel realm, MapUserConsentEntity entity) {
    if (entity == null) {
        return null;
    }
    ClientModel client = realm.getClientById(entity.getClientId());
    if (client == null) {
        throw new ModelException("Client with id " + entity.getClientId() + " is not available");
    }
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());
    Set<String> grantedClientScopesIds = entity.getGrantedClientScopesIds();
    if (grantedClientScopesIds != null && !grantedClientScopesIds.isEmpty()) {
        grantedClientScopesIds.stream().map(scopeId -> KeycloakModelUtils.findClientScopeById(realm, client, scopeId)).filter(Objects::nonNull).forEach(model::addGrantedClientScope);
    }
    return model;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ModelException(org.keycloak.models.ModelException) UserConsentModel(org.keycloak.models.UserConsentModel)

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