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();
}
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);
}
}
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));
}
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());
}
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;
}
Aggregations