Search in sources :

Example 21 with UserProfile

use of org.keycloak.userprofile.UserProfile in project keycloak by keycloak.

the class UserResource method updateUser.

/**
 * Update the user
 *
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateUser(final UserRepresentation rep) {
    auth.users().requireManage(user);
    try {
        boolean wasPermanentlyLockedOut = false;
        if (rep.isEnabled() != null && rep.isEnabled()) {
            UserLoginFailureModel failureModel = session.loginFailures().getUserLoginFailure(realm, user.getId());
            if (failureModel != null) {
                failureModel.clearFailures();
            }
            wasPermanentlyLockedOut = session.getProvider(BruteForceProtector.class).isPermanentlyLockedOut(session, realm, user);
        }
        UserProfile profile = session.getProvider(UserProfileProvider.class).create(USER_API, rep.toAttributes(), user);
        Response response = validateUserProfile(profile, user, session);
        if (response != null) {
            return response;
        }
        profile.update(rep.getAttributes() != null);
        updateUserFromRep(profile, user, rep, session, true);
        RepresentationToModel.createCredentials(rep, session, realm, user, true);
        // we need to do it here as the attributes would be overwritten by what is in the rep
        if (wasPermanentlyLockedOut) {
            session.getProvider(BruteForceProtector.class).cleanUpPermanentLockout(session, realm, user);
        }
        adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().commit();
        }
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("User exists with same username or email");
    } catch (ReadOnlyException re) {
        return ErrorResponse.error("User is read only!", Status.BAD_REQUEST);
    } catch (ModelException me) {
        logger.warn("Could not update user!", me);
        return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
    } catch (ForbiddenException fe) {
        throw fe;
    } catch (Exception me) {
        // JPA
        // may be committed by JTA which can't
        logger.warn("Could not update user!", me);
        return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) ForbiddenException(org.keycloak.services.ForbiddenException) UserLoginFailureModel(org.keycloak.models.UserLoginFailureModel) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) WebApplicationException(javax.ws.rs.WebApplicationException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ValidationException(org.keycloak.userprofile.ValidationException) ReadOnlyException(org.keycloak.storage.ReadOnlyException) BadRequestException(javax.ws.rs.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) ForbiddenException(org.keycloak.services.ForbiddenException) EmailException(org.keycloak.email.EmailException) ModelException(org.keycloak.models.ModelException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 22 with UserProfile

use of org.keycloak.userprofile.UserProfile in project keycloak by keycloak.

the class AccountRestService method account.

/**
 * Get account information.
 *
 * @return
 */
@Path("/")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public UserRepresentation account(@QueryParam("userProfileMetadata") final Boolean userProfileMetadata) {
    auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE);
    UserModel user = auth.getUser();
    UserRepresentation rep = new UserRepresentation();
    rep.setId(user.getId());
    rep.setUsername(user.getUsername());
    rep.setFirstName(user.getFirstName());
    rep.setLastName(user.getLastName());
    rep.setEmail(user.getEmail());
    rep.setEmailVerified(user.isEmailVerified());
    UserProfileProvider provider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = provider.create(UserProfileContext.ACCOUNT, user);
    rep.setAttributes(profile.getAttributes().getReadable(false));
    if (userProfileMetadata == null || userProfileMetadata.booleanValue())
        rep.setUserProfileMetadata(createUserProfileMetadata(profile));
    return rep;
}
Also used : UserModel(org.keycloak.models.UserModel) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) UserRepresentation(org.keycloak.representations.account.UserRepresentation) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 23 with UserProfile

use of org.keycloak.userprofile.UserProfile in project keycloak by keycloak.

the class AccountRestService method updateAccount.

@Path("/")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response updateAccount(UserRepresentation rep) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    event.event(EventType.UPDATE_PROFILE).client(auth.getClient()).user(auth.getUser()).detail(Details.CONTEXT, UserProfileContext.ACCOUNT.name());
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.ACCOUNT, rep.toAttributes(), auth.getUser());
    try {
        profile.update(new EventAuditingAttributeChangeListener(profile, event));
        event.success();
        return Response.noContent().build();
    } catch (ValidationException pve) {
        List<ErrorRepresentation> errors = new ArrayList<>();
        for (Error err : pve.getErrors()) {
            errors.add(new ErrorRepresentation(err.getAttribute(), err.getMessage(), validationErrorParamsToString(err.getMessageParameters(), profile.getAttributes())));
        }
        return ErrorResponse.errors(errors, pve.getStatusCode(), false);
    } catch (ReadOnlyException e) {
        return ErrorResponse.error(Messages.READ_ONLY_USER, Response.Status.BAD_REQUEST);
    }
}
Also used : ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) EventAuditingAttributeChangeListener(org.keycloak.userprofile.EventAuditingAttributeChangeListener) Error(org.keycloak.userprofile.ValidationException.Error) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 24 with UserProfile

use of org.keycloak.userprofile.UserProfile in project keycloak by keycloak.

the class RegistrationProfile method validate.

@Override
public void validate(org.keycloak.authentication.ValidationContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    context.getEvent().detail(Details.REGISTER_METHOD, "form");
    UserProfileProvider profileProvider = context.getSession().getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.REGISTRATION_PROFILE, formData);
    try {
        profile.validate();
    } catch (ValidationException pve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(pve.getErrors());
        if (pve.hasError(Messages.EMAIL_EXISTS, Messages.INVALID_EMAIL)) {
            context.getEvent().detail(Details.EMAIL, profile.getAttributes().getFirstValue(UserModel.EMAIL));
        }
        if (pve.hasError(Messages.EMAIL_EXISTS)) {
            context.error(Errors.EMAIL_IN_USE);
        } else
            context.error(Errors.INVALID_REGISTRATION);
        context.validationError(formData, errors);
        return;
    }
    context.success();
}
Also used : ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) List(java.util.List)

Example 25 with UserProfile

use of org.keycloak.userprofile.UserProfile in project keycloak by keycloak.

the class UpdateProfile method processAction.

@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent();
    event.event(EventType.UPDATE_PROFILE).detail(Details.CONTEXT, UserProfileContext.UPDATE_PROFILE.name());
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    UserModel user = context.getUser();
    UserProfileProvider provider = context.getSession().getProvider(UserProfileProvider.class);
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, formData, user);
    try {
        // backward compatibility with old account console where attributes are not removed if missing
        profile.update(false, new EventAuditingAttributeChangeListener(profile, event));
        context.success();
    } catch (ValidationException pve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(pve.getErrors());
        context.challenge(createResponse(context, formData, errors));
    }
}
Also used : UserModel(org.keycloak.models.UserModel) EventBuilder(org.keycloak.events.EventBuilder) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) EventAuditingAttributeChangeListener(org.keycloak.userprofile.EventAuditingAttributeChangeListener) List(java.util.List)

Aggregations

UserProfile (org.keycloak.userprofile.UserProfile)35 ValidationException (org.keycloak.userprofile.ValidationException)25 UserProfileProvider (org.keycloak.userprofile.UserProfileProvider)24 DeclarativeUserProfileProvider (org.keycloak.userprofile.DeclarativeUserProfileProvider)22 HashMap (java.util.HashMap)19 ComponentValidationException (org.keycloak.component.ComponentValidationException)16 UserModel (org.keycloak.models.UserModel)12 UPAttribute (org.keycloak.userprofile.config.UPAttribute)11 UPConfig (org.keycloak.userprofile.config.UPConfig)11 ComponentModel (org.keycloak.component.ComponentModel)9 List (java.util.List)8 UPAttributePermissions (org.keycloak.userprofile.config.UPAttributePermissions)8 UPAttributeRequired (org.keycloak.userprofile.config.UPAttributeRequired)7 ArrayList (java.util.ArrayList)4 Consumes (javax.ws.rs.Consumes)4 RealmModel (org.keycloak.models.RealmModel)4 HashSet (java.util.HashSet)3 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 Produces (javax.ws.rs.Produces)3