Java Code Examples for org.keycloak.models.UserModel#setFirstName()

The following examples show how to use org.keycloak.models.UserModel#setFirstName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FailableHardcodedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public UserModel getUserByUsername(String uname, RealmModel realm) {
    checkForceFail();
    if (!username.equals(uname)) return null;
    UserModel local = session.userLocalStorage().getUserByUsername(uname, realm);
    if (local != null && !model.getId().equals(local.getFederationLink())) {
        throw new RuntimeException("local storage has wrong federation link");
    }
    if (local != null) return new Delegate(local);
    local = session.userLocalStorage().addUser(realm, uname);
    local.setEnabled(true);
    local.setFirstName(first);
    local.setLastName(last);
    local.setEmail(email);
    local.setFederationLink(model.getId());
    for (String key : attributes.keySet()) {
        List<String> values = attributes.get(key);
        if (values == null) continue;
        local.setAttribute(key, values);
    }
    return new Delegate(local);
}
 
Example 2
Source File: FullNameLDAPStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) {
    if (isWriteOnly()) {
        return;
    }

    String ldapFullNameAttrName = getLdapFullNameAttrName();
    String fullName = ldapUser.getAttributeAsString(ldapFullNameAttrName);
    if (fullName == null) {
        return;
    }

    fullName = fullName.trim();
    if (!fullName.isEmpty()) {
        int lastSpaceIndex = fullName.lastIndexOf(" ");
        if (lastSpaceIndex == -1) {
            user.setLastName(fullName);
        } else {
            user.setFirstName(fullName.substring(0, lastSpaceIndex));
            user.setLastName(fullName.substring(lastSpaceIndex + 1));
        }
    }
}
 
Example 3
Source File: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private UserModel createUserModel(RealmModel realm, String rawUsername) throws NotFoundException {

        String username = rawUsername.toLowerCase().trim();
        FederatedUserModel remoteUser = federatedUserService.getUserDetails(username);
        LOG.infof("Creating user model for: %s", username);
        UserModel userModel = session.userStorage().addUser(realm, username);

        if (!username.equals(remoteUser.getEmail())) {
            throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", username, remoteUser.getUsername()));
        }

        userModel.setFederationLink(model.getId());
        userModel.setEnabled(remoteUser.isEnabled());
        userModel.setEmail(username);
        userModel.setEmailVerified(remoteUser.isEmailVerified());
        userModel.setFirstName(remoteUser.getFirstName());
        userModel.setLastName(remoteUser.getLastName());

        if (remoteUser.getAttributes() != null) {
            Map<String, List<String>> attributes = remoteUser.getAttributes();
            for (String attributeName : attributes.keySet())
                userModel.setAttribute(attributeName, attributes.get(attributeName));
        }

        if (remoteUser.getRoles() != null) {
            for (String role : remoteUser.getRoles()) {
                RoleModel roleModel = realm.getRole(role);
                if (roleModel != null) {
                    userModel.grantRole(roleModel);
                    LOG.infof("Granted user %s, role %s", username, role);
                }
            }
        }

        return userModel;
    }
 
Example 4
Source File: RegistrationProfile.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {
    UserModel user = context.getUser();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    user.setFirstName(formData.getFirst(RegistrationPage.FIELD_FIRST_NAME));
    user.setLastName(formData.getFirst(RegistrationPage.FIELD_LAST_NAME));
    user.setEmail(formData.getFirst(RegistrationPage.FIELD_EMAIL));
}
 
Example 5
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    convertDeprecatedSocialProviders(userRep);

    // Import users just to user storage. Don't federate
    UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
    user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
    user.setCreatedTimestamp(userRep.getCreatedTimestamp());
    user.setEmail(userRep.getEmail());
    if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
    user.setFirstName(userRep.getFirstName());
    user.setLastName(userRep.getLastName());
    user.setFederationLink(userRep.getFederationLink());
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            List<String> value = entry.getValue();
            if (value != null) {
                user.setAttribute(entry.getKey(), new ArrayList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String requiredAction : userRep.getRequiredActions()) {
            try {
                user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
            } catch (IllegalArgumentException iae) {
                user.addRequiredAction(requiredAction);
            }
        }
    }
    createCredentials(userRep, session, newRealm, user, false);
    createFederatedIdentities(userRep, session, newRealm, user);
    createRoleMappings(userRep, user, newRealm);
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            session.users().addConsent(newRealm, user.getId(), consentModel);
        }
    }

    if (userRep.getNotBefore() != null) {
        session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
    }

    if (userRep.getServiceAccountClientId() != null) {
        String clientId = userRep.getServiceAccountClientId();
        ClientModel client = newRealm.getClientByClientId(clientId);
        if (client == null) {
            throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
        }
        user.setServiceAccountClientLink(client.getId());
    }
    createGroups(userRep, newRealm, user);
    return user;
}
 
Example 6
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {

    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();

    if (context.getAuthenticationSession().getAuthNote(EXISTING_USER_INFO) != null) {
        context.attempted();
        return;
    }

    String username = getUsername(context, serializedCtx, brokerContext);
    if (username == null) {
        ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username");
        context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        context.resetFlow();
        return;
    }

    ExistingUserInfo duplication = checkExistingUser(context, username, serializedCtx, brokerContext);

    if (duplication == null) {
        logger.debugf("No duplication detected. Creating account for user '%s' and linking with identity provider '%s' .",
                username, brokerContext.getIdpConfig().getAlias());

        UserModel federatedUser = session.users().addUser(realm, username);
        federatedUser.setEnabled(true);
        federatedUser.setEmail(brokerContext.getEmail());
        federatedUser.setFirstName(brokerContext.getFirstName());
        federatedUser.setLastName(brokerContext.getLastName());

        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            federatedUser.setAttribute(attr.getKey(), attr.getValue());
        }

        AuthenticatorConfigModel config = context.getAuthenticatorConfig();
        if (config != null && Boolean.parseBoolean(config.getConfig().get(IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION))) {
            logger.debugf("User '%s' required to update password", federatedUser.getUsername());
            federatedUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
        }

        userRegisteredSuccess(context, federatedUser, serializedCtx, brokerContext);

        context.setUser(federatedUser);
        context.getAuthenticationSession().setAuthNote(BROKER_REGISTERED_NEW_USER, "true");
        context.success();
    } else {
        logger.debugf("Duplication detected. There is already existing user with %s '%s' .",
                duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue());

        // Set duplicated user, so next authenticators can deal with it
        context.getAuthenticationSession().setAuthNote(EXISTING_USER_INFO, duplication.serialize());
        //Only show error message if the authenticator was required
        if (context.getExecution().isRequired()) {
            Response challengeResponse = context.form()
                    .setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .createErrorPage(Response.Status.CONFLICT);
            context.challenge(challengeResponse);
            context.getEvent()
                    .user(duplication.getExistingUserId())
                    .detail("existing_" + duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .removeDetail(Details.AUTH_METHOD)
                    .removeDetail(Details.AUTH_TYPE)
                    .error(Errors.FEDERATED_IDENTITY_EXISTS);
        } else {
            context.attempted();
        }
    }
}
 
Example 7
Source File: AccountFormService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Update account information.
 * <p>
 * Form params:
 * <p>
 * firstName
 * lastName
 * email
 *
 * @param formData
 * @return
 */
@Path("/")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processAccountUpdate(final MultivaluedMap<String, String> formData) {
    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());

    List<FormMessage> errors = Validation.validateUpdateProfileForm(realm, formData);
    if (errors != null && !errors.isEmpty()) {
        setReferrerOnPage();
        return account.setErrors(Status.OK, errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
    }

    try {
        updateUsername(formData.getFirst("username"), user, session);
        updateEmail(formData.getFirst("email"), user, session, event);

        user.setFirstName(formData.getFirst("firstName"));
        user.setLastName(formData.getFirst("lastName"));

        AttributeFormDataProcessor.process(formData, realm, user);

        event.success();

        setReferrerOnPage();
        return account.setSuccess(Messages.ACCOUNT_UPDATED).createResponse(AccountPages.ACCOUNT);
    } catch (ReadOnlyException roe) {
        setReferrerOnPage();
        return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
    } catch (ModelDuplicateException mde) {
        setReferrerOnPage();
        return account.setError(Response.Status.CONFLICT, mde.getMessage()).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
    }
}