8000 Allow setting default value for userprofile attribute by huyenvu2101 · Pull Request #39746 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
< 8000 /div>
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,14 @@ public class UserProfileAttributeMetadata {
private Map<String, Map<String, Object>> validators;
private String group;
private boolean multivalued;
private String defaultValue;

public UserProfileAttributeMetadata() {

}

public UserProfileAttributeMetadata(String name, String displayName, boolean required, boolean read 8000 Only, String group, Map<String, Object> annotations,
Map<String, Map<String, Object>> validators, boolean multivalued) {
Map<String, Map<String, Object>> validators, boolean multivalued, String defaultValue) {
this.name = name;
this.displayName = displayName;
this.required = required;
Expand All @@ -46,12 +47,17 @@ public UserProfileAttributeMetadata(String name, String displayName, boolean req
this.validators = validators;
this.group = group;
this.multivalued = multivalued;
this.defaultValue = defaultValue;
}

public String getName() {
return name;
}

public String getDefaultValue() {
return defaultValue;
}

/**
* @return display name, either direct string to display, or construct for i18n like <code>${i18nkey}</code>
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class UPAttribute implements Cloneable {
private UPAttributeSelector selector;
private String group;
private boolean multivalued;
private String defaultValue;

public UPAttribute() {
}
Expand Down Expand Up @@ -152,13 +153,21 @@ public void setMultivalued(boolean multivalued) {
this.multivalued = multivalued;
}

public String getDefaultValue() {
return defaultValue;
}

public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}

public boolean isMultivalued() {
return multivalued;
}

@Override
public String toString() {
return "UPAttribute [name=" + name + ", displayName=" + displayName + ", permissions=" + permissions + ", selector=" + selector + ", required=" + required + ", validations=" + validations + ", annotations=" + annotations + ", group=" + group + ", multivalued=" + multivalued + "]";
return "UPAttribute [name=" + name + ", displayName=" + displayName + ", permissions=" + permissions + ", selector=" + selector + ", required=" + required + ", validations=" + validations + ", annotations=" + annotations + ", group=" + group + ", multivalued=" + multivalued + ", defaultValue=" + defaultValue + "]";
}

@Override
Expand All @@ -184,6 +193,7 @@ protected UPAttribute clone() {
attr.setSelector(this.selector == null ? null : this.selector.clone());
attr.setGroup(this.group);
attr.setMultivalued(this.multivalued);
attr.setDefaultValue(this.defaultValue);
return attr;
}

Expand All @@ -209,6 +219,7 @@ public boolean equals(Object obj) {
&& Objects.equals(this.required, other.required)
&& Objects.equals(this.permissions, other.permissions)
&& Objects.equals(this.selector, other.selector)
&& Objects.equals(this.multivalued, other.multivalued);
&& Objects.equals(this.multivalued, other.multivalued)
&& Objects.equals(this.defaultValue, other.defaultValue);
}
}
8BD0
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ Multivalued::
If enabled, the attribute supports multiple values and UIs are rendered accordingly to allow setting many values. When enabling this
setting, make sure to add a validator to set a hard limit to the number of values.

Default Value::
Defines the value that will be automatically assigned to the attribute if the user does not provide one.
Ensure that this default value complies with all configured validators for the attribute.

Attribute Group::
The attribute group to which the attribute belongs to, if any.

Expand Down
1 change: 1 addition & 0 deletions js/apps/account-ui/src/api/representations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export interface UserProfileAttributeMetadata {
annotations?: { [index: string]: any };
validators: { [index: string]: { [index: string]: any } };
multivalued: boolean;
defaultValue: string;
}

export interface UserProfileMetadata {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3156,6 +3156,8 @@ bruteForceMode=Brute Force Mode
error-invalid-multivalued-size=Attribute {{0}} must have at least {{1}} and at most {{2}} value(s).
multivalued=Multivalued
multivaluedHelp=If this attribute supports multiple values. This setting is an indicator and does not enable any validation.
defaultValue=Default value
defaultValueHelp=Default value when attribute value is not specified.
to the attribute. For that, make sure to use any of the built-in validators to properly validate the size and the values.
sendIdTokenOnLogout=Send 'id_token_hint' in logout requests
sendIdTokenOnLogoutHelp=If the 'id_token_hint' parameter should be sent in logout requests.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export default function NewAttributeSettings() {
selector,
required,
multivalued,
defaultValue,
...values
} = config.attributes!.find(
(attribute) => attribute.name === attributeName,
Expand Down Expand Up @@ -180,6 +181,7 @@ export default function NewAttributeSettings() {
);
form.setValue("isRequired", required !== undefined);
form.setValue("multivalued", multivalued === true);
form.setValue("defaultValue", defaultValue);
},
[],
);
Expand Down Expand Up @@ -229,6 +231,9 @@ export default function NewAttributeSettings() {
annotations,
validations,
},
formFields.defaultValue
? { defaultValue: formFields.defaultValue }
: { defaultValue: null },
formFields.isRequired ? { required: formFields.required } : undefined,
formFields.group ? { group: formFields.group } : { group: null },
);
Expand All @@ -247,6 +252,9 @@ export default function NewAttributeSettings() {
annotations,
validations,
},
formFields.defaultValue
? { defaultValue: formFields.defaultValue }
: { defaultValue: null },
formFields.isRequired ? { required: formFields.required } : undefined,
formFields.group ? { group: formFields.group } : undefined,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export const AttributeGeneralSettings = () => {
</SelectOption>
));

const ROOT_ATTRIBUTE = [...USERNAME_EMAIL, "firstName", "lastName"];

return (
<FormProvider {...form}>
<FormAccess role="manage-realm" isHorizontal>
Expand Down Expand Up @@ -139,6 +141,13 @@ export const AttributeGeneralSettings = () => {
label={t("multivalued")}
labelIcon={t("multivaluedHelp")}
/>
{!ROOT_ATTRIBUTE.includes(attributeName) && (
<TextControl
name="defaultValue"
label={t("defaultValue")}
labelIcon={t("defaultValueHelp")}
/>
)}
<SelectControl
name="group"
label={t("attributeGroup")}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface UserProfileAttribute {
displayName?: string;
group?: string;
multivalued?: boolean;
defaultValue?: string;
}
export interface UserProfileAttributeRequired {
roles?: string[];
Expand Down Expand Up @@ -43,6 +44,7 @@ export interface UserProfileAttributeMetadata {
annotations?: Record<string, unknown>;
validators?: Record<string, Record<string, unknown>>;
multivalued?: boolean;
defaultValue?: string;
}

export interface UserProfileAttributeGroupMetadata {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const MultiInputComponent = ({
form={form}
aria-label={labelAttribute(t, attribute)}
name={fieldName(attribute.name)!}
defaultValue={[attribute.defaultValue || ""]}
addButtonLabel={t("addMultivaluedLabel", {
fieldLabel: labelAttribute(t, attribute),
})}
Expand Down
2 changes: 1 addition & 1 deletion js/libs/ui-shared/src/user-profile/OptionsComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const OptionComponent = (props: UserProfileFieldProps) => {
<Controller
name={fieldName(attribute.name)}
control={form.control}
defaultValue=""
defaultValue={attribute.defaultValue}
render={({ field }) => (
<>
{options.map((option) => (
Expand Down
2 changes: 1 addition & 1 deletion js/libs/ui-shared/src/user-profile/SelectComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const SelectComponent = (props: UserProfileFieldProps) => {
<UserProfileGroup {...props}>
<Controller
name={fieldName(attribute.name)}
defaultValue=""
defaultValue={attribute.defaultValue}
control={form.control}
render={({ field }) => (
<KeycloakSelect
Expand Down
1 change: 1 addition & 0 deletions js/libs/ui-shared/src/user-profile/TextAreaComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const TextAreaComponent = (props: UserProfileFieldProps) => {
rows={attribute.annotations?.["inputTypeRows"] as number}
readOnly={attribute.readOnly}
isRequired={isRequired}
defaultValue={attribute.defaultValue}
/>
</UserProfileGroup>
);
Expand Down
1 change: 1 addition & 0 deletions js/libs/ui-shared/src/user-profile/TextComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const TextComponent = (props: UserProfileFieldProps) => {
}
isDisabled={attribute.readOnly}
isRequired={isRequired}
defaultValue={attribute.defaultValue}
{...form.register(fieldName(attribute.name))}
/>
</UserProfileGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,10 +420,10 @@ private Map<String, List<String>> normalizeAttributes(Map<String, ?> attributes)
AttributeMetadata metadata = metadataByAttribute.get(attributeName);

if (user != null && isIncludeAttributeIfNotProvided(metadata)) {
values = normalizeAttributeValues(attributeName, user.getAttributes().getOrDefault(attributeName, EMPTY_VALUE));
values = user.getAttributes().getOrDefault(attributeName, EMPTY_VALUE);
}

newAttributes.put(attributeName, values);
newAttributes.put(attributeName, normalizeAttributeValues(attributeName, values));
}

if (user != null) {
Expand Down Expand Up @@ -468,10 +468,16 @@ protected List<String> normalizeAttributeValues(String name, Object value) {
if (value instanceof String) {
values = Collections.singletonList((String) value);
} else {
values = (List<String>) value;
values = value == null ? EMPTY_VALUE : (List<String>) value;
}

Stream<String> valuesStream = Optional.ofNullable(values).orElse(EMPTY_VALUE).stream().filter(Objects::nonNull);
AttributeMetadata metadata = metadataByAttribute.get(name);

if (values.isEmpty() && metadata != null && metadata.getDefaultValue() != null) {
values = List.of(metadata.getDefaultValue());
}

Stream<String> valuesStream = values.stream().filter(Objects::nonNull);

// do not normalize the username if a federated user because we need to respect the format from the external identity store
if ((UserModel.USERNAME.equals(name) && !isFederated()) || UserModel.EMAIL.equals(name)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ private static UserProfileAttributeMetadata toRestMetadata(AttributeMetadata am,
group,
attributes.getAnnotations(am.getName()),
toValidatorMetadata(am, session),
am.isMultivalued());
am.isMultivalued(),
am.getDefaultValue());
}

private static Map<String, Map<String, Object>> toValidatorMetadata(AttributeMetadata am, KeycloakSession session){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public class AttributeMetadata {
private Map<String, Object> annotations;
private int guiOrder;
private boolean multivalued;
private String defaultValue;
private Function<AttributeContext, Map<String, Object>> annotationDecorator = (c) -> c.getMetadata().getAnnotations();

AttributeMetadata(String attributeName, int guiOrder) {
Expand Down Expand Up @@ -116,6 +117,10 @@ public String getName() {
return attributeName;
}

public String getDefaultValue() {
return defaultValue;
}

public int getGuiOrder() {
return guiOrder;
}
Expand Down Expand Up @@ -226,6 +231,7 @@ public AttributeMetadata clone() {
cloned.setAttributeGroupMetadata(attributeGroupMetadata.clone());
}
cloned.setMultivalued(multivalued);
cloned.setDefaultValue(defaultValue);
cloned.setAnnotationDecorator(annotationDecorator);
return cloned;
}
Expand Down Expand Up @@ -273,6 +279,11 @@ public AttributeMetadata setValidators(List<AttributeValidatorMetadata> validato
return this;
}

public AttributeMetadata setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}

public Map<String, Object> getAnnotations(AttributeContext context) {
return annotationDecorator.apply(context);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ public boolean isMultivalued() {
return metadata.isMultivalued();
}

public String getDefaultValue() {
return metadata.getDefaultValue();
}

public String getValue() {
List<String> v = getValues();
if (v == null || v.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -398,13 +398,15 @@ public boolean test(AttributeContext context) {
.addWriteCondition(writeAllowed)
.addValidators(validators)
.setRequired(required)
.setDefaultValue(attrConfig.getDefaultValue())
.setMultivalued(attrConfig.isMultivalued());
}
} else {
decoratedMetadata.addAttribute(attributeName, guiOrder, validators, selector, writeAllowed, required, readAllowed)
.addAnnotations(annotations)
.setAttributeDisplayName(attrConfig.getDisplayName())
.setAttributeGroupMetadata(groupMetadata)
.setDefaultValue(attrConfig.getDefaultValue())
.setMultivalued(attrConfig.isMultivalued());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.keycloak.userprofile.config;

import static org.keycloak.common.util.ObjectUtil.isBlank;
import static org.keycloak.userprofile.UserProfileUtil.isRootAttribute;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
Expand Down Expand Up @@ -45,6 +46,7 @@
import org.keycloak.representations.userprofile.config.UPConfig;
import org.keycloak.userprofile.UserProfileConstants;
import org.keycloak.util.JsonSerialization;
import org.keycloak.validate.ValidationContext;
import org.keycloak.validate.ValidationResult;
import org.keycloak.validate.ValidatorConfig;
import org.keycloak.validate.Validators;
Expand Down Expand Up @@ -148,7 +150,7 @@ private static List<String> validateRootAttributes(UPConfig config) {
}

List<String> errors = new ArrayList<>();
List<String> attributeNames = attributes.stream().map(UPAttribute::getName).collect(Collectors.toList());
List<String> attributeNames = attributes.stream().map(UPAttribute::getName).toList();

for (String name : Arrays.asList(UserModel.USERNAME, UserModel.EMAIL)) {
if (!attributeNames.contains(name)) {
Expand Down Expand Up @@ -184,6 +186,7 @@ private static void validateAttribute(KeycloakSession session, UPAttribute attri
}
if (attributeConfig.getValidations() != null) {
attributeConfig.getValidations().forEach((validator, validatorConfig) -> validateValidationConfig(session, validator, validatorConfig, attributeName, errors));
validateDefaultValue(session, attributeConfig, errors);
}
if (attributeConfig.getPermissions() != null) {
if (attributeConfig.getPermissions().getView() != null) {
Expand Down Expand Up @@ -212,6 +215,27 @@ private static void validateAttribute(KeycloakSession session, UPAttribute attri
}
}

private static void validateDefaultValue(KeycloakSession session, UPAttribute attributeConfig, List<String> errors) {
String defaultValue = attributeConfig.getDefaultValue();

if (defaultValue == null) {
return;
}

String attributeName = attributeConfig.getName();

if (isRootAttribute(attributeName)) {
errors.add("Default value not supported for attribute '" + attributeName + "'");
} else {
attributeConfig.getValidations().forEach((validator, validatorConfig) -> {
ValidationContext context = Validators.validator(session, validator).validate(defaultValue, attributeName, ValidatorConfig.configFromMap(validatorConfig));
if (!context.isValid()) {
errors.add("Default value for attribute '" + attributeName + "' is invalid");
}
});
}
}

private static void validateAnnotations(Map<String, Object> annotations, List<String> errors, String attributeName) {
if (annotations.containsKey("inputOptions") && !(annotations.get("inputOptions") instanceof List)) {
errors.add(new StringBuilder("Annotation 'inputOptions' configured for attribute '").append(attributeName).append("' must be an array of values!'").toString());
Expand Down
Loading
0