Search in sources :

Example 6 with UserProfile

use of org.keycloak.userprofile.UserProfile 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 7 with UserProfile

use of org.keycloak.userprofile.UserProfile 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 8 with UserProfile

use of org.keycloak.userprofile.UserProfile 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)

Example 9 with UserProfile

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

the class UserProfileTest method testNoValidationsIfUserReadOnly.

private static void testNoValidationsIfUserReadOnly(KeycloakSession session) throws IOException {
    DeclarativeUserProfileProvider provider = getDynamicUserProfileProvider(session);
    ComponentModel component = provider.getComponentModel();
    assertNotNull(component);
    UPConfig config = new UPConfig();
    UPAttribute attribute = new UPAttribute();
    attribute.setName(ATT_ADDRESS);
    UPAttributeRequired requirements = new UPAttributeRequired();
    attribute.setRequired(requirements);
    UPAttributePermissions permissions = new UPAttributePermissions();
    permissions.setEdit(Collections.singleton(UPConfigUtils.ROLE_ADMIN));
    attribute.setPermissions(permissions);
    config.addAttribute(attribute);
    provider.setConfiguration(JsonSerialization.writeValueAsString(config));
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(UserModel.USERNAME, "user");
    attributes.put(UserModel.FIRST_NAME, "user");
    attributes.put(UserModel.LAST_NAME, "user");
    // NO fail on USER contexts
    UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes);
    profile.validate();
    // Fails on ADMIN context - User REST API
    try {
        profile = provider.create(UserProfileContext.USER_API, attributes);
        profile.validate();
        fail("Should fail validation");
    } catch (ValidationException ve) {
        assertTrue(ve.isAttributeOnError(ATT_ADDRESS));
    }
}
Also used : UPAttributePermissions(org.keycloak.userprofile.config.UPAttributePermissions) ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) HashMap(java.util.HashMap) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UPConfig(org.keycloak.userprofile.config.UPConfig) ComponentModel(org.keycloak.component.ComponentModel) UPAttributeRequired(org.keycloak.userprofile.config.UPAttributeRequired) UPAttribute(org.keycloak.userprofile.config.UPAttribute)

Example 10 with UserProfile

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

the class UserProfileTest method testGetProfileAttributes.

private static void testGetProfileAttributes(KeycloakSession session) {
    RealmModel realm = session.getContext().getRealm();
    UserModel user = session.users().addUser(realm, org.keycloak.models.utils.KeycloakModelUtils.generateId());
    UserProfileProvider provider = getDynamicUserProfileProvider(session);
    provider.setConfiguration("{\"attributes\": [{\"name\": \"address\", \"required\": {}, \"permissions\": {\"edit\": [\"user\"]}}]}");
    UserProfile profile = provider.create(UserProfileContext.ACCOUNT, user);
    Attributes attributes = profile.getAttributes();
    assertThat(attributes.nameSet(), containsInAnyOrder(UserModel.USERNAME, UserModel.EMAIL, UserModel.FIRST_NAME, UserModel.LAST_NAME, "address"));
    try {
        profile.validate();
        Assert.fail("Should fail validation");
    } catch (ValidationException ve) {
        // username is mandatory
        assertTrue(ve.isAttributeOnError("address"));
    }
    assertNotNull(attributes.getFirstValue(UserModel.USERNAME));
    assertNull(attributes.getFirstValue(UserModel.EMAIL));
    assertNull(attributes.getFirstValue(UserModel.FIRST_NAME));
    assertNull(attributes.getFirstValue(UserModel.LAST_NAME));
    assertNull(attributes.getFirstValue("address"));
    user.setAttribute("address", Arrays.asList("fixed-address"));
    profile = provider.create(UserProfileContext.ACCOUNT, user);
    attributes = profile.getAttributes();
    profile.validate();
    assertNotNull(attributes.getFirstValue("address"));
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ComponentValidationException(org.keycloak.component.ComponentValidationException) ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) DeclarativeUserProfileProvider(org.keycloak.userprofile.DeclarativeUserProfileProvider) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) Attributes(org.keycloak.userprofile.Attributes)

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