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();
}
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;
}
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);
}
}
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);
}
}
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();
}
Aggregations