Search in sources :

Example 1 with UserProfile

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

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

the class UserResource method getUser.

/**
 * Get representation of the user
 *
 * @return
 */
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public UserRepresentation getUser() {
    auth.users().requireView(user);
    UserRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, user);
    if (realm.isIdentityFederationEnabled()) {
        List<FederatedIdentityRepresentation> reps = getFederatedIdentities(user).collect(Collectors.toList());
        rep.setFederatedIdentities(reps);
    }
    if (session.getProvider(BruteForceProtector.class).isTemporarilyDisabled(session, realm, user)) {
        rep.setEnabled(false);
    }
    rep.setAccess(auth.users().getAccess(user));
    UserProfileProvider provider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = provider.create(USER_API, user);
    Map<String, List<String>> readableAttributes = profile.getAttributes().getReadable(false);
    if (rep.getAttributes() != null) {
        rep.setAttributes(readableAttributes);
    }
    return rep;
}
Also used : UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 3 with UserProfile

use of org.keycloak.userprofile.UserProfile 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);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 4 with UserProfile

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

the class RegistrationUserCreation method success.

@Override
public void success(FormContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String email = formData.getFirst(UserModel.EMAIL);
    String username = formData.getFirst(UserModel.USERNAME);
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        username = email;
    }
    context.getEvent().detail(Details.USERNAME, username).detail(Details.REGISTER_METHOD, "form").detail(Details.EMAIL, email);
    KeycloakSession session = context.getSession();
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.REGISTRATION_USER_CREATION, formData);
    UserModel user = profile.create();
    user.setEnabled(true);
    context.setUser(user);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId()).detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri()).detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserProfile(org.keycloak.userprofile.UserProfile) KeycloakSession(org.keycloak.models.KeycloakSession) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider)

Example 5 with UserProfile

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

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