Search in sources :

Example 1 with ValidationException

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

the class IdpReviewProfileAuthenticator method actionImpl.

@Override
protected void actionImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
    EventBuilder event = context.getEvent();
    // velias: looks like UPDATE_PROFILE event is not fired. IMHO it should not be fired here as user record in keycloak is not changed, user doesn't exist yet
    event.event(EventType.UPDATE_PROFILE).detail(Details.CONTEXT, UserProfileContext.IDP_REVIEW.name());
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    UserModelDelegate updatedProfile = new UserModelDelegate(null) {

        @Override
        public String getId() {
            return userCtx.getId();
        }

        @Override
        public Map<String, List<String>> getAttributes() {
            return userCtx.getAttributes();
        }

        @Override
        public Stream<String> getAttributeStream(String name) {
            return userCtx.getAttribute(name).stream();
        }

        @Override
        public void setAttribute(String name, List<String> values) {
            userCtx.setAttribute(name, values);
        }

        @Override
        public void removeAttribute(String name) {
            userCtx.getAttributes().remove(name);
        }

        @Override
        public String getFirstAttribute(String name) {
            return userCtx.getFirstAttribute(name);
        }

        @Override
        public String getUsername() {
            return userCtx.getUsername();
        }
    };
    UserProfileProvider profileProvider = context.getSession().getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.IDP_REVIEW, formData, updatedProfile);
    try {
        String oldEmail = userCtx.getEmail();
        profile.update((attributeName, userModel, oldValue) -> {
            if (attributeName.equals(UserModel.EMAIL)) {
                context.getAuthenticationSession().setAuthNote(UPDATE_PROFILE_EMAIL_CHANGED, "true");
                event.clone().event(EventType.UPDATE_EMAIL).detail(Details.CONTEXT, UserProfileContext.IDP_REVIEW.name()).detail(Details.PREVIOUS_EMAIL, oldEmail).detail(Details.UPDATED_EMAIL, profile.getAttributes().getFirstValue(UserModel.EMAIL)).success();
            }
        });
    } catch (ValidationException pve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(pve.getErrors());
        Response challenge = context.form().setErrors(errors).setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx).setFormData(formData).createUpdateProfilePage();
        context.challenge(challenge);
        return;
    }
    userCtx.saveToAuthenticationSession(context.getAuthenticationSession(), BROKERED_CONTEXT_NOTE);
    logger.debugf("Profile updated successfully after first authentication with identity provider '%s' for broker user '%s'.", brokerContext.getIdpConfig().getAlias(), userCtx.getUsername());
    String newEmail = profile.getAttributes().getFirstValue(UserModel.EMAIL);
    event.detail(Details.UPDATED_EMAIL, newEmail);
    // Ensure page is always shown when user later returns to it - for example with form "back" button
    context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
    context.success();
}
Also used : Response(javax.ws.rs.core.Response) EventBuilder(org.keycloak.events.EventBuilder) UserModelDelegate(org.keycloak.models.utils.UserModelDelegate) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) List(java.util.List)

Example 2 with ValidationException

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

the class RegistrationUserCreation method validate.

@Override
public void validate(ValidationContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    context.getEvent().detail(Details.REGISTER_METHOD, "form");
    KeycloakSession session = context.getSession();
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.REGISTRATION_USER_CREATION, formData);
    String email = profile.getAttributes().getFirstValue(UserModel.EMAIL);
    String username = profile.getAttributes().getFirstValue(UserModel.USERNAME);
    String firstName = profile.getAttributes().getFirstValue(UserModel.FIRST_NAME);
    String lastName = profile.getAttributes().getFirstValue(UserModel.LAST_NAME);
    context.getEvent().detail(Details.EMAIL, email);
    context.getEvent().detail(Details.USERNAME, username);
    context.getEvent().detail(Details.FIRST_NAME, firstName);
    context.getEvent().detail(Details.LAST_NAME, lastName);
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        context.getEvent().detail(Details.USERNAME, email);
    }
    try {
        profile.validate();
    } catch (ValidationException pve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(pve.getErrors());
        if (pve.hasError(Messages.EMAIL_EXISTS)) {
            context.error(Errors.EMAIL_IN_USE);
        } else if (pve.hasError(Messages.MISSING_EMAIL, Messages.MISSING_USERNAME, Messages.INVALID_EMAIL)) {
            context.error(Errors.INVALID_REGISTRATION);
        } else if (pve.hasError(Messages.USERNAME_EXISTS)) {
            context.error(Errors.USERNAME_IN_USE);
        }
        context.validationError(formData, errors);
        return;
    }
    context.success();
}
Also used : ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) KeycloakSession(org.keycloak.models.KeycloakSession) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) List(java.util.List)

Example 3 with ValidationException

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

the class VerifyUserProfile method requiredActionChallenge.

@Override
public void requiredActionChallenge(RequiredActionContext context) {
    UserProfileProvider provider = context.getSession().getProvider(UserProfileProvider.class);
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, context.getUser());
    try {
        profile.validate();
        context.success();
    } catch (ValidationException ve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(ve.getErrors());
        MultivaluedMap<String, String> parameters;
        if (context.getHttpRequest().getHttpMethod().equalsIgnoreCase(HttpMethod.GET)) {
            parameters = new MultivaluedHashMap<>();
        } else {
            parameters = context.getHttpRequest().getDecodedFormParameters();
        }
        context.challenge(createResponse(context, parameters, errors));
        EventBuilder event = context.getEvent().clone();
        event.event(EventType.VERIFY_PROFILE);
        event.detail("fields_to_update", collectFields(errors));
        event.success();
    }
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ValidationException(org.keycloak.userprofile.ValidationException) EventBuilder(org.keycloak.events.EventBuilder) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) List(java.util.List) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 4 with ValidationException

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

the class AccountFormService method processAccountUpdate.

/**
 * Update account information.
 * <p>
 * Form params:
 * <p>
 * firstName
 * lastName
 * email
 *
 * @return
 */
@Path("/")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processAccountUpdate() {
    MultivaluedMap<String, String> formData = request.getDecodedFormParameters();
    if (auth == null) {
        return login(null);
    }
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    String action = formData.getFirst("submitAction");
    if (action != null && action.equals("Cancel")) {
        setReferrerOnPage();
        return account.createResponse(AccountPages.ACCOUNT);
    }
    csrfCheck(formData);
    UserModel user = auth.getUser();
    event.event(EventType.UPDATE_PROFILE).client(auth.getClient()).user(auth.getUser()).detail(Details.CONTEXT, UserProfileContext.ACCOUNT_OLD.name());
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.ACCOUNT_OLD, formData, user);
    try {
        // backward compatibility with old account console where attributes are not removed if missing
        profile.update(false, new EventAuditingAttributeChangeListener(profile, event));
    } catch (ValidationException pve) {
        List<FormMessage> errors = Validation.getFormErrorsFromValidation(pve.getErrors());
        if (!errors.isEmpty()) {
            setReferrerOnPage();
            Response.Status status = Status.OK;
            if (pve.hasError(Messages.READ_ONLY_USERNAME)) {
                status = Response.Status.BAD_REQUEST;
            } else if (pve.hasError(Messages.EMAIL_EXISTS, Messages.USERNAME_EXISTS)) {
                status = Response.Status.CONFLICT;
            }
            return account.setErrors(status, errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
        }
    } catch (ReadOnlyException e) {
        setReferrerOnPage();
        return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
    }
    event.success();
    setReferrerOnPage();
    return account.setSuccess(Messages.ACCOUNT_UPDATED).createResponse(AccountPages.ACCOUNT);
}
Also used : UserModel(org.keycloak.models.UserModel) Status(javax.ws.rs.core.Response.Status) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) EventAuditingAttributeChangeListener(org.keycloak.userprofile.EventAuditingAttributeChangeListener) List(java.util.List) ArrayList(java.util.ArrayList) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 5 with ValidationException

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

the class UserProfileTest method testDefaultConfig.

private static void testDefaultConfig(KeycloakSession session) {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    // reset configuration to default
    provider.setConfiguration(null);
    // failed required validations
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, Collections.emptyMap());
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(UserModel.USERNAME));
    }
    // failed for blank values also
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.FIRST_NAME, "");
    attributes.put(UserModel.LAST_NAME, " ");
    attributes.put(UserModel.EMAIL, "");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    try {
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(UserModel.USERNAME));
        assertTrue(ve.isAttributeOnError(UserModel.FIRST_NAME));
        assertTrue(ve.isAttributeOnError(UserModel.LAST_NAME));
        assertTrue(ve.isAttributeOnError(UserModel.EMAIL));
    }
    // all OK
    attributes.put(UserModel.USERNAME, "jdoeusername");
    attributes.put(UserModel.FIRST_NAME, "John");
    attributes.put(UserModel.LAST_NAME, "Doe");
    attributes.put(UserModel.EMAIL, "jdoe@acme.org");
    profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
}
Also used : ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider)

Aggregations

ValidationException (org.keycloak.userprofile.ValidationException)25 UserProfile (org.keycloak.userprofile.UserProfile)24 ComponentValidationException (org.keycloak.component.ComponentValidationException)16 DeclarativeUserProfileProvider (org.keycloak.userprofile.DeclarativeUserProfileProvider)16 UserProfileProvider (org.keycloak.userprofile.UserProfileProvider)15 HashMap (java.util.HashMap)14 UPAttribute (org.keycloak.userprofile.config.UPAttribute)10 UPConfig (org.keycloak.userprofile.config.UPConfig)10 ComponentModel (org.keycloak.component.ComponentModel)9 List (java.util.List)7 UPAttributePermissions (org.keycloak.userprofile.config.UPAttributePermissions)7 UPAttributeRequired (org.keycloak.userprofile.config.UPAttributeRequired)7 UserModel (org.keycloak.models.UserModel)6 EventBuilder (org.keycloak.events.EventBuilder)3 RealmModel (org.keycloak.models.RealmModel)3 EventAuditingAttributeChangeListener (org.keycloak.userprofile.EventAuditingAttributeChangeListener)3 ArrayList (java.util.ArrayList)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2