Search in sources :

Example 6 with Company

use of com.liferay.portal.model.Company in project liferay-ide by liferay.

the class UserLocalServiceImpl method addDefaultGroups.

/**
 * Adds the user to the default groups, unless the user is already in these
 * groups. The default groups can be specified in
 * <code>portal.properties</code> with the key
 * <code>admin.default.group.names</code>.
 *
 * @param  userId the primary key of the user
 * @throws PortalException if a user with the primary key could not be found
 * @throws SystemException if a system exception occurred
 */
@Override
public void addDefaultGroups(long userId) throws PortalException, SystemException {
    User user = userPersistence.findByPrimaryKey(userId);
    Set<Long> groupIdsSet = new HashSet<Long>();
    String[] defaultGroupNames = PrefsPropsUtil.getStringArray(user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES, StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
    for (String defaultGroupName : defaultGroupNames) {
        Company company = companyPersistence.findByPrimaryKey(user.getCompanyId());
        Account account = company.getAccount();
        if (StringUtil.equalsIgnoreCase(defaultGroupName, account.getName())) {
            defaultGroupName = GroupConstants.GUEST;
        }
        Group group = groupPersistence.fetchByC_N(user.getCompanyId(), defaultGroupName);
        if ((group != null) && !userPersistence.containsGroup(userId, group.getGroupId())) {
            groupIdsSet.add(group.getGroupId());
        }
    }
    String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES, StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
    for (String defaultOrganizationGroupName : defaultOrganizationGroupNames) {
        defaultOrganizationGroupName += GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
        Group group = groupPersistence.fetchByC_N(user.getCompanyId(), defaultOrganizationGroupName);
        if ((group != null) && !userPersistence.containsGroup(userId, group.getGroupId())) {
            groupIdsSet.add(group.getGroupId());
        }
    }
    long[] groupIds = ArrayUtil.toArray(groupIdsSet.toArray(new Long[groupIdsSet.size()]));
    groupLocalService.addUserGroups(userId, groupIds);
}
Also used : Account(com.liferay.portal.model.Account) Group(com.liferay.portal.model.Group) UserGroup(com.liferay.portal.model.UserGroup) Company(com.liferay.portal.model.Company) User(com.liferay.portal.model.User) HashSet(java.util.HashSet)

Example 7 with Company

use of com.liferay.portal.model.Company in project liferay-ide by liferay.

the class UserLocalServiceImpl method sendPassword.

/**
 * Sends the password email to the user with the email address. The content
 * of this email can be specified in <code>portal.properties</code> with the
 * <code>admin.email.password</code> keys.
 *
 * @param  companyId the primary key of the user's company
 * @param  emailAddress the user's email address
 * @param  fromName the name of the individual that the email should be from
 * @param  fromAddress the address of the individual that the email should
 *         be from
 * @param  subject the email subject. If <code>null</code>, the subject
 *         specified in <code>portal.properties</code> will be used.
 * @param  body the email body. If <code>null</code>, the body specified in
 *         <code>portal.properties</code> will be used.
 * @param  serviceContext the service context to be applied
 * @throws PortalException if a user with the email address could not be
 *         found
 * @throws SystemException if a system exception occurred
 */
@Override
public void sendPassword(long companyId, String emailAddress, String fromName, String fromAddress, String subject, String body, ServiceContext serviceContext) throws PortalException, SystemException {
    Company company = companyPersistence.findByPrimaryKey(companyId);
    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
        return;
    }
    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
    if (Validator.isNull(emailAddress)) {
        throw new UserEmailAddressException();
    }
    User user = userPersistence.findByC_EA(companyId, emailAddress);
    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
    String newPassword = StringPool.BLANK;
    String passwordResetURL = StringPool.BLANK;
    if (company.isSendPasswordResetLink()) {
        Date expirationDate = null;
        if ((passwordPolicy != null) && (passwordPolicy.getResetTicketMaxAge() > 0)) {
            expirationDate = new Date(System.currentTimeMillis() + (passwordPolicy.getResetTicketMaxAge() * 1000));
        }
        Ticket ticket = ticketLocalService.addTicket(companyId, User.class.getName(), user.getUserId(), TicketConstants.TYPE_PASSWORD, null, expirationDate, serviceContext);
        passwordResetURL = serviceContext.getPortalURL() + serviceContext.getPathMain() + "/portal/update_password?p_l_id=" + serviceContext.getPlid() + "&ticketKey=" + ticket.getKey();
    } else {
        if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(PasswordEncryptorUtil.TYPE_NONE)) {
            if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler(5);
                    sb.append("When LDAP password policy is enabled, ");
                    sb.append("it is possible that portal generated ");
                    sb.append("passwords will not match the LDAP policy.");
                    sb.append("Using RegExpToolkit to generate new ");
                    sb.append("password.");
                    _log.warn(sb.toString());
                }
                RegExpToolkit regExpToolkit = new RegExpToolkit();
                newPassword = regExpToolkit.generate(null);
            } else {
                newPassword = PwdToolkitUtil.generate(passwordPolicy);
            }
            boolean passwordReset = false;
            if (passwordPolicy.getChangeable() && passwordPolicy.getChangeRequired()) {
                passwordReset = true;
            }
            user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
            user.setPasswordUnencrypted(newPassword);
            user.setPasswordEncrypted(true);
            user.setPasswordReset(passwordReset);
            user.setPasswordModified(true);
            user.setPasswordModifiedDate(new Date());
            userPersistence.update(user);
            user.setPasswordModified(false);
        } else {
            newPassword = user.getPassword();
        }
    }
    if (Validator.isNull(fromName)) {
        fromName = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
    }
    if (Validator.isNull(fromAddress)) {
        fromAddress = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
    }
    String toName = user.getFullName();
    String toAddress = user.getEmailAddress();
    if (Validator.isNull(subject)) {
        if (company.isSendPasswordResetLink()) {
            subject = PrefsPropsUtil.getContent(companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
        } else {
            subject = PrefsPropsUtil.getContent(companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
        }
    }
    if (Validator.isNull(body)) {
        if (company.isSendPasswordResetLink()) {
            body = PrefsPropsUtil.getContent(companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
        } else {
            body = PrefsPropsUtil.getContent(companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
        }
    }
    SubscriptionSender subscriptionSender = new SubscriptionSender();
    subscriptionSender.setBody(body);
    subscriptionSender.setCompanyId(companyId);
    subscriptionSender.setContextAttributes("[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]", user.getScreenName());
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);
    subscriptionSender.setMailId("user", user.getUserId(), System.currentTimeMillis(), PwdGenerator.getPassword());
    subscriptionSender.setServiceContext(serviceContext);
    subscriptionSender.setSubject(subject);
    subscriptionSender.setUserId(user.getUserId());
    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
    subscriptionSender.flushNotificationsAsync();
}
Also used : Ticket(com.liferay.portal.model.Ticket) Company(com.liferay.portal.model.Company) User(com.liferay.portal.model.User) UserEmailAddressException(com.liferay.portal.UserEmailAddressException) ReservedUserEmailAddressException(com.liferay.portal.ReservedUserEmailAddressException) DuplicateUserEmailAddressException(com.liferay.portal.DuplicateUserEmailAddressException) PasswordPolicy(com.liferay.portal.model.PasswordPolicy) RegExpToolkit(com.liferay.portal.security.pwd.RegExpToolkit) Date(java.util.Date) StringBundler(com.liferay.portal.kernel.util.StringBundler) SubscriptionSender(com.liferay.portal.util.SubscriptionSender)

Example 8 with Company

use of com.liferay.portal.model.Company in project liferay-ide by liferay.

the class UserLocalServiceImpl method updateUser.

/**
 * Updates the user.
 *
 * @param  userId the primary key of the user
 * @param  oldPassword the user's old password
 * @param  newPassword1 the user's new password (optionally
 *         <code>null</code>)
 * @param  newPassword2 the user's new password confirmation (optionally
 *         <code>null</code>)
 * @param  passwordReset whether the user should be asked to reset their
 *         password the next time they login
 * @param  reminderQueryQuestion the user's new password reset question
 * @param  reminderQueryAnswer the user's new password reset answer
 * @param  screenName the user's new screen name
 * @param  emailAddress the user's new email address
 * @param  facebookId the user's new Facebook ID
 * @param  openId the user's new OpenID
 * @param  languageId the user's new language ID
 * @param  timeZoneId the user's new time zone ID
 * @param  greeting the user's new greeting
 * @param  comments the user's new comments
 * @param  firstName the user's new first name
 * @param  middleName the user's new middle name
 * @param  lastName the user's new last name
 * @param  prefixId the user's new name prefix ID
 * @param  suffixId the user's new name suffix ID
 * @param  male whether user is male
 * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
 *         for January)
 * @param  birthdayDay the user's new birthday day
 * @param  birthdayYear the user's birthday year
 * @param  smsSn the user's new SMS screen name
 * @param  aimSn the user's new AIM screen name
 * @param  facebookSn the user's new Facebook screen name
 * @param  icqSn the user's new ICQ screen name
 * @param  jabberSn the user's new Jabber screen name
 * @param  msnSn the user's new MSN screen name
 * @param  mySpaceSn the user's new MySpace screen name
 * @param  skypeSn the user's new Skype screen name
 * @param  twitterSn the user's new Twitter screen name
 * @param  ymSn the user's new Yahoo! Messenger screen name
 * @param  jobTitle the user's new job title
 * @param  groupIds the primary keys of the user's groups
 * @param  organizationIds the primary keys of the user's organizations
 * @param  roleIds the primary keys of the user's roles
 * @param  userGroupRoles the user user's group roles
 * @param  userGroupIds the primary keys of the user's user groups
 * @param  serviceContext the service context to be applied (optionally
 *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
 *         attribute), asset category IDs, asset tag names, and expando
 *         bridge attributes for the user.
 * @return the user
 * @throws PortalException if a user with the primary key could not be found
 *         or if the new information was invalid
 * @throws SystemException if a system exception occurred
 */
@Override
@SuppressWarnings("deprecation")
public User updateUser(long userId, String oldPassword, String newPassword1, String newPassword2, boolean passwordReset, String reminderQueryQuestion, String reminderQueryAnswer, String screenName, String emailAddress, long facebookId, String openId, String languageId, String timeZoneId, String greeting, String comments, String firstName, String middleName, String lastName, int prefixId, int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn, String aimSn, String facebookSn, String icqSn, String jabberSn, String msnSn, String mySpaceSn, String skypeSn, String twitterSn, String ymSn, String jobTitle, long[] groupIds, long[] organizationIds, long[] roleIds, List<UserGroupRole> userGroupRoles, long[] userGroupIds, ServiceContext serviceContext) throws PortalException, SystemException {
    // User
    User user = userPersistence.findByPrimaryKey(userId);
    Company company = companyPersistence.findByPrimaryKey(user.getCompanyId());
    String password = oldPassword;
    screenName = getLogin(screenName);
    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
    openId = openId.trim();
    String oldFullName = user.getFullName();
    aimSn = StringUtil.toLowerCase(aimSn.trim());
    facebookSn = StringUtil.toLowerCase(facebookSn.trim());
    icqSn = StringUtil.toLowerCase(icqSn.trim());
    jabberSn = StringUtil.toLowerCase(jabberSn.trim());
    msnSn = StringUtil.toLowerCase(msnSn.trim());
    mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
    skypeSn = StringUtil.toLowerCase(skypeSn.trim());
    twitterSn = StringUtil.toLowerCase(twitterSn.trim());
    ymSn = StringUtil.toLowerCase(ymSn.trim());
    Date now = new Date();
    EmailAddressGenerator emailAddressGenerator = EmailAddressGeneratorFactory.getInstance();
    if (emailAddressGenerator.isGenerated(emailAddress)) {
        emailAddress = StringPool.BLANK;
    }
    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED && Validator.isNull(emailAddress)) {
        emailAddress = emailAddressGenerator.generate(user.getCompanyId(), userId);
    }
    validate(userId, screenName, emailAddress, openId, firstName, middleName, lastName, smsSn);
    if (Validator.isNotNull(newPassword1) || Validator.isNotNull(newPassword2)) {
        user = updatePassword(userId, newPassword1, newPassword2, passwordReset);
        password = newPassword1;
        user.setDigest(StringPool.BLANK);
    }
    user.setModifiedDate(now);
    if (user.getContactId() <= 0) {
        user.setContactId(counterLocalService.increment());
    }
    user.setPasswordReset(passwordReset);
    if (Validator.isNotNull(reminderQueryQuestion) && Validator.isNotNull(reminderQueryAnswer)) {
        user.setReminderQueryQuestion(reminderQueryQuestion);
        user.setReminderQueryAnswer(reminderQueryAnswer);
    }
    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
        user.setScreenName(screenName);
        user.setDigest(StringPool.BLANK);
    }
    boolean sendEmailAddressVerification = false;
    if (!company.isStrangersVerify()) {
        setEmailAddress(user, password, firstName, middleName, lastName, emailAddress);
    } else {
        sendEmailAddressVerification = true;
    }
    if (serviceContext != null) {
        String uuid = serviceContext.getUuid();
        if (Validator.isNotNull(uuid)) {
            user.setUuid(uuid);
        }
    }
    user.setFacebookId(facebookId);
    Long ldapServerId = (Long) serviceContext.getAttribute("ldapServerId");
    if (ldapServerId != null) {
        user.setLdapServerId(ldapServerId);
    }
    user.setOpenId(openId);
    user.setLanguageId(languageId);
    user.setTimeZoneId(timeZoneId);
    user.setGreeting(greeting);
    user.setComments(comments);
    user.setFirstName(firstName);
    user.setMiddleName(middleName);
    user.setLastName(lastName);
    user.setJobTitle(jobTitle);
    user.setExpandoBridgeAttributes(serviceContext);
    userPersistence.update(user, serviceContext);
    // Contact
    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
    long contactId = user.getContactId();
    Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
    if (contact == null) {
        contact = contactPersistence.create(contactId);
        contact.setCompanyId(user.getCompanyId());
        contact.setUserName(StringPool.BLANK);
        contact.setCreateDate(now);
        contact.setClassName(User.class.getName());
        contact.setClassPK(user.getUserId());
        contact.setAccountId(company.getAccountId());
        contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
    }
    contact.setModifiedDate(now);
    contact.setEmailAddress(user.getEmailAddress());
    contact.setFirstName(firstName);
    contact.setMiddleName(middleName);
    contact.setLastName(lastName);
    contact.setPrefixId(prefixId);
    contact.setSuffixId(suffixId);
    contact.setMale(male);
    contact.setBirthday(birthday);
    contact.setSmsSn(smsSn);
    contact.setAimSn(aimSn);
    contact.setFacebookSn(facebookSn);
    contact.setIcqSn(icqSn);
    contact.setJabberSn(jabberSn);
    contact.setMsnSn(msnSn);
    contact.setMySpaceSn(mySpaceSn);
    contact.setSkypeSn(skypeSn);
    contact.setTwitterSn(twitterSn);
    contact.setYmSn(ymSn);
    contact.setJobTitle(jobTitle);
    contactPersistence.update(contact, serviceContext);
    // Group
    Group group = groupLocalService.getUserGroup(user.getCompanyId(), userId);
    group.setFriendlyURL(StringPool.SLASH + screenName);
    groupPersistence.update(group);
    // Groups and organizations
    // See LPS-33205. Cache the user's list of user group roles because
    // adding or removing groups may add or remove user group roles
    // depending on the site default user associations.
    List<UserGroupRole> previousUserGroupRoles = userGroupRolePersistence.findByUserId(userId);
    updateGroups(userId, groupIds, serviceContext, false);
    updateOrganizations(userId, organizationIds, false);
    if (roleIds != null) {
        roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
        userPersistence.setRoles(userId, roleIds);
    }
    // User group roles
    updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles, previousUserGroupRoles);
    if (userGroupIds != null) {
        if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
            userGroupLocalService.copyUserGroupLayouts(userGroupIds, userId);
        }
        userPersistence.setUserGroups(userId, userGroupIds);
    }
    // Announcements
    announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
    if (serviceContext != null) {
        updateAsset(userId, user, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
    }
    if (GetterUtil.getBoolean(PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) && !oldFullName.equals(user.getFullName())) {
        mbMessageLocalService.updateUserName(userId, user.getFullName());
    }
    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
        indexer.reindex(user);
    }
    if ((serviceContext != null) && sendEmailAddressVerification) {
        sendEmailAddressVerification(user, emailAddress, serviceContext);
    }
    // Permission cache
    PermissionCacheUtil.clearCache();
    return user;
}
Also used : UserGroupRole(com.liferay.portal.model.UserGroupRole) Group(com.liferay.portal.model.Group) UserGroup(com.liferay.portal.model.UserGroup) Company(com.liferay.portal.model.Company) User(com.liferay.portal.model.User) Date(java.util.Date) Contact(com.liferay.portal.model.Contact) EmailAddressGenerator(com.liferay.portal.security.auth.EmailAddressGenerator) Indexer(com.liferay.portal.kernel.search.Indexer) MBMessage(com.liferay.portlet.messageboards.model.MBMessage)

Example 9 with Company

use of com.liferay.portal.model.Company in project liferay-ide by liferay.

the class UserLocalServiceImpl method addUserWithWorkflow.

/**
 * Adds a user with workflow.
 *
 * <p>
 * This method handles the creation and bookkeeping of the user including
 * its resources, metadata, and internal data structures. It is not
 * necessary to make subsequent calls to any methods to setup default
 * groups, resources, etc.
 * </p>
 *
 * @param  creatorUserId the primary key of the creator
 * @param  companyId the primary key of the user's company
 * @param  autoPassword whether a password should be automatically generated
 *         for the user
 * @param  password1 the user's password
 * @param  password2 the user's password confirmation
 * @param  autoScreenName whether a screen name should be automatically
 *         generated for the user
 * @param  screenName the user's screen name
 * @param  emailAddress the user's email address
 * @param  facebookId the user's facebook ID
 * @param  openId the user's OpenID
 * @param  locale the user's locale
 * @param  firstName the user's first name
 * @param  middleName the user's middle name
 * @param  lastName the user's last name
 * @param  prefixId the user's name prefix ID
 * @param  suffixId the user's name suffix ID
 * @param  male whether the user is male
 * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
 *         January)
 * @param  birthdayDay the user's birthday day
 * @param  birthdayYear the user's birthday year
 * @param  jobTitle the user's job title
 * @param  groupIds the primary keys of the user's groups
 * @param  organizationIds the primary keys of the user's organizations
 * @param  roleIds the primary keys of the roles this user possesses
 * @param  userGroupIds the primary keys of the user's user groups
 * @param  sendEmail whether to send the user an email notification about
 *         their new account
 * @param  serviceContext the service context to be applied (optionally
 *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
 *         attribute), asset category IDs, asset tag names, and expando
 *         bridge attributes for the user.
 * @return the new user
 * @throws PortalException if the user's information was invalid
 * @throws SystemException if a system exception occurred
 */
@Override
@SuppressWarnings("deprecation")
public User addUserWithWorkflow(long creatorUserId, long companyId, boolean autoPassword, String password1, String password2, boolean autoScreenName, String screenName, String emailAddress, long facebookId, String openId, Locale locale, String firstName, String middleName, String lastName, int prefixId, int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds, long[] organizationIds, long[] roleIds, long[] userGroupIds, boolean sendEmail, ServiceContext serviceContext) throws PortalException, SystemException {
    // User
    Company company = companyPersistence.findByPrimaryKey(companyId);
    screenName = getLogin(screenName);
    openId = StringUtil.trim(openId);
    Date now = new Date();
    if (PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
        autoScreenName = true;
    }
    // PLACEHOLDER 01
    long userId = counterLocalService.increment();
    EmailAddressGenerator emailAddressGenerator = EmailAddressGeneratorFactory.getInstance();
    if ((emailAddress == null) || emailAddressGenerator.isGenerated(emailAddress)) {
        emailAddress = StringPool.BLANK;
    } else {
        emailAddress = StringUtil.toLowerCase(emailAddress.trim());
    }
    if (!PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) && Validator.isNull(emailAddress)) {
        emailAddress = emailAddressGenerator.generate(companyId, userId);
    }
    validate(companyId, userId, autoPassword, password1, password2, autoScreenName, screenName, emailAddress, openId, firstName, middleName, lastName, organizationIds);
    if (!autoPassword) {
        if (Validator.isNull(password1) || Validator.isNull(password2)) {
            throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID);
        }
    }
    if (autoScreenName) {
        ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance();
        try {
            screenName = screenNameGenerator.generate(companyId, userId, emailAddress);
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }
    User defaultUser = getDefaultUser(companyId);
    FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance();
    String fullName = fullNameGenerator.getFullName(firstName, middleName, lastName);
    String greeting = LanguageUtil.format(locale, "welcome-x", " " + fullName, false);
    User user = userPersistence.create(userId);
    if (serviceContext != null) {
        String uuid = serviceContext.getUuid();
        if (Validator.isNotNull(uuid)) {
            user.setUuid(uuid);
        }
    }
    user.setCompanyId(companyId);
    user.setCreateDate(now);
    user.setModifiedDate(now);
    user.setDefaultUser(false);
    user.setContactId(counterLocalService.increment());
    if (Validator.isNotNull(password1)) {
        user.setPassword(PasswordEncryptorUtil.encrypt(password1));
        user.setPasswordUnencrypted(password1);
    }
    user.setPasswordEncrypted(true);
    PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
    boolean passwordReset = false;
    if (passwordPolicy != null) {
        if (passwordPolicy.isChangeable() && passwordPolicy.isChangeRequired()) {
            passwordReset = true;
        }
        addPasswordPolicyUsers(passwordPolicy.getPasswordPolicyId(), new long[] { userId });
    }
    user.setPasswordReset(passwordReset);
    user.setDigest(StringPool.BLANK);
    user.setScreenName(screenName);
    user.setEmailAddress(emailAddress);
    user.setFacebookId(facebookId);
    Long ldapServerId = (Long) serviceContext.getAttribute("ldapServerId");
    if (ldapServerId != null) {
        user.setLdapServerId(ldapServerId);
    } else {
        user.setLdapServerId(-1);
    }
    user.setOpenId(openId);
    user.setLanguageId(LocaleUtil.toLanguageId(locale));
    user.setTimeZoneId(defaultUser.getTimeZoneId());
    user.setGreeting(greeting);
    user.setFirstName(firstName);
    user.setMiddleName(middleName);
    user.setLastName(lastName);
    user.setJobTitle(jobTitle);
    user.setStatus(WorkflowConstants.STATUS_DRAFT);
    user.setExpandoBridgeAttributes(serviceContext);
    userPersistence.update(user, serviceContext);
    // Contact
    String creatorUserName = StringPool.BLANK;
    if (creatorUserId <= 0) {
        creatorUserId = user.getUserId();
    // Don't grab the full name from the User object because it doesn't
    // have a corresponding Contact object yet
    // creatorUserName = user.getFullName();
    } else {
        User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
        creatorUserName = creatorUser.getFullName();
    }
    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
    Contact contact = contactPersistence.create(user.getContactId());
    contact.setCompanyId(user.getCompanyId());
    contact.setUserId(creatorUserId);
    contact.setUserName(creatorUserName);
    contact.setCreateDate(now);
    contact.setModifiedDate(now);
    contact.setClassName(User.class.getName());
    contact.setClassPK(user.getUserId());
    contact.setAccountId(company.getAccountId());
    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
    contact.setEmailAddress(user.getEmailAddress());
    contact.setFirstName(firstName);
    contact.setMiddleName(middleName);
    contact.setLastName(lastName);
    contact.setPrefixId(prefixId);
    contact.setSuffixId(suffixId);
    contact.setMale(male);
    contact.setBirthday(birthday);
    contact.setJobTitle(jobTitle);
    contactPersistence.update(contact, serviceContext);
    // Group
    groupLocalService.addGroup(user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID, User.class.getName(), user.getUserId(), null, null, 0, StringPool.SLASH + screenName, false, true, null);
    if (groupIds != null) {
        List<Group> groups = new ArrayList<Group>();
        for (long groupId : groupIds) {
            Group group = groupLocalService.fetchGroup(groupId);
            if (group != null) {
                groups.add(group);
            } else {
                if (_log.isWarnEnabled()) {
                    _log.warn("Group " + groupId + " does not exist");
                }
            }
        }
        groupLocalService.addUserGroups(userId, groups);
    }
    addDefaultGroups(userId);
    // Organizations
    updateOrganizations(userId, organizationIds, false);
    if (roleIds != null) {
        roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
        userPersistence.setRoles(userId, roleIds);
    }
    addDefaultRoles(userId);
    if (userGroupIds != null) {
        if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
            for (long userGroupId : userGroupIds) {
                userGroupLocalService.copyUserGroupLayouts(userGroupId, new long[] { userId });
            }
        }
        userPersistence.setUserGroups(userId, userGroupIds);
    }
    addDefaultUserGroups(userId);
    // Resources
    resourceLocalService.addResources(companyId, 0, creatorUserId, User.class.getName(), user.getUserId(), false, false, false);
    if (serviceContext != null) {
        updateAsset(creatorUserId, user, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
    }
    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
        reindex(user);
    }
    // Workflow
    long workflowUserId = creatorUserId;
    if (workflowUserId == userId) {
        workflowUserId = defaultUser.getUserId();
    }
    ServiceContext workflowServiceContext = serviceContext;
    if (workflowServiceContext == null) {
        workflowServiceContext = new ServiceContext();
    }
    workflowServiceContext.setAttribute("autoPassword", autoPassword);
    workflowServiceContext.setAttribute("passwordUnencrypted", password1);
    workflowServiceContext.setAttribute("sendEmail", sendEmail);
    WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, workflowUserId, User.class.getName(), userId, user, workflowServiceContext);
    if (serviceContext != null) {
        String passwordUnencrypted = (String) serviceContext.getAttribute("passwordUnencrypted");
        if (Validator.isNotNull(passwordUnencrypted)) {
            user.setPasswordUnencrypted(passwordUnencrypted);
        }
    }
    return user;
}
Also used : Group(com.liferay.portal.model.Group) UserGroup(com.liferay.portal.model.UserGroup) Company(com.liferay.portal.model.Company) User(com.liferay.portal.model.User) ScreenNameGenerator(com.liferay.portal.security.auth.ScreenNameGenerator) ServiceContext(com.liferay.portal.service.ServiceContext) ArrayList(java.util.ArrayList) Date(java.util.Date) ContactFirstNameException(com.liferay.portal.ContactFirstNameException) ModelListenerException(com.liferay.portal.ModelListenerException) NoSuchImageException(com.liferay.portal.NoSuchImageException) GroupFriendlyURLException(com.liferay.portal.GroupFriendlyURLException) DuplicateOpenIdException(com.liferay.portal.DuplicateOpenIdException) ImageSizeException(com.liferay.portlet.documentlibrary.ImageSizeException) PasswordExpiredException(com.liferay.portal.PasswordExpiredException) UserPasswordException(com.liferay.portal.UserPasswordException) NoSuchUserException(com.liferay.portal.NoSuchUserException) UserSmsException(com.liferay.portal.UserSmsException) NoSuchRoleException(com.liferay.portal.NoSuchRoleException) PortalException(com.liferay.portal.kernel.exception.PortalException) UserIdException(com.liferay.portal.UserIdException) UserPortraitTypeException(com.liferay.portal.UserPortraitTypeException) RequiredUserException(com.liferay.portal.RequiredUserException) ReservedUserScreenNameException(com.liferay.portal.ReservedUserScreenNameException) IOException(java.io.IOException) ContactBirthdayException(com.liferay.portal.ContactBirthdayException) UserReminderQueryException(com.liferay.portal.UserReminderQueryException) DuplicateUserScreenNameException(com.liferay.portal.DuplicateUserScreenNameException) UserEmailAddressException(com.liferay.portal.UserEmailAddressException) ContactFullNameException(com.liferay.portal.ContactFullNameException) EncryptorException(com.liferay.util.EncryptorException) CompanyMaxUsersException(com.liferay.portal.CompanyMaxUsersException) NoSuchTicketException(com.liferay.portal.NoSuchTicketException) UserScreenNameException(com.liferay.portal.UserScreenNameException) ContactLastNameException(com.liferay.portal.ContactLastNameException) ReservedUserEmailAddressException(com.liferay.portal.ReservedUserEmailAddressException) DuplicateUserEmailAddressException(com.liferay.portal.DuplicateUserEmailAddressException) NoSuchUserGroupException(com.liferay.portal.NoSuchUserGroupException) PrincipalException(com.liferay.portal.security.auth.PrincipalException) SystemException(com.liferay.portal.kernel.exception.SystemException) NoSuchOrganizationException(com.liferay.portal.NoSuchOrganizationException) UserLockoutException(com.liferay.portal.UserLockoutException) UserPortraitSizeException(com.liferay.portal.UserPortraitSizeException) Contact(com.liferay.portal.model.Contact) EmailAddressGenerator(com.liferay.portal.security.auth.EmailAddressGenerator) SystemException(com.liferay.portal.kernel.exception.SystemException) UserPasswordException(com.liferay.portal.UserPasswordException) FullNameGenerator(com.liferay.portal.security.auth.FullNameGenerator) PasswordPolicy(com.liferay.portal.model.PasswordPolicy)

Example 10 with Company

use of com.liferay.portal.model.Company in project liferay-ide by liferay.

the class UserLocalServiceImpl method validateCompanyMaxUsers.

protected void validateCompanyMaxUsers(long companyId) throws PortalException, SystemException {
    Company company = companyPersistence.findByPrimaryKey(companyId);
    if (company.isSystem() || (company.getMaxUsers() == 0)) {
        return;
    }
    int userCount = searchCount(companyId, null, WorkflowConstants.STATUS_APPROVED, null);
    if (userCount >= company.getMaxUsers()) {
        throw new CompanyMaxUsersException();
    }
}
Also used : Company(com.liferay.portal.model.Company) CompanyMaxUsersException(com.liferay.portal.CompanyMaxUsersException)

Aggregations

Company (com.liferay.portal.model.Company)15 User (com.liferay.portal.model.User)11 Group (com.liferay.portal.model.Group)4 UserGroup (com.liferay.portal.model.UserGroup)4 EncryptorException (com.liferay.util.EncryptorException)4 Date (java.util.Date)4 SystemException (com.liferay.portal.kernel.exception.SystemException)3 Contact (com.liferay.portal.model.Contact)3 PasswordPolicy (com.liferay.portal.model.PasswordPolicy)3 CompanyMaxUsersException (com.liferay.portal.CompanyMaxUsersException)2 DuplicateUserEmailAddressException (com.liferay.portal.DuplicateUserEmailAddressException)2 ReservedUserEmailAddressException (com.liferay.portal.ReservedUserEmailAddressException)2 UserEmailAddressException (com.liferay.portal.UserEmailAddressException)2 EmailAddressGenerator (com.liferay.portal.security.auth.EmailAddressGenerator)2 IOException (java.io.IOException)2 ContactBirthdayException (com.liferay.portal.ContactBirthdayException)1 ContactFirstNameException (com.liferay.portal.ContactFirstNameException)1 ContactFullNameException (com.liferay.portal.ContactFullNameException)1 ContactLastNameException (com.liferay.portal.ContactLastNameException)1 DuplicateOpenIdException (com.liferay.portal.DuplicateOpenIdException)1