001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateOpenIdException;
023 import com.liferay.portal.DuplicateUserEmailAddressException;
024 import com.liferay.portal.DuplicateUserScreenNameException;
025 import com.liferay.portal.GroupFriendlyURLException;
026 import com.liferay.portal.ModelListenerException;
027 import com.liferay.portal.NoSuchImageException;
028 import com.liferay.portal.NoSuchOrganizationException;
029 import com.liferay.portal.NoSuchRoleException;
030 import com.liferay.portal.NoSuchTicketException;
031 import com.liferay.portal.NoSuchUserException;
032 import com.liferay.portal.NoSuchUserGroupException;
033 import com.liferay.portal.PasswordExpiredException;
034 import com.liferay.portal.RequiredUserException;
035 import com.liferay.portal.ReservedUserEmailAddressException;
036 import com.liferay.portal.ReservedUserScreenNameException;
037 import com.liferay.portal.UserEmailAddressException;
038 import com.liferay.portal.UserIdException;
039 import com.liferay.portal.UserLockoutException;
040 import com.liferay.portal.UserPasswordException;
041 import com.liferay.portal.UserPortraitSizeException;
042 import com.liferay.portal.UserPortraitTypeException;
043 import com.liferay.portal.UserReminderQueryException;
044 import com.liferay.portal.UserScreenNameException;
045 import com.liferay.portal.UserSmsException;
046 import com.liferay.portal.kernel.cache.PortalCache;
047 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil;
048 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil.Synchronizer;
049 import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
050 import com.liferay.portal.kernel.dao.shard.ShardCallable;
051 import com.liferay.portal.kernel.exception.PortalException;
052 import com.liferay.portal.kernel.exception.SystemException;
053 import com.liferay.portal.kernel.image.ImageBag;
054 import com.liferay.portal.kernel.image.ImageToolUtil;
055 import com.liferay.portal.kernel.language.LanguageUtil;
056 import com.liferay.portal.kernel.log.Log;
057 import com.liferay.portal.kernel.log.LogFactoryUtil;
058 import com.liferay.portal.kernel.messaging.DestinationNames;
059 import com.liferay.portal.kernel.messaging.Message;
060 import com.liferay.portal.kernel.messaging.MessageBusUtil;
061 import com.liferay.portal.kernel.search.Hits;
062 import com.liferay.portal.kernel.search.Indexer;
063 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
064 import com.liferay.portal.kernel.search.QueryConfig;
065 import com.liferay.portal.kernel.search.SearchContext;
066 import com.liferay.portal.kernel.search.Sort;
067 import com.liferay.portal.kernel.spring.aop.Skip;
068 import com.liferay.portal.kernel.transaction.Propagation;
069 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
070 import com.liferay.portal.kernel.transaction.Transactional;
071 import com.liferay.portal.kernel.util.ArrayUtil;
072 import com.liferay.portal.kernel.util.CharPool;
073 import com.liferay.portal.kernel.util.Digester;
074 import com.liferay.portal.kernel.util.DigesterUtil;
075 import com.liferay.portal.kernel.util.GetterUtil;
076 import com.liferay.portal.kernel.util.KeyValuePair;
077 import com.liferay.portal.kernel.util.LocaleUtil;
078 import com.liferay.portal.kernel.util.OrderByComparator;
079 import com.liferay.portal.kernel.util.ParamUtil;
080 import com.liferay.portal.kernel.util.PropsKeys;
081 import com.liferay.portal.kernel.util.StringBundler;
082 import com.liferay.portal.kernel.util.StringPool;
083 import com.liferay.portal.kernel.util.StringUtil;
084 import com.liferay.portal.kernel.util.UnicodeProperties;
085 import com.liferay.portal.kernel.util.Validator;
086 import com.liferay.portal.kernel.workflow.WorkflowConstants;
087 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
088 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
089 import com.liferay.portal.model.Account;
090 import com.liferay.portal.model.Company;
091 import com.liferay.portal.model.CompanyConstants;
092 import com.liferay.portal.model.Contact;
093 import com.liferay.portal.model.ContactConstants;
094 import com.liferay.portal.model.Group;
095 import com.liferay.portal.model.GroupConstants;
096 import com.liferay.portal.model.Layout;
097 import com.liferay.portal.model.Organization;
098 import com.liferay.portal.model.PasswordPolicy;
099 import com.liferay.portal.model.ResourceConstants;
100 import com.liferay.portal.model.Role;
101 import com.liferay.portal.model.RoleConstants;
102 import com.liferay.portal.model.Team;
103 import com.liferay.portal.model.Ticket;
104 import com.liferay.portal.model.TicketConstants;
105 import com.liferay.portal.model.User;
106 import com.liferay.portal.model.UserGroup;
107 import com.liferay.portal.model.UserGroupRole;
108 import com.liferay.portal.model.impl.LayoutImpl;
109 import com.liferay.portal.model.impl.UserCacheModel;
110 import com.liferay.portal.model.impl.UserImpl;
111 import com.liferay.portal.security.auth.AuthPipeline;
112 import com.liferay.portal.security.auth.Authenticator;
113 import com.liferay.portal.security.auth.EmailAddressGenerator;
114 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
115 import com.liferay.portal.security.auth.EmailAddressValidator;
116 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
117 import com.liferay.portal.security.auth.FullNameGenerator;
118 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
119 import com.liferay.portal.security.auth.FullNameValidator;
120 import com.liferay.portal.security.auth.FullNameValidatorFactory;
121 import com.liferay.portal.security.auth.PrincipalException;
122 import com.liferay.portal.security.auth.ScreenNameGenerator;
123 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
124 import com.liferay.portal.security.auth.ScreenNameValidator;
125 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
126 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
127 import com.liferay.portal.security.permission.PermissionCacheUtil;
128 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
129 import com.liferay.portal.security.pwd.PwdAuthenticator;
130 import com.liferay.portal.security.pwd.PwdToolkitUtil;
131 import com.liferay.portal.security.pwd.RegExpToolkit;
132 import com.liferay.portal.service.BaseServiceImpl;
133 import com.liferay.portal.service.ServiceContext;
134 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
135 import com.liferay.portal.util.PortalUtil;
136 import com.liferay.portal.util.PrefsPropsUtil;
137 import com.liferay.portal.util.PropsValues;
138 import com.liferay.portal.util.SubscriptionSender;
139 import com.liferay.portlet.documentlibrary.ImageSizeException;
140 import com.liferay.portlet.messageboards.model.MBMessage;
141 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
142 import com.liferay.util.Encryptor;
143 import com.liferay.util.EncryptorException;
144 import com.liferay.util.PwdGenerator;
145
146 import java.awt.image.RenderedImage;
147
148 import java.io.IOException;
149 import java.io.Serializable;
150
151 import java.util.ArrayList;
152 import java.util.Arrays;
153 import java.util.Calendar;
154 import java.util.Date;
155 import java.util.HashMap;
156 import java.util.HashSet;
157 import java.util.LinkedHashMap;
158 import java.util.List;
159 import java.util.Locale;
160 import java.util.Map;
161 import java.util.Set;
162 import java.util.concurrent.Callable;
163 import java.util.concurrent.ConcurrentHashMap;
164
165
177 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
178
179
193 @Override
194 public User addDefaultAdminUser(
195 long companyId, String screenName, String emailAddress,
196 Locale locale, String firstName, String middleName, String lastName)
197 throws PortalException, SystemException {
198
199 long creatorUserId = 0;
200 boolean autoPassword = false;
201 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
202 String password2 = password1;
203 boolean autoScreenName = false;
204
205 screenName = getLogin(screenName);
206
207 for (int i = 1;; i++) {
208 User screenNameUser = userPersistence.fetchByC_SN(
209 companyId, screenName);
210
211 if (screenNameUser == null) {
212 break;
213 }
214
215 screenName = screenName + i;
216 }
217
218 long facebookId = 0;
219 String openId = StringPool.BLANK;
220 int prefixId = 0;
221 int suffixId = 0;
222 boolean male = true;
223 int birthdayMonth = Calendar.JANUARY;
224 int birthdayDay = 1;
225 int birthdayYear = 1970;
226 String jobTitle = StringPool.BLANK;
227
228 Group guestGroup = groupLocalService.getGroup(
229 companyId, GroupConstants.GUEST);
230
231 long[] groupIds = {guestGroup.getGroupId()};
232
233 long[] organizationIds = null;
234
235 Role adminRole = roleLocalService.getRole(
236 companyId, RoleConstants.ADMINISTRATOR);
237
238 Role powerUserRole = roleLocalService.getRole(
239 companyId, RoleConstants.POWER_USER);
240
241 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
242
243 long[] userGroupIds = null;
244 boolean sendEmail = false;
245 ServiceContext serviceContext = new ServiceContext();
246
247 User defaultAdminUser = addUser(
248 creatorUserId, companyId, autoPassword, password1, password2,
249 autoScreenName, screenName, emailAddress, facebookId, openId,
250 locale, firstName, middleName, lastName, prefixId, suffixId, male,
251 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
252 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
253
254 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
255
256 updateLastLogin(
257 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
258
259 updatePasswordReset(defaultAdminUser.getUserId(), false);
260
261 return defaultAdminUser;
262 }
263
264
274 @Override
275 public void addDefaultGroups(long userId)
276 throws PortalException, SystemException {
277
278 User user = userPersistence.findByPrimaryKey(userId);
279
280 Set<Long> groupIdsSet = new HashSet<Long>();
281
282 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
283 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
284 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
285
286 for (String defaultGroupName : defaultGroupNames) {
287 Company company = companyPersistence.findByPrimaryKey(
288 user.getCompanyId());
289
290 Account account = company.getAccount();
291
292 if (StringUtil.equalsIgnoreCase(
293 defaultGroupName, account.getName())) {
294
295 defaultGroupName = GroupConstants.GUEST;
296 }
297
298 Group group = groupPersistence.fetchByC_N(
299 user.getCompanyId(), defaultGroupName);
300
301 if ((group != null) &&
302 !userPersistence.containsGroup(
303 userId, group.getGroupId())) {
304
305 groupIdsSet.add(group.getGroupId());
306 }
307 }
308
309 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
310 user.getCompanyId(),
311 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
312 StringPool.NEW_LINE,
313 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
314
315 for (String defaultOrganizationGroupName :
316 defaultOrganizationGroupNames) {
317
318 defaultOrganizationGroupName +=
319 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
320
321 Group group = groupPersistence.fetchByC_N(
322 user.getCompanyId(), defaultOrganizationGroupName);
323
324 if ((group != null) &&
325 !userPersistence.containsGroup(
326 userId, group.getGroupId())) {
327
328 groupIdsSet.add(group.getGroupId());
329 }
330 }
331
332 long[] groupIds = ArrayUtil.toArray(
333 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
334
335 groupLocalService.addUserGroups(userId, groupIds);
336 }
337
338
348 @Override
349 public void addDefaultRoles(long userId)
350 throws PortalException, SystemException {
351
352 User user = userPersistence.findByPrimaryKey(userId);
353
354 Set<Long> roleIdSet = new HashSet<Long>();
355
356 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
357 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
358 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
359
360 for (String defaultRoleName : defaultRoleNames) {
361 try {
362 Role role = rolePersistence.findByC_N(
363 user.getCompanyId(), defaultRoleName);
364
365 if (!userPersistence.containsRole(userId, role.getRoleId())) {
366 roleIdSet.add(role.getRoleId());
367 }
368 }
369 catch (NoSuchRoleException nsre) {
370 }
371 }
372
373 long[] roleIds = ArrayUtil.toArray(
374 roleIdSet.toArray(new Long[roleIdSet.size()]));
375
376 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
377
378 userPersistence.addRoles(userId, roleIds);
379 }
380
381
391 @Override
392 @SuppressWarnings("deprecation")
393 public void addDefaultUserGroups(long userId)
394 throws PortalException, SystemException {
395
396 User user = userPersistence.findByPrimaryKey(userId);
397
398 Set<Long> userGroupIdSet = new HashSet<Long>();
399
400 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
401 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
402 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
403
404 for (String defaultUserGroupName : defaultUserGroupNames) {
405 try {
406 UserGroup userGroup = userGroupPersistence.findByC_N(
407 user.getCompanyId(), defaultUserGroupName);
408
409 if (!userPersistence.containsUserGroup(
410 userId, userGroup.getUserGroupId())) {
411
412 userGroupIdSet.add(userGroup.getUserGroupId());
413 }
414 }
415 catch (NoSuchUserGroupException nsuge) {
416 }
417 }
418
419 long[] userGroupIds = ArrayUtil.toArray(
420 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
421
422 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
423 for (long userGroupId : userGroupIds) {
424 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
425 }
426 }
427
428 userPersistence.addUserGroups(userId, userGroupIds);
429 }
430
431
440 @Override
441 public void addGroupUsers(long groupId, long[] userIds)
442 throws PortalException, SystemException {
443
444 groupPersistence.addUsers(groupId, userIds);
445
446 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
447
448 indexer.reindex(userIds);
449
450 PermissionCacheUtil.clearCache();
451
452 addDefaultRolesAndTeams(groupId, userIds);
453 }
454
455
464 @Override
465 public void addOrganizationUsers(long organizationId, long[] userIds)
466 throws PortalException, SystemException {
467
468 organizationPersistence.addUsers(organizationId, userIds);
469
470 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
471
472 indexer.reindex(userIds);
473
474 PermissionCacheUtil.clearCache();
475 }
476
477
485 @Override
486 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
487 throws SystemException {
488
489 passwordPolicyRelLocalService.addPasswordPolicyRels(
490 passwordPolicyId, User.class.getName(), userIds);
491 }
492
493
502 @Override
503 public void addRoleUsers(long roleId, long[] userIds)
504 throws PortalException, SystemException {
505
506 rolePersistence.addUsers(roleId, userIds);
507
508 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
509
510 indexer.reindex(userIds);
511
512 PermissionCacheUtil.clearCache();
513 }
514
515
524 @Override
525 public void addTeamUsers(long teamId, long[] userIds)
526 throws PortalException, SystemException {
527
528 teamPersistence.addUsers(teamId, userIds);
529
530 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
531
532 indexer.reindex(userIds);
533
534 PermissionCacheUtil.clearCache();
535 }
536
537
585 @Override
586 public User addUser(
587 long creatorUserId, long companyId, boolean autoPassword,
588 String password1, String password2, boolean autoScreenName,
589 String screenName, String emailAddress, long facebookId,
590 String openId, Locale locale, String firstName, String middleName,
591 String lastName, int prefixId, int suffixId, boolean male,
592 int birthdayMonth, int birthdayDay, int birthdayYear,
593 String jobTitle, long[] groupIds, long[] organizationIds,
594 long[] roleIds, long[] userGroupIds, boolean sendEmail,
595 ServiceContext serviceContext)
596 throws PortalException, SystemException {
597
598 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
599
600 try {
601 WorkflowThreadLocal.setEnabled(false);
602
603 if (serviceContext == null) {
604 serviceContext = new ServiceContext();
605 }
606
607 if (serviceContext.getWorkflowAction() !=
608 WorkflowConstants.ACTION_PUBLISH) {
609
610 serviceContext.setWorkflowAction(
611 WorkflowConstants.ACTION_PUBLISH);
612 }
613
614 return addUserWithWorkflow(
615 creatorUserId, companyId, autoPassword, password1, password2,
616 autoScreenName, screenName, emailAddress, facebookId, openId,
617 locale, firstName, middleName, lastName, prefixId, suffixId,
618 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
619 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
620 serviceContext);
621 }
622 finally {
623 WorkflowThreadLocal.setEnabled(workflowEnabled);
624 }
625 }
626
627
636 @Override
637 @SuppressWarnings("deprecation")
638 public void addUserGroupUsers(long userGroupId, long[] userIds)
639 throws PortalException, SystemException {
640
641 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
642 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
643 }
644
645 userGroupPersistence.addUsers(userGroupId, userIds);
646
647 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
648
649 indexer.reindex(userIds);
650
651 PermissionCacheUtil.clearCache();
652 }
653
654
702 @Override
703 @SuppressWarnings("deprecation")
704 public User addUserWithWorkflow(
705 long creatorUserId, long companyId, boolean autoPassword,
706 String password1, String password2, boolean autoScreenName,
707 String screenName, String emailAddress, long facebookId,
708 String openId, Locale locale, String firstName, String middleName,
709 String lastName, int prefixId, int suffixId, boolean male,
710 int birthdayMonth, int birthdayDay, int birthdayYear,
711 String jobTitle, long[] groupIds, long[] organizationIds,
712 long[] roleIds, long[] userGroupIds, boolean sendEmail,
713 ServiceContext serviceContext)
714 throws PortalException, SystemException {
715
716
717
718 Company company = companyPersistence.findByPrimaryKey(companyId);
719 screenName = getLogin(screenName);
720 openId = StringUtil.trim(openId);
721 Date now = new Date();
722
723 if (PrefsPropsUtil.getBoolean(
724 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
725
726 autoScreenName = true;
727 }
728
729
730
731 long userId = counterLocalService.increment();
732
733 EmailAddressGenerator emailAddressGenerator =
734 EmailAddressGeneratorFactory.getInstance();
735
736 if ((emailAddress == null) ||
737 emailAddressGenerator.isGenerated(emailAddress)) {
738
739 emailAddress = StringPool.BLANK;
740 }
741 else {
742 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
743 }
744
745 if (!PrefsPropsUtil.getBoolean(
746 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
747 Validator.isNull(emailAddress)) {
748
749 emailAddress = emailAddressGenerator.generate(companyId, userId);
750 }
751
752 validate(
753 companyId, userId, autoPassword, password1, password2,
754 autoScreenName, screenName, emailAddress, openId, firstName,
755 middleName, lastName, organizationIds);
756
757 if (!autoPassword) {
758 if (Validator.isNull(password1) || Validator.isNull(password2)) {
759 throw new UserPasswordException(
760 UserPasswordException.PASSWORD_INVALID);
761 }
762 }
763
764 if (autoScreenName) {
765 ScreenNameGenerator screenNameGenerator =
766 ScreenNameGeneratorFactory.getInstance();
767
768 try {
769 screenName = screenNameGenerator.generate(
770 companyId, userId, emailAddress);
771 }
772 catch (Exception e) {
773 throw new SystemException(e);
774 }
775 }
776
777 User defaultUser = getDefaultUser(companyId);
778
779 FullNameGenerator fullNameGenerator =
780 FullNameGeneratorFactory.getInstance();
781
782 String fullName = fullNameGenerator.getFullName(
783 firstName, middleName, lastName);
784
785 String greeting = LanguageUtil.format(
786 locale, "welcome-x", " " + fullName, false);
787
788 User user = userPersistence.create(userId);
789
790 if (serviceContext != null) {
791 String uuid = serviceContext.getUuid();
792
793 if (Validator.isNotNull(uuid)) {
794 user.setUuid(uuid);
795 }
796 }
797
798 user.setCompanyId(companyId);
799 user.setCreateDate(now);
800 user.setModifiedDate(now);
801 user.setDefaultUser(false);
802 user.setContactId(counterLocalService.increment());
803
804 if (Validator.isNotNull(password1)) {
805 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
806 user.setPasswordUnencrypted(password1);
807 }
808
809 user.setPasswordEncrypted(true);
810
811 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
812
813 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
814 passwordPolicy.isChangeRequired()) {
815
816 user.setPasswordReset(true);
817 }
818 else {
819 user.setPasswordReset(false);
820 }
821
822 user.setDigest(StringPool.BLANK);
823 user.setScreenName(screenName);
824 user.setEmailAddress(emailAddress);
825 user.setFacebookId(facebookId);
826
827 Long ldapServerId = null;
828
829 if (serviceContext != null) {
830 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
831 }
832
833 if (ldapServerId != null) {
834 user.setLdapServerId(ldapServerId);
835 }
836 else {
837 user.setLdapServerId(-1);
838 }
839
840 user.setOpenId(openId);
841 user.setLanguageId(LocaleUtil.toLanguageId(locale));
842 user.setTimeZoneId(defaultUser.getTimeZoneId());
843 user.setGreeting(greeting);
844 user.setFirstName(firstName);
845 user.setMiddleName(middleName);
846 user.setLastName(lastName);
847 user.setJobTitle(jobTitle);
848 user.setStatus(WorkflowConstants.STATUS_DRAFT);
849 user.setExpandoBridgeAttributes(serviceContext);
850
851 userPersistence.update(user, serviceContext);
852
853
854
855 String creatorUserName = StringPool.BLANK;
856
857 if (creatorUserId <= 0) {
858 creatorUserId = user.getUserId();
859
860
861
862
863
864 }
865 else {
866 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
867
868 creatorUserName = creatorUser.getFullName();
869 }
870
871 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
872
873 Contact contact = contactPersistence.create(user.getContactId());
874
875 contact.setCompanyId(user.getCompanyId());
876 contact.setUserId(creatorUserId);
877 contact.setUserName(creatorUserName);
878 contact.setCreateDate(now);
879 contact.setModifiedDate(now);
880 contact.setClassName(User.class.getName());
881 contact.setClassPK(user.getUserId());
882 contact.setAccountId(company.getAccountId());
883 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
884 contact.setEmailAddress(user.getEmailAddress());
885 contact.setFirstName(firstName);
886 contact.setMiddleName(middleName);
887 contact.setLastName(lastName);
888 contact.setPrefixId(prefixId);
889 contact.setSuffixId(suffixId);
890 contact.setMale(male);
891 contact.setBirthday(birthday);
892 contact.setJobTitle(jobTitle);
893
894 contactPersistence.update(contact, serviceContext);
895
896
897
898 groupLocalService.addGroup(
899 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
900 User.class.getName(), user.getUserId(), null, null, 0,
901 StringPool.SLASH + screenName, false, true, null);
902
903
904
905 if (groupIds != null) {
906 List<Group> groups = new ArrayList<Group>();
907
908 for (long groupId : groupIds) {
909 Group group = groupLocalService.fetchGroup(groupId);
910
911 if (group != null) {
912 groups.add(group);
913 }
914 else {
915 if (_log.isWarnEnabled()) {
916 _log.warn("Group " + groupId + " does not exist");
917 }
918 }
919 }
920
921 groupLocalService.addUserGroups(userId, groups);
922 }
923
924 addDefaultGroups(userId);
925
926
927
928 updateOrganizations(userId, organizationIds, false);
929
930
931
932 if (roleIds != null) {
933 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
934
935 userPersistence.setRoles(userId, roleIds);
936 }
937
938 addDefaultRoles(userId);
939
940
941
942 if (userGroupIds != null) {
943 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
944 for (long userGroupId : userGroupIds) {
945 userGroupLocalService.copyUserGroupLayouts(
946 userGroupId, new long[] {userId});
947 }
948 }
949
950 userPersistence.setUserGroups(userId, userGroupIds);
951 }
952
953 addDefaultUserGroups(userId);
954
955
956
957 resourceLocalService.addResources(
958 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
959 false, false, false);
960
961
962
963 if (serviceContext != null) {
964 updateAsset(
965 creatorUserId, user, serviceContext.getAssetCategoryIds(),
966 serviceContext.getAssetTagNames());
967 }
968
969
970
971 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
972 reindex(user);
973 }
974
975
976
977 long workflowUserId = creatorUserId;
978
979 if (workflowUserId == userId) {
980 workflowUserId = defaultUser.getUserId();
981 }
982
983 ServiceContext workflowServiceContext = serviceContext;
984
985 if (workflowServiceContext == null) {
986 workflowServiceContext = new ServiceContext();
987 }
988
989 workflowServiceContext.setAttribute("autoPassword", autoPassword);
990 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
991 workflowServiceContext.setAttribute("sendEmail", sendEmail);
992
993 WorkflowHandlerRegistryUtil.startWorkflowInstance(
994 companyId, workflowUserId, User.class.getName(), userId, user,
995 workflowServiceContext);
996
997 if (serviceContext != null) {
998 String passwordUnencrypted = (String)serviceContext.getAttribute(
999 "passwordUnencrypted");
1000
1001 if (Validator.isNotNull(passwordUnencrypted)) {
1002 user.setPasswordUnencrypted(passwordUnencrypted);
1003 }
1004 }
1005
1006 return user;
1007 }
1008
1009 @Override
1010 public void afterPropertiesSet() {
1011 super.afterPropertiesSet();
1012
1013 PortalCache<Serializable, Serializable> portalCache =
1014 EntityCacheUtil.getPortalCache(UserImpl.class);
1015
1016 PortalCacheMapSynchronizeUtil.synchronize(
1017 portalCache, _defaultUsers,
1018 new Synchronizer<Serializable, Serializable>() {
1019
1020 @Override
1021 public void onSynchronize(
1022 Map<? extends Serializable, ? extends Serializable> map,
1023 Serializable key, Serializable value) {
1024
1025 if (!(value instanceof UserCacheModel)) {
1026 return;
1027 }
1028
1029 UserCacheModel userCacheModel = (UserCacheModel)value;
1030
1031 if (userCacheModel.defaultUser) {
1032 _defaultUsers.remove(userCacheModel.companyId);
1033 }
1034 }
1035
1036 });
1037 }
1038
1039
1063 @Override
1064 public int authenticateByEmailAddress(
1065 long companyId, String emailAddress, String password,
1066 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1067 Map<String, Object> resultsMap)
1068 throws PortalException, SystemException {
1069
1070 return authenticate(
1071 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1072 headerMap, parameterMap, resultsMap);
1073 }
1074
1075
1099 @Override
1100 public int authenticateByScreenName(
1101 long companyId, String screenName, String password,
1102 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1103 Map<String, Object> resultsMap)
1104 throws PortalException, SystemException {
1105
1106 return authenticate(
1107 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1108 headerMap, parameterMap, resultsMap);
1109 }
1110
1111
1135 @Override
1136 public int authenticateByUserId(
1137 long companyId, long userId, String password,
1138 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1139 Map<String, Object> resultsMap)
1140 throws PortalException, SystemException {
1141
1142 return authenticate(
1143 companyId, String.valueOf(userId), password,
1144 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1145 }
1146
1147
1187 @Override
1188 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1189 public long authenticateForBasic(
1190 long companyId, String authType, String login, String password)
1191 throws PortalException, SystemException {
1192
1193 if (PropsValues.AUTH_LOGIN_DISABLED) {
1194 return 0;
1195 }
1196
1197 User user = null;
1198
1199 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1200 user = fetchUserByEmailAddress(companyId, login);
1201 }
1202 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1203 user = fetchUserByScreenName(companyId, login);
1204 }
1205 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1206 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1207 }
1208
1209 if (user == null) {
1210 return 0;
1211 }
1212
1213 if (user.isDefaultUser()) {
1214 if (_log.isInfoEnabled()) {
1215 _log.info(
1216 "Basic authentication is disabled for the default " +
1217 "user");
1218 }
1219
1220 return 0;
1221 }
1222 else if (!user.isActive()) {
1223 if (_log.isInfoEnabled()) {
1224 _log.info(
1225 "Basic authentication is disabled for inactive user " +
1226 user.getUserId());
1227 }
1228
1229 return 0;
1230 }
1231
1232 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1233 return user.getUserId();
1234 }
1235
1236 String userPassword = user.getPassword();
1237
1238 if (!user.isPasswordEncrypted()) {
1239 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1240 }
1241
1242 String encPassword = PasswordEncryptorUtil.encrypt(
1243 password, userPassword);
1244
1245 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1246 return user.getUserId();
1247 }
1248
1249 return 0;
1250 }
1251
1252
1270 @Override
1271 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1272 public long authenticateForDigest(
1273 long companyId, String username, String realm, String nonce,
1274 String method, String uri, String response)
1275 throws PortalException, SystemException {
1276
1277 if (PropsValues.AUTH_LOGIN_DISABLED) {
1278 return 0;
1279 }
1280
1281
1282
1283 User user = fetchUserByEmailAddress(companyId, username);
1284
1285 if (user == null) {
1286 user = fetchUserByScreenName(companyId, username);
1287 }
1288
1289 if (user == null) {
1290 user = userPersistence.fetchByPrimaryKey(
1291 GetterUtil.getLong(username));
1292 }
1293
1294 if (user == null) {
1295 return 0;
1296 }
1297
1298 if (user.isDefaultUser()) {
1299 if (_log.isInfoEnabled()) {
1300 _log.info(
1301 "Digest authentication is disabled for the default user");
1302 }
1303
1304 return 0;
1305 }
1306 else if (!user.isActive()) {
1307 if (_log.isInfoEnabled()) {
1308 _log.info(
1309 "Digest authentication is disabled for inactive user " +
1310 user.getUserId());
1311 }
1312
1313 return 0;
1314 }
1315
1316
1317
1318 String digest = user.getDigest();
1319
1320 if (Validator.isNull(digest)) {
1321 _log.error(
1322 "User must first login through the portal " + user.getUserId());
1323
1324 return 0;
1325 }
1326
1327 String[] digestArray = StringUtil.split(user.getDigest());
1328
1329 for (String ha1 : digestArray) {
1330 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1331
1332 String curResponse = DigesterUtil.digestHex(
1333 Digester.MD5, ha1, nonce, ha2);
1334
1335 if (response.equals(curResponse)) {
1336 return user.getUserId();
1337 }
1338 }
1339
1340 return 0;
1341 }
1342
1343
1352 @Override
1353 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1354 public boolean authenticateForJAAS(long userId, String encPassword) {
1355 if (PropsValues.AUTH_LOGIN_DISABLED) {
1356 return false;
1357 }
1358
1359 try {
1360 User user = userPersistence.findByPrimaryKey(userId);
1361
1362 if (user.isDefaultUser()) {
1363 if (_log.isInfoEnabled()) {
1364 _log.info(
1365 "JAAS authentication is disabled for the default user");
1366 }
1367
1368 return false;
1369 }
1370 else if (!user.isActive()) {
1371 if (_log.isInfoEnabled()) {
1372 _log.info(
1373 "JAAS authentication is disabled for inactive user " +
1374 userId);
1375 }
1376
1377 return false;
1378 }
1379
1380 String userPassword = user.getPassword();
1381
1382 if (user.isPasswordEncrypted()) {
1383 if (userPassword.equals(encPassword)) {
1384 return true;
1385 }
1386
1387 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1388 encPassword = PasswordEncryptorUtil.encrypt(
1389 encPassword, userPassword);
1390
1391 if (userPassword.equals(encPassword)) {
1392 return true;
1393 }
1394 }
1395 }
1396 else {
1397 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1398 if (userPassword.equals(encPassword)) {
1399 return true;
1400 }
1401 }
1402
1403 userPassword = PasswordEncryptorUtil.encrypt(
1404 userPassword, encPassword);
1405
1406 if (userPassword.equals(encPassword)) {
1407 return true;
1408 }
1409 }
1410 }
1411 catch (Exception e) {
1412 _log.error(e);
1413 }
1414
1415 return false;
1416 }
1417
1418
1426 @Override
1427 public void checkLockout(User user)
1428 throws PortalException, SystemException {
1429
1430 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1431 return;
1432 }
1433
1434 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1435
1436 if (!passwordPolicy.isLockout()) {
1437 return;
1438 }
1439
1440
1441
1442 Date now = new Date();
1443 int failedLoginAttempts = user.getFailedLoginAttempts();
1444
1445 if (failedLoginAttempts > 0) {
1446 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1447 long elapsedTime = now.getTime() - failedLoginTime;
1448 long requiredElapsedTime =
1449 passwordPolicy.getResetFailureCount() * 1000;
1450
1451 if ((requiredElapsedTime != 0) &&
1452 (elapsedTime > requiredElapsedTime)) {
1453
1454 user.setFailedLoginAttempts(0);
1455
1456 userPersistence.update(user);
1457 }
1458 }
1459
1460
1461
1462 if (user.isLockout()) {
1463 long lockoutTime = user.getLockoutDate().getTime();
1464 long elapsedTime = now.getTime() - lockoutTime;
1465 long requiredElapsedTime =
1466 passwordPolicy.getLockoutDuration() * 1000;
1467
1468 if ((requiredElapsedTime != 0) &&
1469 (elapsedTime > requiredElapsedTime)) {
1470
1471 user.setLockout(false);
1472 user.setLockoutDate(null);
1473
1474 userPersistence.update(user);
1475 }
1476 }
1477
1478 if (user.isLockout()) {
1479 throw new UserLockoutException();
1480 }
1481 }
1482
1483
1490 @Override
1491 public void checkLoginFailure(User user) throws SystemException {
1492 Date now = new Date();
1493
1494 int failedLoginAttempts = user.getFailedLoginAttempts();
1495
1496 user.setLastFailedLoginDate(now);
1497 user.setFailedLoginAttempts(++failedLoginAttempts);
1498
1499 userPersistence.update(user);
1500 }
1501
1502
1512 @Override
1513 public void checkLoginFailureByEmailAddress(
1514 long companyId, String emailAddress)
1515 throws PortalException, SystemException {
1516
1517 User user = getUserByEmailAddress(companyId, emailAddress);
1518
1519 checkLoginFailure(user);
1520 }
1521
1522
1530 @Override
1531 public void checkLoginFailureById(long userId)
1532 throws PortalException, SystemException {
1533
1534 User user = userPersistence.findByPrimaryKey(userId);
1535
1536 checkLoginFailure(user);
1537 }
1538
1539
1548 @Override
1549 public void checkLoginFailureByScreenName(long companyId, String screenName)
1550 throws PortalException, SystemException {
1551
1552 User user = getUserByScreenName(companyId, screenName);
1553
1554 checkLoginFailure(user);
1555 }
1556
1557
1567 @Override
1568 public void checkPasswordExpired(User user)
1569 throws PortalException, SystemException {
1570
1571 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1572 return;
1573 }
1574
1575 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1576
1577
1578
1579 if (isPasswordExpired(user)) {
1580 int graceLoginCount = user.getGraceLoginCount();
1581
1582 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1583 user.setGraceLoginCount(++graceLoginCount);
1584
1585 userPersistence.update(user);
1586 }
1587 else {
1588 user.setDigest(StringPool.BLANK);
1589
1590 userPersistence.update(user);
1591
1592 throw new PasswordExpiredException();
1593 }
1594 }
1595
1596
1597
1598 if (passwordPolicy.isChangeable() &&
1599 passwordPolicy.isChangeRequired()) {
1600
1601 if (user.getLastLoginDate() == null) {
1602 user.setPasswordReset(true);
1603
1604 userPersistence.update(user);
1605 }
1606 }
1607 }
1608
1609
1615 @Override
1616 public void clearOrganizationUsers(long organizationId)
1617 throws SystemException {
1618
1619 organizationPersistence.clearUsers(organizationId);
1620
1621 PermissionCacheUtil.clearCache();
1622 }
1623
1624
1630 @Override
1631 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1632 userGroupPersistence.clearUsers(userGroupId);
1633
1634 PermissionCacheUtil.clearCache();
1635 }
1636
1637
1652 @Override
1653 public void completeUserRegistration(
1654 User user, ServiceContext serviceContext)
1655 throws PortalException, SystemException {
1656
1657 boolean autoPassword = ParamUtil.getBoolean(
1658 serviceContext, "autoPassword");
1659
1660 String password = (String)serviceContext.getAttribute(
1661 "passwordUnencrypted");
1662
1663 if (autoPassword) {
1664 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1665 if (_log.isWarnEnabled()) {
1666 StringBundler sb = new StringBundler(4);
1667
1668 sb.append("When LDAP password policy is enabled, it is ");
1669 sb.append("possible that portal generated passwords will ");
1670 sb.append("not match the LDAP policy. Using ");
1671 sb.append("RegExpToolkit to generate new password.");
1672
1673 _log.warn(sb.toString());
1674 }
1675
1676 RegExpToolkit regExpToolkit = new RegExpToolkit();
1677
1678 password = regExpToolkit.generate(null);
1679 }
1680 else {
1681 PasswordPolicy passwordPolicy =
1682 passwordPolicyLocalService.getPasswordPolicy(
1683 user.getCompanyId(), user.getOrganizationIds());
1684
1685 password = PwdToolkitUtil.generate(passwordPolicy);
1686 }
1687
1688 serviceContext.setAttribute("passwordUnencrypted", password);
1689
1690 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1691 user.setPasswordUnencrypted(password);
1692 user.setPasswordEncrypted(true);
1693 user.setPasswordModified(true);
1694 user.setPasswordModifiedDate(new Date());
1695
1696 userPersistence.update(user);
1697
1698 user.setPasswordModified(false);
1699 }
1700
1701 if (user.hasCompanyMx()) {
1702 mailService.addUser(
1703 user.getCompanyId(), user.getUserId(), password,
1704 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1705 user.getEmailAddress());
1706 }
1707
1708 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1709
1710 if (sendEmail) {
1711 sendEmail(user, password, serviceContext);
1712 }
1713
1714 Company company = companyPersistence.findByPrimaryKey(
1715 user.getCompanyId());
1716
1717 if (company.isStrangersVerify()) {
1718 sendEmailAddressVerification(
1719 user, user.getEmailAddress(), serviceContext);
1720 }
1721 }
1722
1723
1736 @Override
1737 public KeyValuePair decryptUserId(
1738 long companyId, String name, String password)
1739 throws PortalException, SystemException {
1740
1741 Company company = companyPersistence.findByPrimaryKey(companyId);
1742
1743 try {
1744 name = Encryptor.decrypt(company.getKeyObj(), name);
1745 }
1746 catch (EncryptorException ee) {
1747 throw new SystemException(ee);
1748 }
1749
1750 long userId = GetterUtil.getLong(name);
1751
1752 User user = userPersistence.findByPrimaryKey(userId);
1753
1754 try {
1755 password = Encryptor.decrypt(company.getKeyObj(), password);
1756 }
1757 catch (EncryptorException ee) {
1758 throw new SystemException(ee);
1759 }
1760
1761 String userPassword = user.getPassword();
1762 String encPassword = PasswordEncryptorUtil.encrypt(
1763 password, userPassword);
1764
1765 if (userPassword.equals(encPassword)) {
1766 if (isPasswordExpired(user)) {
1767 user.setPasswordReset(true);
1768
1769 userPersistence.update(user);
1770 }
1771
1772 return new KeyValuePair(name, password);
1773 }
1774 else {
1775 throw new PrincipalException();
1776 }
1777 }
1778
1779
1787 @Override
1788 public void deletePortrait(long userId)
1789 throws PortalException, SystemException {
1790
1791 User user = userPersistence.findByPrimaryKey(userId);
1792
1793 long portraitId = user.getPortraitId();
1794
1795 if (portraitId > 0) {
1796 user.setPortraitId(0);
1797
1798 userPersistence.update(user);
1799
1800 imageLocalService.deleteImage(portraitId);
1801 }
1802 }
1803
1804
1813 @Override
1814 public void deleteRoleUser(long roleId, long userId)
1815 throws PortalException, SystemException {
1816
1817 rolePersistence.removeUser(roleId, userId);
1818
1819 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1820
1821 indexer.reindex(userId);
1822
1823 PermissionCacheUtil.clearCache();
1824 }
1825
1826
1834 @Override
1835 public User deleteUser(long userId)
1836 throws PortalException, SystemException {
1837
1838 User user = userPersistence.findByPrimaryKey(userId);
1839
1840 return deleteUser(user);
1841 }
1842
1843
1851 @Override
1852 public User deleteUser(User user) throws PortalException, SystemException {
1853 if (!PropsValues.USERS_DELETE) {
1854 throw new RequiredUserException();
1855 }
1856
1857
1858
1859 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1860
1861
1862
1863 Group group = null;
1864
1865 if (!user.isDefaultUser()) {
1866 group = user.getGroup();
1867 }
1868
1869 if (group != null) {
1870 groupLocalService.deleteGroup(group);
1871 }
1872
1873
1874
1875 try {
1876 imageLocalService.deleteImage(user.getPortraitId());
1877 }
1878 catch (NoSuchImageException nsie) {
1879 if (_log.isWarnEnabled()) {
1880 _log.warn("Unable to delete image " + user.getPortraitId());
1881 }
1882 }
1883
1884
1885
1886 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1887 User.class.getName(), user.getUserId());
1888
1889
1890
1891 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1892
1893
1894
1895 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1896
1897
1898
1899 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1900
1901
1902
1903 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1904
1905
1906
1907 assetEntryLocalService.deleteEntry(
1908 User.class.getName(), user.getUserId());
1909
1910
1911
1912 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1913
1914
1915
1916 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1917
1918
1919
1920 expandoRowLocalService.deleteRows(user.getUserId());
1921
1922
1923
1924 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1925 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1926 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1927
1928
1929
1930 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1931 user.getUserId());
1932
1933
1934
1935 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1936
1937
1938
1939 socialActivityLocalService.deleteUserActivities(user.getUserId());
1940 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1941 socialRequestLocalService.deleteUserRequests(user.getUserId());
1942
1943
1944
1945 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1946
1947
1948
1949 Contact contact = contactLocalService.fetchContact(user.getContactId());
1950
1951 if (contact != null) {
1952 contactLocalService.deleteContact(contact);
1953 }
1954
1955
1956
1957 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1958 user.getUserId());
1959
1960
1961
1962 resourceLocalService.deleteResource(
1963 user.getCompanyId(), User.class.getName(),
1964 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1965
1966
1967
1968 userPersistence.remove(user);
1969
1970
1971
1972 PermissionCacheUtil.clearCache();
1973
1974
1975
1976 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1977 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1978
1979 return user;
1980 }
1981
1982
1990 @Override
1991 public void deleteUserGroupUser(long userGroupId, long userId)
1992 throws PortalException, SystemException {
1993
1994 userGroupPersistence.removeUser(userGroupId, userId);
1995
1996 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1997
1998 indexer.reindex(userId);
1999
2000 PermissionCacheUtil.clearCache();
2001 }
2002
2003
2012 @Override
2013 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
2014 public String encryptUserId(String name)
2015 throws PortalException, SystemException {
2016
2017 long userId = GetterUtil.getLong(name);
2018
2019 User user = userPersistence.findByPrimaryKey(userId);
2020
2021 Company company = companyPersistence.findByPrimaryKey(
2022 user.getCompanyId());
2023
2024 try {
2025 return Encryptor.encrypt(company.getKeyObj(), name);
2026 }
2027 catch (EncryptorException ee) {
2028 throw new SystemException(ee);
2029 }
2030 }
2031
2032
2041 @Override
2042 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2043 throws SystemException {
2044
2045 emailAddress = getLogin(emailAddress);
2046
2047 return userPersistence.fetchByC_EA(companyId, emailAddress);
2048 }
2049
2050
2059 @Override
2060 public User fetchUserByFacebookId(long companyId, long facebookId)
2061 throws SystemException {
2062
2063 return userPersistence.fetchByC_FID(companyId, facebookId);
2064 }
2065
2066
2074 @Override
2075 public User fetchUserById(long userId) throws SystemException {
2076 return userPersistence.fetchByPrimaryKey(userId);
2077 }
2078
2079
2088 @Override
2089 public User fetchUserByOpenId(long companyId, String openId)
2090 throws SystemException {
2091
2092 return userPersistence.fetchByC_O(companyId, openId);
2093 }
2094
2095
2104 @Override
2105 public User fetchUserByScreenName(long companyId, String screenName)
2106 throws SystemException {
2107
2108 screenName = getLogin(screenName);
2109
2110 return userPersistence.fetchByC_SN(companyId, screenName);
2111 }
2112
2113
2132 @Override
2133 public List<User> getCompanyUsers(long companyId, int start, int end)
2134 throws SystemException {
2135
2136 return userPersistence.findByCompanyId(companyId, start, end);
2137 }
2138
2139
2146 @Override
2147 public int getCompanyUsersCount(long companyId) throws SystemException {
2148 return userPersistence.countByCompanyId(companyId);
2149 }
2150
2151
2160 @Override
2161 @Skip
2162 public User getDefaultUser(long companyId)
2163 throws PortalException, SystemException {
2164
2165 User userModel = _defaultUsers.get(companyId);
2166
2167 if (userModel == null) {
2168 userModel = userLocalService.loadGetDefaultUser(companyId);
2169
2170 _defaultUsers.put(companyId, userModel);
2171 }
2172
2173 return userModel;
2174 }
2175
2176
2185 @Override
2186 @Skip
2187 public long getDefaultUserId(long companyId)
2188 throws PortalException, SystemException {
2189
2190 User user = getDefaultUser(companyId);
2191
2192 return user.getUserId();
2193 }
2194
2195
2202 @Override
2203 public long[] getGroupUserIds(long groupId) throws SystemException {
2204 return getUserIds(getGroupUsers(groupId));
2205 }
2206
2207
2217 @Override
2218 public int getGroupUsersCount(long groupId, int status)
2219 throws PortalException, SystemException {
2220
2221 Group group = groupPersistence.findByPrimaryKey(groupId);
2222
2223 LinkedHashMap<String, Object> params =
2224 new LinkedHashMap<String, Object>();
2225
2226 params.put("usersGroups", new Long(groupId));
2227
2228 return searchCount(group.getCompanyId(), null, status, params);
2229 }
2230
2231 @Override
2232 public List<User> getInheritedRoleUsers(
2233 long roleId, int start, int end, OrderByComparator obc)
2234 throws PortalException, SystemException {
2235
2236 Role role = rolePersistence.findByPrimaryKey(roleId);
2237
2238 LinkedHashMap<String, Object> params =
2239 new LinkedHashMap<String, Object>();
2240
2241 params.put("inherit", Boolean.TRUE);
2242 params.put("usersRoles", roleId);
2243
2244 return search(
2245 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2246 params, start, end, obc);
2247 }
2248
2249
2257 @Override
2258 public List<User> getNoAnnouncementsDeliveries(String type)
2259 throws SystemException {
2260
2261 return userFinder.findByNoAnnouncementsDeliveries(type);
2262 }
2263
2264
2270 @Override
2271 public List<User> getNoContacts() throws SystemException {
2272 return userFinder.findByNoContacts();
2273 }
2274
2275
2282 @Override
2283 public List<User> getNoGroups() throws SystemException {
2284 return userFinder.findByNoGroups();
2285 }
2286
2287
2294 @Override
2295 public long[] getOrganizationUserIds(long organizationId)
2296 throws SystemException {
2297
2298 return getUserIds(getOrganizationUsers(organizationId));
2299 }
2300
2301
2312 @Override
2313 public int getOrganizationUsersCount(long organizationId, int status)
2314 throws PortalException, SystemException {
2315
2316 Organization organization = organizationPersistence.findByPrimaryKey(
2317 organizationId);
2318
2319 LinkedHashMap<String, Object> params =
2320 new LinkedHashMap<String, Object>();
2321
2322 params.put("usersOrgs", new Long(organizationId));
2323
2324 return searchCount(organization.getCompanyId(), null, status, params);
2325 }
2326
2327
2334 @Override
2335 public long[] getRoleUserIds(long roleId) throws SystemException {
2336 return getUserIds(getRoleUsers(roleId));
2337 }
2338
2339
2349 @Override
2350 public int getRoleUsersCount(long roleId, int status)
2351 throws PortalException, SystemException {
2352
2353 Role role = rolePersistence.findByPrimaryKey(roleId);
2354
2355 LinkedHashMap<String, Object> params =
2356 new LinkedHashMap<String, Object>();
2357
2358 params.put("usersRoles", new Long(roleId));
2359
2360 return searchCount(role.getCompanyId(), null, status, params);
2361 }
2362
2363
2390 @Override
2391 public List<User> getSocialUsers(
2392 long userId, int type, int start, int end, OrderByComparator obc)
2393 throws PortalException, SystemException {
2394
2395 User user = userPersistence.findByPrimaryKey(userId);
2396
2397 LinkedHashMap<String, Object> params =
2398 new LinkedHashMap<String, Object>();
2399
2400 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2401
2402 return search(
2403 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2404 params, start, end, obc);
2405 }
2406
2407
2430 @Override
2431 public List<User> getSocialUsers(
2432 long userId, int start, int end, OrderByComparator obc)
2433 throws PortalException, SystemException {
2434
2435 User user = userPersistence.findByPrimaryKey(userId);
2436
2437 LinkedHashMap<String, Object> params =
2438 new LinkedHashMap<String, Object>();
2439
2440 params.put("socialRelation", new Long[] {userId});
2441
2442 return search(
2443 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2444 params, start, end, obc);
2445 }
2446
2447
2475 @Override
2476 public List<User> getSocialUsers(
2477 long userId1, long userId2, int type, int start, int end,
2478 OrderByComparator obc)
2479 throws PortalException, SystemException {
2480
2481 User user1 = userPersistence.findByPrimaryKey(userId1);
2482
2483 LinkedHashMap<String, Object> params =
2484 new LinkedHashMap<String, Object>();
2485
2486 params.put(
2487 "socialMutualRelationType",
2488 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2489
2490 return search(
2491 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2492 params, start, end, obc);
2493 }
2494
2495
2520 @Override
2521 public List<User> getSocialUsers(
2522 long userId1, long userId2, int start, int end,
2523 OrderByComparator obc)
2524 throws PortalException, SystemException {
2525
2526 User user1 = userPersistence.findByPrimaryKey(userId1);
2527
2528 LinkedHashMap<String, Object> params =
2529 new LinkedHashMap<String, Object>();
2530
2531 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2532
2533 return search(
2534 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2535 params, start, end, obc);
2536 }
2537
2538
2546 @Override
2547 public int getSocialUsersCount(long userId)
2548 throws PortalException, SystemException {
2549
2550 User user = userPersistence.findByPrimaryKey(userId);
2551
2552 LinkedHashMap<String, Object> params =
2553 new LinkedHashMap<String, Object>();
2554
2555 params.put("socialRelation", new Long[] {userId});
2556
2557 return searchCount(
2558 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2559 params);
2560 }
2561
2562
2575 @Override
2576 public int getSocialUsersCount(long userId, int type)
2577 throws PortalException, SystemException {
2578
2579 User user = userPersistence.findByPrimaryKey(userId);
2580
2581 LinkedHashMap<String, Object> params =
2582 new LinkedHashMap<String, Object>();
2583
2584 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2585
2586 return searchCount(
2587 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2588 params);
2589 }
2590
2591
2601 @Override
2602 public int getSocialUsersCount(long userId1, long userId2)
2603 throws PortalException, SystemException {
2604
2605 User user1 = userPersistence.findByPrimaryKey(userId1);
2606
2607 LinkedHashMap<String, Object> params =
2608 new LinkedHashMap<String, Object>();
2609
2610 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2611
2612 return searchCount(
2613 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2614 params);
2615 }
2616
2617
2631 @Override
2632 public int getSocialUsersCount(long userId1, long userId2, int type)
2633 throws PortalException, SystemException {
2634
2635 User user1 = userPersistence.findByPrimaryKey(userId1);
2636
2637 LinkedHashMap<String, Object> params =
2638 new LinkedHashMap<String, Object>();
2639
2640 params.put(
2641 "socialMutualRelationType",
2642 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2643
2644 return searchCount(
2645 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2646 params);
2647 }
2648
2649
2657 @Override
2658 public User getUserByContactId(long contactId)
2659 throws PortalException, SystemException {
2660
2661 return userPersistence.findByContactId(contactId);
2662 }
2663
2664
2674 @Override
2675 public User getUserByEmailAddress(long companyId, String emailAddress)
2676 throws PortalException, SystemException {
2677
2678 emailAddress = getLogin(emailAddress);
2679
2680 return userPersistence.findByC_EA(companyId, emailAddress);
2681 }
2682
2683
2692 @Override
2693 public User getUserByFacebookId(long companyId, long facebookId)
2694 throws PortalException, SystemException {
2695
2696 return userPersistence.findByC_FID(companyId, facebookId);
2697 }
2698
2699
2707 @Override
2708 public User getUserById(long userId)
2709 throws PortalException, SystemException {
2710
2711 return userPersistence.findByPrimaryKey(userId);
2712 }
2713
2714
2724 @Override
2725 public User getUserById(long companyId, long userId)
2726 throws PortalException, SystemException {
2727
2728 return userPersistence.findByC_U(companyId, userId);
2729 }
2730
2731
2740 @Override
2741 public User getUserByOpenId(long companyId, String openId)
2742 throws PortalException, SystemException {
2743
2744 return userPersistence.findByC_O(companyId, openId);
2745 }
2746
2747
2755 @Override
2756 public User getUserByPortraitId(long portraitId)
2757 throws PortalException, SystemException {
2758
2759 return userPersistence.findByPortraitId(portraitId);
2760 }
2761
2762
2771 @Override
2772 public User getUserByScreenName(long companyId, String screenName)
2773 throws PortalException, SystemException {
2774
2775 screenName = getLogin(screenName);
2776
2777 return userPersistence.findByC_SN(companyId, screenName);
2778 }
2779
2780
2790 @Override
2791 public User getUserByUuid(String uuid)
2792 throws PortalException, SystemException {
2793
2794 List<User> users = userPersistence.findByUuid(uuid);
2795
2796 if (users.isEmpty()) {
2797 throw new NoSuchUserException("{uuid=" + uuid + "}");
2798 }
2799 else {
2800 return users.get(0);
2801 }
2802 }
2803
2804
2813 @Override
2814 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2815 throws PortalException, SystemException {
2816
2817 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2818
2819 if (users.isEmpty()) {
2820 StringBundler sb = new StringBundler(5);
2821
2822 sb.append("{uuid=");
2823 sb.append(uuid);
2824 sb.append(", companyId=");
2825 sb.append(companyId);
2826 sb.append("}");
2827
2828 throw new NoSuchUserException(sb.toString());
2829 }
2830 else {
2831 return users.get(0);
2832 }
2833 }
2834
2835
2845 @Override
2846 public int getUserGroupUsersCount(long userGroupId, int status)
2847 throws PortalException, SystemException {
2848
2849 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2850 userGroupId);
2851
2852 LinkedHashMap<String, Object> params =
2853 new LinkedHashMap<String, Object>();
2854
2855 params.put("usersUserGroups", new Long(userGroupId));
2856
2857 return searchCount(userGroup.getCompanyId(), null, status, params);
2858 }
2859
2860
2870 @Override
2871 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2872 throws PortalException, SystemException {
2873
2874 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2875
2876 User user = userPersistence.findByC_EA(companyId, emailAddress);
2877
2878 return user.getUserId();
2879 }
2880
2881
2890 @Override
2891 public long getUserIdByScreenName(long companyId, String screenName)
2892 throws PortalException, SystemException {
2893
2894 screenName = getLogin(screenName);
2895
2896 User user = userPersistence.findByC_SN(companyId, screenName);
2897
2898 return user.getUserId();
2899 }
2900
2901
2911 @Override
2912 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2913 throws SystemException {
2914
2915 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2916 passwordPolicyId, User.class.getName(), userId);
2917 }
2918
2919
2934 @Override
2935 public boolean hasRoleUser(
2936 long companyId, String name, long userId, boolean inherited)
2937 throws PortalException, SystemException {
2938
2939 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2940 }
2941
2942
2952 @Override
2953 public boolean isPasswordExpired(User user)
2954 throws PortalException, SystemException {
2955
2956 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2957
2958 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2959 Date now = new Date();
2960
2961 if (user.getPasswordModifiedDate() == null) {
2962 user.setPasswordModifiedDate(now);
2963
2964 userLocalService.updateUser(user);
2965 }
2966
2967 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2968 long elapsedTime = now.getTime() - passwordStartTime;
2969
2970 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2971 return true;
2972 }
2973 else {
2974 return false;
2975 }
2976 }
2977
2978 return false;
2979 }
2980
2981
2993 @Override
2994 public boolean isPasswordExpiringSoon(User user)
2995 throws PortalException, SystemException {
2996
2997 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2998
2999 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3000 (passwordPolicy.getWarningTime() > 0)) {
3001
3002 Date now = new Date();
3003
3004 if (user.getPasswordModifiedDate() == null) {
3005 user.setPasswordModifiedDate(now);
3006
3007 userLocalService.updateUser(user);
3008 }
3009
3010 long timeModified = user.getPasswordModifiedDate().getTime();
3011 long passwordExpiresOn =
3012 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3013
3014 long timeStartWarning =
3015 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3016
3017 if (now.getTime() > timeStartWarning) {
3018 return true;
3019 }
3020 else {
3021 return false;
3022 }
3023 }
3024
3025 return false;
3026 }
3027
3028
3036 @Override
3037 public User loadGetDefaultUser(long companyId)
3038 throws PortalException, SystemException {
3039
3040 return userPersistence.findByC_DU(companyId, true);
3041 }
3042
3043
3075 @Override
3076 public List<User> search(
3077 long companyId, String keywords, int status,
3078 LinkedHashMap<String, Object> params, int start, int end,
3079 OrderByComparator obc)
3080 throws SystemException {
3081
3082 return userFinder.findByKeywords(
3083 companyId, keywords, status, params, start, end, obc);
3084 }
3085
3086
3117 @Override
3118 public Hits search(
3119 long companyId, String keywords, int status,
3120 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3121 throws SystemException {
3122
3123 String firstName = null;
3124 String middleName = null;
3125 String lastName = null;
3126 String fullName = null;
3127 String screenName = null;
3128 String emailAddress = null;
3129 String street = null;
3130 String city = null;
3131 String zip = null;
3132 String region = null;
3133 String country = null;
3134 boolean andOperator = false;
3135
3136 if (Validator.isNotNull(keywords)) {
3137 firstName = keywords;
3138 middleName = keywords;
3139 lastName = keywords;
3140 fullName = keywords;
3141 screenName = keywords;
3142 emailAddress = keywords;
3143 street = keywords;
3144 city = keywords;
3145 zip = keywords;
3146 region = keywords;
3147 country = keywords;
3148 }
3149 else {
3150 andOperator = true;
3151 }
3152
3153 if (params != null) {
3154 params.put("keywords", keywords);
3155 }
3156
3157 return search(
3158 companyId, firstName, middleName, lastName, fullName, screenName,
3159 emailAddress, street, city, zip, region, country, status, params,
3160 andOperator, start, end, sort);
3161 }
3162
3163
3203 @Override
3204 public List<User> search(
3205 long companyId, String firstName, String middleName,
3206 String lastName, String screenName, String emailAddress, int status,
3207 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3208 int end, OrderByComparator obc)
3209 throws SystemException {
3210
3211 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3212 companyId, firstName, middleName, lastName, screenName,
3213 emailAddress, status, params, andSearch, start, end, obc);
3214 }
3215
3216
3255 @Override
3256 public Hits search(
3257 long companyId, String firstName, String middleName,
3258 String lastName, String screenName, String emailAddress, int status,
3259 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3260 int end, Sort sort)
3261 throws SystemException {
3262
3263 return search(
3264 companyId, firstName, middleName, lastName, null, screenName,
3265 emailAddress, null, null, null, null, null, status, params,
3266 andSearch, start, end, sort);
3267 }
3268
3269
3283 @Override
3284 public int searchCount(
3285 long companyId, String keywords, int status,
3286 LinkedHashMap<String, Object> params)
3287 throws SystemException {
3288
3289 return userFinder.countByKeywords(companyId, keywords, status, params);
3290 }
3291
3292
3314 @Override
3315 public int searchCount(
3316 long companyId, String firstName, String middleName,
3317 String lastName, String screenName, String emailAddress, int status,
3318 LinkedHashMap<String, Object> params, boolean andSearch)
3319 throws SystemException {
3320
3321 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3322 companyId, firstName, middleName, lastName, screenName,
3323 emailAddress, status, params, andSearch);
3324 }
3325
3326
3337 @Override
3338 public void sendEmailAddressVerification(
3339 User user, String emailAddress, ServiceContext serviceContext)
3340 throws PortalException, SystemException {
3341
3342 if (user.isEmailAddressVerified() &&
3343 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3344
3345 return;
3346 }
3347
3348 Ticket ticket = ticketLocalService.addDistinctTicket(
3349 user.getCompanyId(), User.class.getName(), user.getUserId(),
3350 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3351 serviceContext);
3352
3353 String verifyEmailAddressURL =
3354 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3355 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3356
3357 long plid = serviceContext.getPlid();
3358
3359 if (plid > 0) {
3360 Layout layout = layoutLocalService.fetchLayout(plid);
3361
3362 if (layout != null) {
3363 Group group = layout.getGroup();
3364
3365 if (!layout.isPrivateLayout() && !group.isUser()) {
3366 verifyEmailAddressURL +=
3367 "&p_l_id=" + serviceContext.getPlid();
3368 }
3369 }
3370 }
3371
3372 String fromName = PrefsPropsUtil.getString(
3373 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3374 String fromAddress = PrefsPropsUtil.getString(
3375 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3376
3377 String toName = user.getFullName();
3378 String toAddress = emailAddress;
3379
3380 String subject = PrefsPropsUtil.getContent(
3381 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3382
3383 String body = PrefsPropsUtil.getContent(
3384 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3385
3386 SubscriptionSender subscriptionSender = new SubscriptionSender();
3387
3388 subscriptionSender.setBody(body);
3389 subscriptionSender.setCompanyId(user.getCompanyId());
3390 subscriptionSender.setContextAttributes(
3391 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3392 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3393 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3394 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3395 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3396 subscriptionSender.setFrom(fromAddress, fromName);
3397 subscriptionSender.setHtmlFormat(true);
3398 subscriptionSender.setMailId(
3399 "user", user.getUserId(), System.currentTimeMillis(),
3400 PwdGenerator.getPassword());
3401 subscriptionSender.setServiceContext(serviceContext);
3402 subscriptionSender.setSubject(subject);
3403 subscriptionSender.setUserId(user.getUserId());
3404
3405 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3406
3407 subscriptionSender.flushNotificationsAsync();
3408 }
3409
3410
3429 @Override
3430 public void sendPassword(
3431 long companyId, String emailAddress, String fromName,
3432 String fromAddress, String subject, String body,
3433 ServiceContext serviceContext)
3434 throws PortalException, SystemException {
3435
3436 Company company = companyPersistence.findByPrimaryKey(companyId);
3437
3438 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3439 return;
3440 }
3441
3442 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3443
3444 if (Validator.isNull(emailAddress)) {
3445 throw new UserEmailAddressException();
3446 }
3447
3448 User user = userPersistence.findByC_EA(companyId, emailAddress);
3449
3450 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3451
3452 String newPassword = StringPool.BLANK;
3453 String passwordResetURL = StringPool.BLANK;
3454
3455 if (company.isSendPasswordResetLink()) {
3456 Date expirationDate = null;
3457
3458 if ((passwordPolicy != null) &&
3459 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3460
3461 expirationDate = new Date(
3462 System.currentTimeMillis() +
3463 (passwordPolicy.getResetTicketMaxAge() * 1000));
3464 }
3465
3466 Ticket ticket = ticketLocalService.addDistinctTicket(
3467 companyId, User.class.getName(), user.getUserId(),
3468 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3469 serviceContext);
3470
3471 passwordResetURL =
3472 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3473 "/portal/update_password?p_l_id="+
3474 serviceContext.getPlid() +
3475 "&ticketKey=" + ticket.getKey();
3476 }
3477 else {
3478 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3479 PasswordEncryptorUtil.TYPE_NONE)) {
3480
3481 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3482 user.getCompanyId())) {
3483
3484 if (_log.isWarnEnabled()) {
3485 StringBundler sb = new StringBundler(5);
3486
3487 sb.append("When LDAP password policy is enabled, ");
3488 sb.append("it is possible that portal generated ");
3489 sb.append("passwords will not match the LDAP policy.");
3490 sb.append("Using RegExpToolkit to generate new ");
3491 sb.append("password.");
3492
3493 _log.warn(sb.toString());
3494 }
3495
3496 RegExpToolkit regExpToolkit = new RegExpToolkit();
3497
3498 newPassword = regExpToolkit.generate(null);
3499 }
3500 else {
3501 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3502 }
3503
3504 boolean passwordReset = false;
3505
3506 if (passwordPolicy.getChangeable() &&
3507 passwordPolicy.getChangeRequired()) {
3508
3509 passwordReset = true;
3510 }
3511
3512 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3513 user.setPasswordUnencrypted(newPassword);
3514 user.setPasswordEncrypted(true);
3515 user.setPasswordReset(passwordReset);
3516 user.setPasswordModified(true);
3517 user.setPasswordModifiedDate(new Date());
3518
3519 userPersistence.update(user);
3520
3521 user.setPasswordModified(false);
3522 }
3523 else {
3524 newPassword = user.getPassword();
3525 }
3526 }
3527
3528 if (Validator.isNull(fromName)) {
3529 fromName = PrefsPropsUtil.getString(
3530 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3531 }
3532
3533 if (Validator.isNull(fromAddress)) {
3534 fromAddress = PrefsPropsUtil.getString(
3535 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3536 }
3537
3538 String toName = user.getFullName();
3539 String toAddress = user.getEmailAddress();
3540
3541 if (Validator.isNull(subject)) {
3542 if (company.isSendPasswordResetLink()) {
3543 subject = PrefsPropsUtil.getContent(
3544 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3545 }
3546 else {
3547 subject = PrefsPropsUtil.getContent(
3548 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3549 }
3550 }
3551
3552 if (Validator.isNull(body)) {
3553 if (company.isSendPasswordResetLink()) {
3554 body = PrefsPropsUtil.getContent(
3555 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3556 }
3557 else {
3558 body = PrefsPropsUtil.getContent(
3559 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3560 }
3561 }
3562
3563 SubscriptionSender subscriptionSender = new SubscriptionSender();
3564
3565 subscriptionSender.setBody(body);
3566 subscriptionSender.setCompanyId(companyId);
3567 subscriptionSender.setContextAttributes(
3568 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3569 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3570 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3571 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3572 user.getScreenName());
3573 subscriptionSender.setFrom(fromAddress, fromName);
3574 subscriptionSender.setHtmlFormat(true);
3575 subscriptionSender.setMailId(
3576 "user", user.getUserId(), System.currentTimeMillis(),
3577 PwdGenerator.getPassword());
3578 subscriptionSender.setServiceContext(serviceContext);
3579 subscriptionSender.setSubject(subject);
3580 subscriptionSender.setUserId(user.getUserId());
3581
3582 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3583
3584 subscriptionSender.flushNotificationsAsync();
3585 }
3586
3587
3596 @Override
3597 public void setRoleUsers(long roleId, long[] userIds)
3598 throws PortalException, SystemException {
3599
3600 rolePersistence.setUsers(roleId, userIds);
3601
3602 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3603
3604 indexer.reindex(userIds);
3605
3606 PermissionCacheUtil.clearCache();
3607 }
3608
3609
3618 @Override
3619 @SuppressWarnings("deprecation")
3620 public void setUserGroupUsers(long userGroupId, long[] userIds)
3621 throws PortalException, SystemException {
3622
3623 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3624 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3625 }
3626
3627 userGroupPersistence.setUsers(userGroupId, userIds);
3628
3629 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3630
3631 indexer.reindex(userIds);
3632
3633 PermissionCacheUtil.clearCache();
3634 }
3635
3636
3644 @Override
3645 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3646 throws PortalException, SystemException {
3647
3648 List<Team> teams = teamPersistence.findByGroupId(groupId);
3649
3650 for (Team team : teams) {
3651 unsetTeamUsers(team.getTeamId(), userIds);
3652 }
3653
3654 PermissionCacheUtil.clearCache();
3655 }
3656
3657
3667 @Override
3668 public void unsetGroupUsers(
3669 final long groupId, final long[] userIds,
3670 ServiceContext serviceContext)
3671 throws PortalException, SystemException {
3672
3673 userGroupRoleLocalService.deleteUserGroupRoles(
3674 userIds, groupId, RoleConstants.TYPE_SITE);
3675
3676 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3677
3678 groupPersistence.removeUsers(groupId, userIds);
3679
3680 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3681
3682 indexer.reindex(userIds);
3683
3684 PermissionCacheUtil.clearCache();
3685
3686 Callable<Void> callable = new Callable<Void>() {
3687
3688 @Override
3689 public Void call() throws Exception {
3690 Message message = new Message();
3691
3692 message.put("groupId", groupId);
3693 message.put("userIds", userIds);
3694
3695 MessageBusUtil.sendMessage(
3696 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3697
3698 return null;
3699 }
3700
3701 };
3702
3703 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3704 }
3705
3706
3714 @Override
3715 public void unsetOrganizationUsers(
3716 long organizationId, final long[] userIds)
3717 throws PortalException, SystemException {
3718
3719 Organization organization = organizationPersistence.findByPrimaryKey(
3720 organizationId);
3721
3722 final Group group = organization.getGroup();
3723
3724 userGroupRoleLocalService.deleteUserGroupRoles(
3725 userIds, group.getGroupId());
3726
3727 organizationPersistence.removeUsers(organizationId, userIds);
3728
3729 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3730
3731 indexer.reindex(userIds);
3732
3733 PermissionCacheUtil.clearCache();
3734
3735 Callable<Void> callable = new Callable<Void>() {
3736
3737 @Override
3738 public Void call() throws Exception {
3739 Message message = new Message();
3740
3741 message.put("groupId", group.getGroupId());
3742 message.put("userIds", userIds);
3743
3744 MessageBusUtil.sendMessage(
3745 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3746
3747 return null;
3748 }
3749
3750 };
3751
3752 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3753 }
3754
3755
3762 @Override
3763 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3764 throws SystemException {
3765
3766 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3767 passwordPolicyId, User.class.getName(), userIds);
3768 }
3769
3770
3778 @Override
3779 public void unsetRoleUsers(long roleId, List<User> users)
3780 throws PortalException, SystemException {
3781
3782 Role role = rolePersistence.findByPrimaryKey(roleId);
3783
3784 String roleName = role.getName();
3785
3786 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3787 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3788 roleName.equals(RoleConstants.USER)) {
3789
3790 return;
3791 }
3792
3793 rolePersistence.removeUsers(roleId, users);
3794
3795 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3796
3797 indexer.reindex(users);
3798
3799 PermissionCacheUtil.clearCache();
3800 }
3801
3802
3810 @Override
3811 public void unsetRoleUsers(long roleId, long[] userIds)
3812 throws PortalException, SystemException {
3813
3814 Role role = rolePersistence.findByPrimaryKey(roleId);
3815
3816 String roleName = role.getName();
3817
3818 if (roleName.equals(RoleConstants.USER) ||
3819 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3820 getRoleUsersCount(role.getRoleId()) <= 1)) {
3821
3822 return;
3823 }
3824
3825 rolePersistence.removeUsers(roleId, userIds);
3826
3827 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3828
3829 indexer.reindex(userIds);
3830
3831 PermissionCacheUtil.clearCache();
3832 }
3833
3834
3842 @Override
3843 public void unsetTeamUsers(long teamId, long[] userIds)
3844 throws PortalException, SystemException {
3845
3846 teamPersistence.removeUsers(teamId, userIds);
3847
3848 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3849
3850 indexer.reindex(userIds);
3851
3852 PermissionCacheUtil.clearCache();
3853 }
3854
3855
3863 @Override
3864 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3865 throws PortalException, SystemException {
3866
3867 userGroupPersistence.removeUsers(userGroupId, userIds);
3868
3869 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3870
3871 indexer.reindex(userIds);
3872
3873 PermissionCacheUtil.clearCache();
3874 }
3875
3876
3886 @Override
3887 public User updateAgreedToTermsOfUse(
3888 long userId, boolean agreedToTermsOfUse)
3889 throws PortalException, SystemException {
3890
3891 User user = userPersistence.findByPrimaryKey(userId);
3892
3893 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3894
3895 userPersistence.update(user);
3896
3897 return user;
3898 }
3899
3900
3911 @Override
3912 public void updateAsset(
3913 long userId, User user, long[] assetCategoryIds,
3914 String[] assetTagNames)
3915 throws PortalException, SystemException {
3916
3917 User owner = userPersistence.findByPrimaryKey(userId);
3918
3919 Company company = companyPersistence.findByPrimaryKey(
3920 owner.getCompanyId());
3921
3922 Group companyGroup = company.getGroup();
3923
3924 assetEntryLocalService.updateEntry(
3925 userId, companyGroup.getGroupId(), user.getCreateDate(),
3926 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3927 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3928 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3929 null, false);
3930 }
3931
3932
3941 @Override
3942 public User updateCreateDate(long userId, Date createDate)
3943 throws PortalException, SystemException {
3944
3945 User user = userPersistence.findByPrimaryKey(userId);
3946
3947 user.setCreateDate(createDate);
3948
3949 userPersistence.update(user);
3950
3951 return user;
3952 }
3953
3954
3965 @Override
3966 public User updateEmailAddress(
3967 long userId, String password, String emailAddress1,
3968 String emailAddress2)
3969 throws PortalException, SystemException {
3970
3971 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
3972 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
3973
3974 User user = userPersistence.findByPrimaryKey(userId);
3975
3976 validateEmailAddress(user, emailAddress1, emailAddress2);
3977
3978 setEmailAddress(
3979 user, password, user.getFirstName(), user.getMiddleName(),
3980 user.getLastName(), emailAddress1);
3981
3982 userPersistence.update(user);
3983
3984 Contact contact = user.getContact();
3985
3986 contact.setEmailAddress(user.getEmailAddress());
3987
3988 contactPersistence.update(contact);
3989
3990 return user;
3991 }
3992
3993
4007 @Override
4008 public User updateEmailAddress(
4009 long userId, String password, String emailAddress1,
4010 String emailAddress2, ServiceContext serviceContext)
4011 throws PortalException, SystemException {
4012
4013 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4014 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4015
4016 User user = userPersistence.findByPrimaryKey(userId);
4017
4018 validateEmailAddress(user, emailAddress1, emailAddress2);
4019
4020 Company company = companyPersistence.findByPrimaryKey(
4021 user.getCompanyId());
4022
4023 if (company.isStrangersVerify() &&
4024 !StringUtil.equalsIgnoreCase(
4025 emailAddress1, user.getEmailAddress())) {
4026
4027 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4028 }
4029 else {
4030 setEmailAddress(
4031 user, password, user.getFirstName(), user.getMiddleName(),
4032 user.getLastName(), emailAddress1);
4033
4034 userPersistence.update(user);
4035
4036 Contact contact = user.getContact();
4037
4038 contact.setEmailAddress(user.getEmailAddress());
4039
4040 contactPersistence.update(contact);
4041 }
4042
4043 return user;
4044 }
4045
4046
4055 @Override
4056 public User updateEmailAddressVerified(
4057 long userId, boolean emailAddressVerified)
4058 throws PortalException, SystemException {
4059
4060 User user = userPersistence.findByPrimaryKey(userId);
4061
4062 user.setEmailAddressVerified(emailAddressVerified);
4063
4064 userPersistence.update(user);
4065
4066 return user;
4067 }
4068
4069
4078 @Override
4079 public User updateFacebookId(long userId, long facebookId)
4080 throws PortalException, SystemException {
4081
4082 User user = userPersistence.findByPrimaryKey(userId);
4083
4084 user.setFacebookId(facebookId);
4085
4086 userPersistence.update(user);
4087
4088 return user;
4089 }
4090
4091
4101 @Override
4102 public void updateGroups(
4103 long userId, long[] newGroupIds, ServiceContext serviceContext)
4104 throws PortalException, SystemException {
4105
4106 boolean indexingEnabled = true;
4107
4108 if (serviceContext != null) {
4109 indexingEnabled = serviceContext.isIndexingEnabled();
4110 }
4111
4112 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4113 }
4114
4115
4154 @Override
4155 public User updateIncompleteUser(
4156 long creatorUserId, long companyId, boolean autoPassword,
4157 String password1, String password2, boolean autoScreenName,
4158 String screenName, String emailAddress, long facebookId,
4159 String openId, Locale locale, String firstName, String middleName,
4160 String lastName, int prefixId, int suffixId, boolean male,
4161 int birthdayMonth, int birthdayDay, int birthdayYear,
4162 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4163 ServiceContext serviceContext)
4164 throws PortalException, SystemException {
4165
4166 User user = getUserByEmailAddress(companyId, emailAddress);
4167
4168 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4169 throw new PortalException("Invalid user status");
4170 }
4171
4172 User defaultUser = getDefaultUser(companyId);
4173
4174 if (facebookId > 0) {
4175 autoPassword = false;
4176
4177 if ((password1 == null) || (password2 == null)) {
4178 password1 = PwdGenerator.getPassword();
4179 password2 = password1;
4180 }
4181
4182 sendEmail = false;
4183 }
4184
4185 if (updateUserInformation) {
4186 autoScreenName = false;
4187
4188 if (PrefsPropsUtil.getBoolean(
4189 companyId,
4190 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4191
4192 autoScreenName = true;
4193 }
4194
4195 validate(
4196 companyId, user.getUserId(), autoPassword, password1, password2,
4197 autoScreenName, screenName, emailAddress, openId, firstName,
4198 middleName, lastName, null);
4199
4200 if (!autoPassword) {
4201 if (Validator.isNull(password1) ||
4202 Validator.isNull(password2)) {
4203 throw new UserPasswordException(
4204 UserPasswordException.PASSWORD_INVALID);
4205 }
4206 }
4207
4208 if (autoScreenName) {
4209 ScreenNameGenerator screenNameGenerator =
4210 ScreenNameGeneratorFactory.getInstance();
4211
4212 try {
4213 screenName = screenNameGenerator.generate(
4214 companyId, user.getUserId(), emailAddress);
4215 }
4216 catch (Exception e) {
4217 throw new SystemException(e);
4218 }
4219 }
4220
4221 FullNameGenerator fullNameGenerator =
4222 FullNameGeneratorFactory.getInstance();
4223
4224 String fullName = fullNameGenerator.getFullName(
4225 firstName, middleName, lastName);
4226
4227 String greeting = LanguageUtil.format(
4228 locale, "welcome-x", " " + fullName, false);
4229
4230 if (Validator.isNotNull(password1)) {
4231 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4232 user.setPasswordUnencrypted(password1);
4233 }
4234
4235 user.setPasswordEncrypted(true);
4236
4237 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4238
4239 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4240 passwordPolicy.isChangeRequired()) {
4241
4242 user.setPasswordReset(true);
4243 }
4244 else {
4245 user.setPasswordReset(false);
4246 }
4247
4248 user.setScreenName(screenName);
4249 user.setFacebookId(facebookId);
4250 user.setOpenId(openId);
4251 user.setLanguageId(locale.toString());
4252 user.setTimeZoneId(defaultUser.getTimeZoneId());
4253 user.setGreeting(greeting);
4254 user.setFirstName(firstName);
4255 user.setMiddleName(middleName);
4256 user.setLastName(lastName);
4257 user.setJobTitle(jobTitle);
4258 user.setExpandoBridgeAttributes(serviceContext);
4259
4260 Date birthday = getBirthday(
4261 birthdayMonth, birthdayDay, birthdayYear);
4262
4263 Contact contact = user.getContact();
4264
4265 contact.setFirstName(firstName);
4266 contact.setMiddleName(middleName);
4267 contact.setLastName(lastName);
4268 contact.setPrefixId(prefixId);
4269 contact.setSuffixId(suffixId);
4270 contact.setMale(male);
4271 contact.setBirthday(birthday);
4272 contact.setJobTitle(jobTitle);
4273
4274 contactPersistence.update(contact, serviceContext);
4275
4276
4277
4278 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4279 User.class);
4280
4281 indexer.reindex(user);
4282 }
4283
4284 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4285
4286 userPersistence.update(user, serviceContext);
4287
4288
4289
4290 long workflowUserId = creatorUserId;
4291
4292 if (workflowUserId == user.getUserId()) {
4293 workflowUserId = defaultUser.getUserId();
4294 }
4295
4296 ServiceContext workflowServiceContext = serviceContext;
4297
4298 if (workflowServiceContext == null) {
4299 workflowServiceContext = new ServiceContext();
4300 }
4301
4302 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4303 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4304 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4305
4306 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4307 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4308 user, workflowServiceContext);
4309
4310 return getUserByEmailAddress(companyId, emailAddress);
4311 }
4312
4313
4323 @Override
4324 public User updateJobTitle(long userId, String jobTitle)
4325 throws PortalException, SystemException {
4326
4327 User user = userPersistence.findByPrimaryKey(userId);
4328
4329 user.setJobTitle(jobTitle);
4330
4331 userPersistence.update(user);
4332
4333 Contact contact = contactPersistence.findByPrimaryKey(
4334 user.getContactId());
4335
4336 contact.setJobTitle(jobTitle);
4337
4338 contactPersistence.update(contact);
4339
4340 return user;
4341 }
4342
4343
4352 @Override
4353 public User updateLastLogin(long userId, String loginIP)
4354 throws PortalException, SystemException {
4355
4356 User user = userPersistence.findByPrimaryKey(userId);
4357
4358 Date lastLoginDate = user.getLoginDate();
4359
4360 if (lastLoginDate == null) {
4361 lastLoginDate = new Date();
4362 }
4363
4364 user.setLoginDate(new Date());
4365 user.setLoginIP(loginIP);
4366 user.setLastLoginDate(lastLoginDate);
4367 user.setLastLoginIP(user.getLoginIP());
4368 user.setFailedLoginAttempts(0);
4369
4370 userPersistence.update(user);
4371
4372 return user;
4373 }
4374
4375
4384 @Override
4385 public User updateLockout(User user, boolean lockout)
4386 throws PortalException, SystemException {
4387
4388 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4389
4390 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4391 return user;
4392 }
4393
4394 Date lockoutDate = null;
4395
4396 if (lockout) {
4397 lockoutDate = new Date();
4398 }
4399
4400 user.setLockout(lockout);
4401 user.setLockoutDate(lockoutDate);
4402
4403 if (!lockout) {
4404 user.setLastFailedLoginDate(lockoutDate);
4405 user.setFailedLoginAttempts(0);
4406 }
4407
4408 userPersistence.update(user);
4409
4410 return user;
4411 }
4412
4413
4424 @Override
4425 public User updateLockoutByEmailAddress(
4426 long companyId, String emailAddress, boolean lockout)
4427 throws PortalException, SystemException {
4428
4429 User user = getUserByEmailAddress(companyId, emailAddress);
4430
4431 return updateLockout(user, lockout);
4432 }
4433
4434
4443 @Override
4444 public User updateLockoutById(long userId, boolean lockout)
4445 throws PortalException, SystemException {
4446
4447 User user = userPersistence.findByPrimaryKey(userId);
4448
4449 return updateLockout(user, lockout);
4450 }
4451
4452
4462 @Override
4463 public User updateLockoutByScreenName(
4464 long companyId, String screenName, boolean lockout)
4465 throws PortalException, SystemException {
4466
4467 User user = getUserByScreenName(companyId, screenName);
4468
4469 return updateLockout(user, lockout);
4470 }
4471
4472
4481 @Override
4482 public User updateModifiedDate(long userId, Date modifiedDate)
4483 throws PortalException, SystemException {
4484
4485 User user = userPersistence.findByPrimaryKey(userId);
4486
4487 user.setModifiedDate(modifiedDate);
4488
4489 userPersistence.update(user);
4490
4491 return user;
4492 }
4493
4494
4503 @Override
4504 public User updateOpenId(long userId, String openId)
4505 throws PortalException, SystemException {
4506
4507 openId = openId.trim();
4508
4509 User user = userPersistence.findByPrimaryKey(userId);
4510
4511 user.setOpenId(openId);
4512
4513 userPersistence.update(user);
4514
4515 return user;
4516 }
4517
4518
4529 @Override
4530 public void updateOrganizations(
4531 long userId, long[] newOrganizationIds,
4532 ServiceContext serviceContext)
4533 throws PortalException, SystemException {
4534
4535 updateOrganizations(
4536 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4537 }
4538
4539
4551 @Override
4552 public User updatePassword(
4553 long userId, String password1, String password2,
4554 boolean passwordReset)
4555 throws PortalException, SystemException {
4556
4557 return updatePassword(
4558 userId, password1, password2, passwordReset, false);
4559 }
4560
4561
4576 @Override
4577 public User updatePassword(
4578 long userId, String password1, String password2,
4579 boolean passwordReset, boolean silentUpdate)
4580 throws PortalException, SystemException {
4581
4582 User user = userPersistence.findByPrimaryKey(userId);
4583
4584 if (!silentUpdate) {
4585 validatePassword(user.getCompanyId(), userId, password1, password2);
4586 }
4587
4588 String oldEncPwd = user.getPassword();
4589
4590 if (!user.isPasswordEncrypted()) {
4591 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4592 }
4593
4594 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4595
4596 if (user.hasCompanyMx()) {
4597 mailService.updatePassword(user.getCompanyId(), userId, password1);
4598 }
4599
4600 user.setPassword(newEncPwd);
4601 user.setPasswordUnencrypted(password1);
4602 user.setPasswordEncrypted(true);
4603 user.setPasswordReset(passwordReset);
4604 user.setPasswordModifiedDate(new Date());
4605 user.setDigest(StringPool.BLANK);
4606 user.setGraceLoginCount(0);
4607
4608 if (!silentUpdate) {
4609 user.setPasswordModified(true);
4610 }
4611
4612 try {
4613 userPersistence.update(user);
4614 }
4615 catch (ModelListenerException mle) {
4616 String msg = GetterUtil.getString(mle.getCause().getMessage());
4617
4618 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4619 String passwordHistory = PrefsPropsUtil.getString(
4620 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4621
4622 if (msg.contains(passwordHistory)) {
4623 throw new UserPasswordException(
4624 UserPasswordException.PASSWORD_ALREADY_USED);
4625 }
4626 }
4627
4628 throw new UserPasswordException(
4629 UserPasswordException.PASSWORD_INVALID);
4630 }
4631
4632 if (!silentUpdate) {
4633 user.setPasswordModified(false);
4634
4635 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4636 }
4637
4638 return user;
4639 }
4640
4641
4655 @Override
4656 public User updatePasswordManually(
4657 long userId, String password, boolean passwordEncrypted,
4658 boolean passwordReset, Date passwordModifiedDate)
4659 throws PortalException, SystemException {
4660
4661
4662
4663 User user = userPersistence.findByPrimaryKey(userId);
4664
4665 user.setPassword(password);
4666 user.setPasswordEncrypted(passwordEncrypted);
4667 user.setPasswordReset(passwordReset);
4668 user.setPasswordModifiedDate(passwordModifiedDate);
4669 user.setDigest(StringPool.BLANK);
4670
4671 userPersistence.update(user);
4672
4673 return user;
4674 }
4675
4676
4687 @Override
4688 public User updatePasswordReset(long userId, boolean passwordReset)
4689 throws PortalException, SystemException {
4690
4691 User user = userPersistence.findByPrimaryKey(userId);
4692
4693 user.setPasswordReset(passwordReset);
4694
4695 userPersistence.update(user);
4696
4697 return user;
4698 }
4699
4700
4710 @Override
4711 public User updatePortrait(long userId, byte[] bytes)
4712 throws PortalException, SystemException {
4713
4714 User user = userPersistence.findByPrimaryKey(userId);
4715
4716 long imageMaxSize = PrefsPropsUtil.getLong(
4717 PropsKeys.USERS_IMAGE_MAX_SIZE);
4718
4719 if ((imageMaxSize > 0) &&
4720 ((bytes == null) || (bytes.length > imageMaxSize))) {
4721
4722 throw new UserPortraitSizeException();
4723 }
4724
4725 long portraitId = user.getPortraitId();
4726
4727 if (portraitId <= 0) {
4728 portraitId = counterLocalService.increment();
4729
4730 user.setPortraitId(portraitId);
4731 }
4732
4733 try {
4734 ImageBag imageBag = ImageToolUtil.read(bytes);
4735
4736 RenderedImage renderedImage = imageBag.getRenderedImage();
4737
4738 if (renderedImage == null) {
4739 throw new UserPortraitTypeException();
4740 }
4741
4742 renderedImage = ImageToolUtil.scale(
4743 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4744 PropsValues.USERS_IMAGE_MAX_WIDTH);
4745
4746 String contentType = imageBag.getType();
4747
4748 imageLocalService.updateImage(
4749 portraitId,
4750 ImageToolUtil.getBytes(renderedImage, contentType));
4751 }
4752 catch (IOException ioe) {
4753 throw new ImageSizeException(ioe);
4754 }
4755
4756 userPersistence.update(user);
4757
4758 return user;
4759 }
4760
4761
4772 @Override
4773 public User updateReminderQuery(long userId, String question, String answer)
4774 throws PortalException, SystemException {
4775
4776 validateReminderQuery(question, answer);
4777
4778 User user = userPersistence.findByPrimaryKey(userId);
4779
4780 user.setReminderQueryQuestion(question);
4781 user.setReminderQueryAnswer(answer);
4782
4783 userPersistence.update(user);
4784
4785 return user;
4786 }
4787
4788
4798 @Override
4799 public User updateScreenName(long userId, String screenName)
4800 throws PortalException, SystemException {
4801
4802
4803
4804 User user = userPersistence.findByPrimaryKey(userId);
4805
4806 screenName = getLogin(screenName);
4807
4808 validateScreenName(user.getCompanyId(), userId, screenName);
4809
4810 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4811 user.setDigest(StringPool.BLANK);
4812 }
4813
4814 user.setScreenName(screenName);
4815
4816 userPersistence.update(user);
4817
4818
4819
4820 Group group = groupLocalService.getUserGroup(
4821 user.getCompanyId(), userId);
4822
4823 group.setFriendlyURL(StringPool.SLASH + screenName);
4824
4825 groupPersistence.update(group);
4826
4827 return user;
4828 }
4829
4830
4842 @Deprecated
4843 @Override
4844 public User updateStatus(long userId, int status)
4845 throws PortalException, SystemException {
4846
4847 return updateStatus(userId, status, new ServiceContext());
4848 }
4849
4850
4862 @Override
4863 public User updateStatus(
4864 long userId, int status, ServiceContext serviceContext)
4865 throws PortalException, SystemException {
4866
4867 User user = userPersistence.findByPrimaryKey(userId);
4868
4869 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4870 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4871
4872 validateCompanyMaxUsers(user.getCompanyId());
4873 }
4874
4875 String passwordUnencrypted = (String)serviceContext.getAttribute(
4876 "passwordUnencrypted");
4877
4878 if (Validator.isNotNull(passwordUnencrypted)) {
4879 user.setPasswordUnencrypted(passwordUnencrypted);
4880 }
4881
4882 user.setStatus(status);
4883
4884 userPersistence.update(user);
4885
4886 reindex(user);
4887
4888 return user;
4889 }
4890
4891
4947 @Override
4948 @SuppressWarnings("deprecation")
4949 public User updateUser(
4950 long userId, String oldPassword, String newPassword1,
4951 String newPassword2, boolean passwordReset,
4952 String reminderQueryQuestion, String reminderQueryAnswer,
4953 String screenName, String emailAddress, long facebookId,
4954 String openId, String languageId, String timeZoneId,
4955 String greeting, String comments, String firstName,
4956 String middleName, String lastName, int prefixId, int suffixId,
4957 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4958 String smsSn, String aimSn, String facebookSn, String icqSn,
4959 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4960 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4961 long[] organizationIds, long[] roleIds,
4962 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4963 ServiceContext serviceContext)
4964 throws PortalException, SystemException {
4965
4966
4967
4968 User user = userPersistence.findByPrimaryKey(userId);
4969 Company company = companyPersistence.findByPrimaryKey(
4970 user.getCompanyId());
4971 String password = oldPassword;
4972 screenName = getLogin(screenName);
4973 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
4974 openId = openId.trim();
4975 String oldFullName = user.getFullName();
4976 aimSn = StringUtil.toLowerCase(aimSn.trim());
4977 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
4978 icqSn = StringUtil.toLowerCase(icqSn.trim());
4979 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
4980 msnSn = StringUtil.toLowerCase(msnSn.trim());
4981 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
4982 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
4983 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
4984 ymSn = StringUtil.toLowerCase(ymSn.trim());
4985 Date now = new Date();
4986
4987 EmailAddressGenerator emailAddressGenerator =
4988 EmailAddressGeneratorFactory.getInstance();
4989
4990 if (emailAddressGenerator.isGenerated(emailAddress)) {
4991 emailAddress = StringPool.BLANK;
4992 }
4993
4994 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4995 Validator.isNull(emailAddress)) {
4996
4997 emailAddress = emailAddressGenerator.generate(
4998 user.getCompanyId(), userId);
4999 }
5000
5001 validate(
5002 userId, screenName, emailAddress, openId, firstName, middleName,
5003 lastName, smsSn);
5004
5005 if (Validator.isNotNull(newPassword1) ||
5006 Validator.isNotNull(newPassword2)) {
5007
5008 user = updatePassword(
5009 userId, newPassword1, newPassword2, passwordReset);
5010
5011 password = newPassword1;
5012
5013 user.setDigest(StringPool.BLANK);
5014 }
5015
5016 user.setModifiedDate(now);
5017
5018 if (user.getContactId() <= 0) {
5019 user.setContactId(counterLocalService.increment());
5020 }
5021
5022 user.setPasswordReset(passwordReset);
5023
5024 if (Validator.isNotNull(reminderQueryQuestion) &&
5025 Validator.isNotNull(reminderQueryAnswer)) {
5026
5027 user.setReminderQueryQuestion(reminderQueryQuestion);
5028 user.setReminderQueryAnswer(reminderQueryAnswer);
5029 }
5030
5031 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5032 user.setScreenName(screenName);
5033
5034 user.setDigest(StringPool.BLANK);
5035 }
5036
5037 boolean sendEmailAddressVerification = false;
5038
5039 if (company.isStrangersVerify() &&
5040 !StringUtil.equalsIgnoreCase(
5041 emailAddress, user.getEmailAddress())) {
5042
5043 sendEmailAddressVerification = true;
5044 }
5045 else {
5046 setEmailAddress(
5047 user, password, firstName, middleName, lastName, emailAddress);
5048 }
5049
5050 if (serviceContext != null) {
5051 String uuid = serviceContext.getUuid();
5052
5053 if (Validator.isNotNull(uuid)) {
5054 user.setUuid(uuid);
5055 }
5056 }
5057
5058 user.setFacebookId(facebookId);
5059
5060 Long ldapServerId = null;
5061
5062 if (serviceContext != null) {
5063 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5064 }
5065
5066 if (ldapServerId != null) {
5067 user.setLdapServerId(ldapServerId);
5068 }
5069
5070 user.setOpenId(openId);
5071 user.setLanguageId(languageId);
5072 user.setTimeZoneId(timeZoneId);
5073 user.setGreeting(greeting);
5074 user.setComments(comments);
5075 user.setFirstName(firstName);
5076 user.setMiddleName(middleName);
5077 user.setLastName(lastName);
5078 user.setJobTitle(jobTitle);
5079 user.setExpandoBridgeAttributes(serviceContext);
5080
5081 userPersistence.update(user, serviceContext);
5082
5083
5084
5085 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5086
5087 long contactId = user.getContactId();
5088
5089 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5090
5091 if (contact == null) {
5092 contact = contactPersistence.create(contactId);
5093
5094 contact.setCompanyId(user.getCompanyId());
5095 contact.setUserName(StringPool.BLANK);
5096 contact.setCreateDate(now);
5097 contact.setClassName(User.class.getName());
5098 contact.setClassPK(user.getUserId());
5099 contact.setAccountId(company.getAccountId());
5100 contact.setParentContactId(
5101 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5102 }
5103
5104 contact.setModifiedDate(now);
5105 contact.setEmailAddress(user.getEmailAddress());
5106 contact.setFirstName(firstName);
5107 contact.setMiddleName(middleName);
5108 contact.setLastName(lastName);
5109 contact.setPrefixId(prefixId);
5110 contact.setSuffixId(suffixId);
5111 contact.setMale(male);
5112 contact.setBirthday(birthday);
5113 contact.setSmsSn(smsSn);
5114 contact.setAimSn(aimSn);
5115 contact.setFacebookSn(facebookSn);
5116 contact.setIcqSn(icqSn);
5117 contact.setJabberSn(jabberSn);
5118 contact.setMsnSn(msnSn);
5119 contact.setMySpaceSn(mySpaceSn);
5120 contact.setSkypeSn(skypeSn);
5121 contact.setTwitterSn(twitterSn);
5122 contact.setYmSn(ymSn);
5123 contact.setJobTitle(jobTitle);
5124
5125 contactPersistence.update(contact, serviceContext);
5126
5127
5128
5129 Group group = groupLocalService.getUserGroup(
5130 user.getCompanyId(), userId);
5131
5132 group.setFriendlyURL(StringPool.SLASH + screenName);
5133
5134 groupPersistence.update(group);
5135
5136
5137
5138
5139
5140
5141
5142 List<UserGroupRole> previousUserGroupRoles =
5143 userGroupRolePersistence.findByUserId(userId);
5144
5145 updateGroups(userId, groupIds, serviceContext, false);
5146 updateOrganizations(userId, organizationIds, false);
5147
5148
5149
5150 if (roleIds != null) {
5151 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5152
5153 userPersistence.setRoles(userId, roleIds);
5154 }
5155
5156
5157
5158 updateUserGroupRoles(
5159 user, groupIds, organizationIds, userGroupRoles,
5160 previousUserGroupRoles);
5161
5162
5163
5164 if (userGroupIds != null) {
5165 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5166 userGroupLocalService.copyUserGroupLayouts(
5167 userGroupIds, userId);
5168 }
5169
5170 userPersistence.setUserGroups(userId, userGroupIds);
5171 }
5172
5173
5174
5175 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5176
5177
5178
5179 if (serviceContext != null) {
5180 updateAsset(
5181 userId, user, serviceContext.getAssetCategoryIds(),
5182 serviceContext.getAssetTagNames());
5183 }
5184
5185
5186
5187 if (GetterUtil.getBoolean(
5188 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5189 !oldFullName.equals(user.getFullName())) {
5190
5191 mbMessageLocalService.updateUserName(userId, user.getFullName());
5192 }
5193
5194
5195
5196 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5197 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5198 User.class);
5199
5200 indexer.reindex(user);
5201 }
5202
5203
5204
5205 if ((serviceContext != null) && sendEmailAddressVerification) {
5206 sendEmailAddressVerification(user, emailAddress, serviceContext);
5207 }
5208
5209
5210
5211 PermissionCacheUtil.clearCache();
5212
5213 return user;
5214 }
5215
5216
5225 @Override
5226 public void verifyEmailAddress(String ticketKey)
5227 throws PortalException, SystemException {
5228
5229 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5230
5231 if (ticket.isExpired() ||
5232 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5233
5234 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5235 }
5236
5237 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5238
5239 String emailAddress = ticket.getExtraInfo();
5240
5241 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5242
5243 if (!emailAddress.equals(user.getEmailAddress())) {
5244 if (userPersistence.fetchByC_EA(
5245 user.getCompanyId(), emailAddress) != null) {
5246
5247 throw new DuplicateUserEmailAddressException(
5248 "{userId=" + user.getUserId() + "}");
5249 }
5250
5251 setEmailAddress(
5252 user, StringPool.BLANK, user.getFirstName(),
5253 user.getMiddleName(), user.getLastName(), emailAddress);
5254
5255 Contact contact = user.getContact();
5256
5257 contact.setEmailAddress(user.getEmailAddress());
5258
5259 contactPersistence.update(contact);
5260 }
5261
5262 user.setEmailAddressVerified(true);
5263
5264 userPersistence.update(user);
5265
5266 ticketLocalService.deleteTicket(ticket);
5267 }
5268
5269 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5270 throws PortalException, SystemException {
5271
5272 List<Role> defaultSiteRoles = new ArrayList<Role>();
5273
5274 Group group = groupLocalService.getGroup(groupId);
5275
5276 UnicodeProperties typeSettingsProperties =
5277 group.getTypeSettingsProperties();
5278
5279 long[] defaultSiteRoleIds = StringUtil.split(
5280 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5281
5282 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5283 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5284 defaultSiteRoleId);
5285
5286 if (defaultSiteRole == null) {
5287 if (_log.isWarnEnabled()) {
5288 _log.warn("Unable to find role " + defaultSiteRoleId);
5289 }
5290
5291 continue;
5292 }
5293
5294 defaultSiteRoles.add(defaultSiteRole);
5295 }
5296
5297 List<Team> defaultTeams = new ArrayList<Team>();
5298
5299 long[] defaultTeamIds = StringUtil.split(
5300 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5301
5302 for (long defaultTeamId : defaultTeamIds) {
5303 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5304
5305 if (defaultTeam == null) {
5306 if (_log.isWarnEnabled()) {
5307 _log.warn("Unable to find team " + defaultTeamId);
5308 }
5309
5310 continue;
5311 }
5312
5313 defaultTeams.add(defaultTeam);
5314 }
5315
5316 for (long userId : userIds) {
5317 Set<Long> userRoleIdsSet = new HashSet<Long>();
5318
5319 for (Role role : defaultSiteRoles) {
5320 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5321 userRoleIdsSet.add(role.getRoleId());
5322 }
5323 }
5324
5325 long[] userRoleIds = ArrayUtil.toArray(
5326 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5327
5328 userGroupRoleLocalService.addUserGroupRoles(
5329 userId, groupId, userRoleIds);
5330
5331 Set<Long> userTeamIdsSet = new HashSet<Long>();
5332
5333 for (Team team : defaultTeams) {
5334 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5335 userTeamIdsSet.add(team.getTeamId());
5336 }
5337 }
5338
5339 long[] userTeamIds = ArrayUtil.toArray(
5340 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5341
5342 userPersistence.addTeams(userId, userTeamIds);
5343 }
5344 }
5345
5346
5392 protected int authenticate(
5393 long companyId, String login, String password, String authType,
5394 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5395 Map<String, Object> resultsMap)
5396 throws PortalException, SystemException {
5397
5398 if (PropsValues.AUTH_LOGIN_DISABLED) {
5399 return Authenticator.FAILURE;
5400 }
5401
5402 login = StringUtil.toLowerCase(login.trim());
5403
5404 long userId = GetterUtil.getLong(login);
5405
5406
5407
5408 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5409 if (Validator.isNull(login)) {
5410 throw new UserEmailAddressException();
5411 }
5412 }
5413 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5414 if (Validator.isNull(login)) {
5415 throw new UserScreenNameException();
5416 }
5417 }
5418 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5419 if (Validator.isNull(login)) {
5420 throw new UserIdException();
5421 }
5422 }
5423
5424 if (Validator.isNull(password)) {
5425 throw new UserPasswordException(
5426 UserPasswordException.PASSWORD_INVALID);
5427 }
5428
5429 int authResult = Authenticator.FAILURE;
5430
5431
5432
5433 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5434 authResult = AuthPipeline.authenticateByEmailAddress(
5435 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5436 headerMap, parameterMap);
5437 }
5438 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5439 authResult = AuthPipeline.authenticateByScreenName(
5440 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5441 headerMap, parameterMap);
5442 }
5443 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5444 authResult = AuthPipeline.authenticateByUserId(
5445 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5446 headerMap, parameterMap);
5447 }
5448
5449
5450
5451 User user = null;
5452
5453 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5454 user = fetchUserByEmailAddress(companyId, login);
5455 }
5456 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5457 user = fetchUserByScreenName(companyId, login);
5458 }
5459 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5460 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5461 }
5462
5463 if (user == null) {
5464 return Authenticator.DNE;
5465 }
5466
5467 if (user.isDefaultUser()) {
5468 if (_log.isInfoEnabled()) {
5469 _log.info("Authentication is disabled for the default user");
5470 }
5471
5472 return Authenticator.DNE;
5473 }
5474 else if (!user.isActive()) {
5475 if (_log.isInfoEnabled()) {
5476 _log.info(
5477 "Authentication is disabled for inactive user " +
5478 user.getUserId());
5479 }
5480
5481 return Authenticator.FAILURE;
5482 }
5483
5484 if (!user.isPasswordEncrypted()) {
5485 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5486 user.setPasswordEncrypted(true);
5487
5488 userPersistence.update(user);
5489 }
5490
5491
5492
5493
5494 checkLockout(user);
5495
5496 checkPasswordExpired(user);
5497
5498
5499
5500 boolean skipLiferayCheck = false;
5501
5502 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5503 authResult = Authenticator.SUCCESS;
5504
5505 skipLiferayCheck = true;
5506 }
5507 else if ((authResult == Authenticator.SUCCESS) &&
5508 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5509
5510 boolean authenticated = PwdAuthenticator.authenticate(
5511 login, password, user.getPassword());
5512
5513 if (authenticated) {
5514 authResult = Authenticator.SUCCESS;
5515 }
5516 else {
5517 authResult = Authenticator.FAILURE;
5518 }
5519 }
5520
5521
5522
5523 if (authResult == Authenticator.SUCCESS) {
5524 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5525 authResult = AuthPipeline.authenticateByEmailAddress(
5526 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5527 headerMap, parameterMap);
5528 }
5529 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5530 authResult = AuthPipeline.authenticateByScreenName(
5531 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5532 headerMap, parameterMap);
5533 }
5534 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5535 authResult = AuthPipeline.authenticateByUserId(
5536 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5537 headerMap, parameterMap);
5538 }
5539 }
5540
5541 if (authResult == Authenticator.SUCCESS) {
5542 if (resultsMap != null) {
5543 resultsMap.put("userId", user.getUserId());
5544 }
5545
5546
5547
5548 if (skipLiferayCheck ||
5549 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5550 Validator.isNull(user.getDigest())) {
5551
5552 String digest = user.getDigest(password);
5553
5554 user.setDigest(digest);
5555
5556 userPersistence.update(user);
5557 }
5558 }
5559
5560
5561
5562 if (authResult == Authenticator.FAILURE) {
5563 try {
5564 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5565 AuthPipeline.onFailureByEmailAddress(
5566 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5567 parameterMap);
5568 }
5569 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5570 AuthPipeline.onFailureByScreenName(
5571 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5572 parameterMap);
5573 }
5574 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5575 AuthPipeline.onFailureByUserId(
5576 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5577 parameterMap);
5578 }
5579
5580 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5581
5582 if (user == null) {
5583 return Authenticator.DNE;
5584 }
5585
5586
5587
5588 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5589 user.getCompanyId())) {
5590
5591 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5592
5593 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5594
5595 int failedLoginAttempts = user.getFailedLoginAttempts();
5596 int maxFailures = passwordPolicy.getMaxFailure();
5597
5598 if ((failedLoginAttempts >= maxFailures) &&
5599 (maxFailures != 0)) {
5600
5601 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5602 AuthPipeline.onMaxFailuresByEmailAddress(
5603 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5604 headerMap, parameterMap);
5605 }
5606 else if (authType.equals(
5607 CompanyConstants.AUTH_TYPE_SN)) {
5608
5609 AuthPipeline.onMaxFailuresByScreenName(
5610 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5611 headerMap, parameterMap);
5612 }
5613 else if (authType.equals(
5614 CompanyConstants.AUTH_TYPE_ID)) {
5615
5616 AuthPipeline.onMaxFailuresByUserId(
5617 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5618 headerMap, parameterMap);
5619 }
5620 }
5621 }
5622 }
5623 catch (Exception e) {
5624 _log.error(e, e);
5625 }
5626 }
5627
5628
5629
5630 return authResult;
5631 }
5632
5633 protected Date getBirthday(
5634 int birthdayMonth, int birthdayDay, int birthdayYear)
5635 throws PortalException {
5636
5637 Date birthday = PortalUtil.getDate(
5638 birthdayMonth, birthdayDay, birthdayYear,
5639 ContactBirthdayException.class);
5640
5641 Date now = new Date();
5642
5643 if (birthday.after(now)) {
5644 throw new ContactBirthdayException();
5645 }
5646
5647 return birthday;
5648 }
5649
5650 protected String getLogin(String login) {
5651 return StringUtil.lowerCase(StringUtil.trim(login));
5652 }
5653
5654 protected long[] getUserIds(List<User> users) {
5655 long[] userIds = new long[users.size()];
5656
5657 for (int i = 0; i < users.size(); i++) {
5658 User user = users.get(i);
5659
5660 userIds[i] = user.getUserId();
5661 }
5662
5663 return userIds;
5664 }
5665
5666 protected void reindex(final User user) {
5667 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5668 User.class);
5669
5670 Callable<Void> callable = new ShardCallable<Void>(
5671 user.getCompanyId()) {
5672
5673 @Override
5674 protected Void doCall() throws Exception {
5675 indexer.reindex(user);
5676
5677 return null;
5678 }
5679
5680 };
5681
5682 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5683 }
5684
5685 protected Hits search(
5686 long companyId, String firstName, String middleName,
5687 String lastName, String fullName, String screenName,
5688 String emailAddress, String street, String city, String zip,
5689 String region, String country, int status,
5690 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5691 int end, Sort sort)
5692 throws SystemException {
5693
5694 try {
5695 SearchContext searchContext = new SearchContext();
5696
5697 searchContext.setAndSearch(andSearch);
5698
5699 Map<String, Serializable> attributes =
5700 new HashMap<String, Serializable>();
5701
5702 attributes.put("city", city);
5703 attributes.put("country", country);
5704 attributes.put("emailAddress", emailAddress);
5705 attributes.put("firstName", firstName);
5706 attributes.put("fullName", fullName);
5707 attributes.put("lastName", lastName);
5708 attributes.put("middleName", middleName);
5709 attributes.put("params", params);
5710 attributes.put("region", region);
5711 attributes.put("screenName", screenName);
5712 attributes.put("street", street);
5713 attributes.put("status", status);
5714 attributes.put("zip", zip);
5715
5716 searchContext.setAttributes(attributes);
5717
5718 searchContext.setCompanyId(companyId);
5719 searchContext.setEnd(end);
5720
5721 if (params != null) {
5722 String keywords = (String)params.remove("keywords");
5723
5724 if (Validator.isNotNull(keywords)) {
5725 searchContext.setKeywords(keywords);
5726 }
5727 }
5728
5729 QueryConfig queryConfig = new QueryConfig();
5730
5731 queryConfig.setHighlightEnabled(false);
5732 queryConfig.setScoreEnabled(false);
5733
5734 searchContext.setQueryConfig(queryConfig);
5735
5736 if (sort != null) {
5737 searchContext.setSorts(sort);
5738 }
5739
5740 searchContext.setStart(start);
5741
5742 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5743 User.class);
5744
5745 return indexer.search(searchContext);
5746 }
5747 catch (Exception e) {
5748 throw new SystemException(e);
5749 }
5750 }
5751
5752 protected void sendEmail(
5753 User user, String password, ServiceContext serviceContext)
5754 throws SystemException {
5755
5756 if (!PrefsPropsUtil.getBoolean(
5757 user.getCompanyId(),
5758 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5759
5760 return;
5761 }
5762
5763 String fromName = PrefsPropsUtil.getString(
5764 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5765 String fromAddress = PrefsPropsUtil.getString(
5766 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5767
5768 String toName = user.getFullName();
5769 String toAddress = user.getEmailAddress();
5770
5771 String subject = PrefsPropsUtil.getContent(
5772 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5773
5774 String body = null;
5775
5776 if (Validator.isNotNull(password)) {
5777 body = PrefsPropsUtil.getContent(
5778 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5779 }
5780 else {
5781 body = PrefsPropsUtil.getContent(
5782 user.getCompanyId(),
5783 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5784 }
5785
5786 SubscriptionSender subscriptionSender = new SubscriptionSender();
5787
5788 subscriptionSender.setBody(body);
5789 subscriptionSender.setCompanyId(user.getCompanyId());
5790 subscriptionSender.setContextAttributes(
5791 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5792 "[$USER_SCREENNAME$]", user.getScreenName());
5793 subscriptionSender.setFrom(fromAddress, fromName);
5794 subscriptionSender.setHtmlFormat(true);
5795 subscriptionSender.setMailId(
5796 "user", user.getUserId(), System.currentTimeMillis(),
5797 PwdGenerator.getPassword());
5798 subscriptionSender.setServiceContext(serviceContext);
5799 subscriptionSender.setSubject(subject);
5800 subscriptionSender.setUserId(user.getUserId());
5801
5802 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5803
5804 subscriptionSender.flushNotificationsAsync();
5805 }
5806
5807 protected void setEmailAddress(
5808 User user, String password, String firstName, String middleName,
5809 String lastName, String emailAddress)
5810 throws PortalException, SystemException {
5811
5812 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
5813 return;
5814 }
5815
5816 long userId = user.getUserId();
5817
5818
5819
5820 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5821 Validator.isNotNull(password)) {
5822
5823 mailService.addUser(
5824 user.getCompanyId(), userId, password, firstName, middleName,
5825 lastName, emailAddress);
5826 }
5827
5828
5829
5830 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5831 mailService.updateEmailAddress(
5832 user.getCompanyId(), userId, emailAddress);
5833 }
5834
5835
5836
5837 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5838 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5839 }
5840
5841 user.setEmailAddress(emailAddress);
5842 user.setDigest(StringPool.BLANK);
5843 }
5844
5845 protected void updateGroups(
5846 long userId, long[] newGroupIds, ServiceContext serviceContext,
5847 boolean indexingEnabled)
5848 throws PortalException, SystemException {
5849
5850 if (newGroupIds == null) {
5851 return;
5852 }
5853
5854 List<Group> oldGroups = userPersistence.getGroups(userId);
5855
5856 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5857
5858 for (Group oldGroup : oldGroups) {
5859 long oldGroupId = oldGroup.getGroupId();
5860
5861 oldGroupIds.add(oldGroupId);
5862
5863 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5864 unsetGroupUsers(
5865 oldGroupId, new long[] {userId}, serviceContext);
5866 }
5867 }
5868
5869 for (long newGroupId : newGroupIds) {
5870 if (!oldGroupIds.contains(newGroupId)) {
5871 addGroupUsers(newGroupId, new long[] {userId});
5872 }
5873 }
5874
5875 if (indexingEnabled) {
5876 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5877 User.class);
5878
5879 indexer.reindex(new long[] {userId});
5880 }
5881
5882 PermissionCacheUtil.clearCache();
5883 }
5884
5885 protected void updateOrganizations(
5886 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5887 throws PortalException, SystemException {
5888
5889 if (newOrganizationIds == null) {
5890 return;
5891 }
5892
5893 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5894 userId);
5895
5896 Set<Long> oldOrganizationIds = new HashSet<Long>(
5897 oldOrganizations.size());
5898
5899 for (Organization oldOrganization : oldOrganizations) {
5900 long oldOrganizationId = oldOrganization.getOrganizationId();
5901
5902 oldOrganizationIds.add(oldOrganizationId);
5903
5904 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5905 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5906 }
5907 }
5908
5909 for (long newOrganizationId : newOrganizationIds) {
5910 if (!oldOrganizationIds.contains(newOrganizationId)) {
5911 addOrganizationUsers(newOrganizationId, new long[] {userId});
5912 }
5913 }
5914
5915 if (indexingEnabled) {
5916 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5917 User.class);
5918
5919 indexer.reindex(new long[] {userId});
5920 }
5921
5922 PermissionCacheUtil.clearCache();
5923 }
5924
5925 protected void updateUserGroupRoles(
5926 User user, long[] groupIds, long[] organizationIds,
5927 List<UserGroupRole> userGroupRoles,
5928 List<UserGroupRole> previousUserGroupRoles)
5929 throws PortalException, SystemException {
5930
5931 if (userGroupRoles == null) {
5932 return;
5933 }
5934
5935 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
5936
5937 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5938 if (userGroupRoles.contains(userGroupRole)) {
5939 userGroupRoles.remove(userGroupRole);
5940 }
5941 else {
5942 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5943 }
5944 }
5945
5946 if (userGroupRoles.isEmpty()) {
5947 return;
5948 }
5949
5950 long[] validGroupIds = null;
5951
5952 if (groupIds != null) {
5953 validGroupIds = ArrayUtil.clone(groupIds);
5954 }
5955 else {
5956 validGroupIds = user.getGroupIds();
5957 }
5958
5959 if (organizationIds == null) {
5960 organizationIds = user.getOrganizationIds();
5961 }
5962
5963 long[] organizationGroupIds = new long[organizationIds.length];
5964
5965 for (int i = 0; i < organizationIds.length; i++) {
5966 long organizationId = organizationIds[i];
5967
5968 Organization organization =
5969 organizationPersistence.findByPrimaryKey(organizationId);
5970
5971 organizationGroupIds[i] = organization.getGroupId();
5972 }
5973
5974 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5975
5976 Arrays.sort(validGroupIds);
5977
5978 for (UserGroupRole userGroupRole : userGroupRoles) {
5979 if (Arrays.binarySearch(
5980 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5981
5982 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5983 }
5984 }
5985 }
5986
5987 protected void validate(
5988 long companyId, long userId, boolean autoPassword, String password1,
5989 String password2, boolean autoScreenName, String screenName,
5990 String emailAddress, String openId, String firstName,
5991 String middleName, String lastName, long[] organizationIds)
5992 throws PortalException, SystemException {
5993
5994 validateCompanyMaxUsers(companyId);
5995
5996 if (!autoScreenName) {
5997 validateScreenName(companyId, userId, screenName);
5998 }
5999
6000 if (!autoPassword) {
6001 PasswordPolicy passwordPolicy =
6002 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6003
6004 PwdToolkitUtil.validate(
6005 companyId, 0, password1, password2, passwordPolicy);
6006 }
6007
6008 validateEmailAddress(companyId, emailAddress);
6009
6010 if (Validator.isNotNull(emailAddress)) {
6011 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6012
6013 if ((user != null) && (user.getUserId() != userId)) {
6014 throw new DuplicateUserEmailAddressException(
6015 "{userId=" + userId + "}");
6016 }
6017 }
6018
6019 validateOpenId(companyId, userId, openId);
6020
6021 validateFullName(companyId, firstName, middleName, lastName);
6022
6023 if (organizationIds != null) {
6024 for (long organizationId : organizationIds) {
6025 Organization organization =
6026 organizationPersistence.fetchByPrimaryKey(organizationId);
6027
6028 if (organization == null) {
6029 throw new NoSuchOrganizationException(
6030 "{organizationId=" + organizationId + "}");
6031 }
6032 }
6033 }
6034 }
6035
6036 protected void validate(
6037 long userId, String screenName, String emailAddress, String openId,
6038 String firstName, String middleName, String lastName, String smsSn)
6039 throws PortalException, SystemException {
6040
6041 User user = userPersistence.findByPrimaryKey(userId);
6042
6043 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6044 validateScreenName(user.getCompanyId(), userId, screenName);
6045 }
6046
6047 validateEmailAddress(user.getCompanyId(), emailAddress);
6048
6049 validateOpenId(user.getCompanyId(), userId, openId);
6050
6051 if (!user.isDefaultUser()) {
6052 if (Validator.isNotNull(emailAddress) &&
6053 !StringUtil.equalsIgnoreCase(
6054 user.getEmailAddress(), emailAddress)) {
6055
6056 if (userPersistence.fetchByC_EA(
6057 user.getCompanyId(), emailAddress) != null) {
6058
6059 throw new DuplicateUserEmailAddressException(
6060 "{userId=" + userId + "}");
6061 }
6062 }
6063
6064 validateFullName(
6065 user.getCompanyId(), firstName, middleName, lastName);
6066 }
6067
6068 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6069 throw new UserSmsException();
6070 }
6071 }
6072
6073 protected void validateCompanyMaxUsers(long companyId)
6074 throws PortalException, SystemException {
6075
6076 Company company = companyPersistence.findByPrimaryKey(companyId);
6077
6078 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6079 return;
6080 }
6081
6082 int userCount = searchCount(
6083 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6084
6085 if (userCount >= company.getMaxUsers()) {
6086 throw new CompanyMaxUsersException();
6087 }
6088 }
6089
6090 protected void validateEmailAddress(long companyId, String emailAddress)
6091 throws PortalException, SystemException {
6092
6093 if (Validator.isNull(emailAddress) &&
6094 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6095
6096 return;
6097 }
6098
6099 EmailAddressValidator emailAddressValidator =
6100 EmailAddressValidatorFactory.getInstance();
6101
6102 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6103 throw new UserEmailAddressException();
6104 }
6105
6106 String pop3User = PrefsPropsUtil.getString(
6107 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6108 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6109
6110 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6111 throw new ReservedUserEmailAddressException();
6112 }
6113
6114 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6115 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6116 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6117
6118 for (String reservedEmailAddress : reservedEmailAddresses) {
6119 if (StringUtil.equalsIgnoreCase(
6120 emailAddress, reservedEmailAddress)) {
6121
6122 throw new ReservedUserEmailAddressException();
6123 }
6124 }
6125 }
6126
6127 protected void validateEmailAddress(
6128 User user, String emailAddress1, String emailAddress2)
6129 throws PortalException, SystemException {
6130
6131 if (!emailAddress1.equals(emailAddress2)) {
6132 throw new UserEmailAddressException();
6133 }
6134
6135 validateEmailAddress(user.getCompanyId(), emailAddress1);
6136 validateEmailAddress(user.getCompanyId(), emailAddress2);
6137
6138 if (!StringUtil.equalsIgnoreCase(
6139 emailAddress1, user.getEmailAddress())) {
6140
6141 if (userPersistence.fetchByC_EA(
6142 user.getCompanyId(), emailAddress1) != null) {
6143
6144 throw new DuplicateUserEmailAddressException(
6145 "{userId=" + user.getUserId() + "}");
6146 }
6147 }
6148 }
6149
6150 protected void validateFullName(
6151 long companyId, String firstName, String middleName,
6152 String lastName)
6153 throws PortalException, SystemException {
6154
6155 if (Validator.isNull(firstName)) {
6156 throw new ContactFirstNameException();
6157 }
6158 else if (Validator.isNull(lastName) &&
6159 PrefsPropsUtil.getBoolean(
6160 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6161 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6162
6163 throw new ContactLastNameException();
6164 }
6165
6166 FullNameValidator fullNameValidator =
6167 FullNameValidatorFactory.getInstance();
6168
6169 if (!fullNameValidator.validate(
6170 companyId, firstName, middleName, lastName)) {
6171
6172 throw new ContactFullNameException();
6173 }
6174 }
6175
6176 protected void validateOpenId(long companyId, long userId, String openId)
6177 throws PortalException, SystemException {
6178
6179 if (Validator.isNull(openId)) {
6180 return;
6181 }
6182
6183 User user = userPersistence.fetchByC_O(companyId, openId);
6184
6185 if ((user != null) && (user.getUserId() != userId)) {
6186 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6187 }
6188 }
6189
6190 protected void validatePassword(
6191 long companyId, long userId, String password1, String password2)
6192 throws PortalException, SystemException {
6193
6194 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6195 throw new UserPasswordException(
6196 UserPasswordException.PASSWORD_INVALID);
6197 }
6198
6199 if (!password1.equals(password2)) {
6200 throw new UserPasswordException(
6201 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6202 }
6203
6204 PasswordPolicy passwordPolicy =
6205 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6206
6207 PwdToolkitUtil.validate(
6208 companyId, userId, password1, password2, passwordPolicy);
6209 }
6210
6211 protected void validateReminderQuery(String question, String answer)
6212 throws PortalException {
6213
6214 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6215 return;
6216 }
6217
6218 if (Validator.isNull(question)) {
6219 throw new UserReminderQueryException("Question is null");
6220 }
6221
6222 if (Validator.isNull(answer)) {
6223 throw new UserReminderQueryException("Answer is null");
6224 }
6225 }
6226
6227 protected void validateScreenName(
6228 long companyId, long userId, String screenName)
6229 throws PortalException, SystemException {
6230
6231 if (Validator.isNull(screenName)) {
6232 throw new UserScreenNameException();
6233 }
6234
6235 ScreenNameValidator screenNameValidator =
6236 ScreenNameValidatorFactory.getInstance();
6237
6238 if (!screenNameValidator.validate(companyId, screenName)) {
6239 throw new UserScreenNameException();
6240 }
6241
6242 if (Validator.isNumber(screenName)) {
6243 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6244 throw new UserScreenNameException();
6245 }
6246
6247 if (!screenName.equals(String.valueOf(userId))) {
6248 Group group = groupPersistence.fetchByPrimaryKey(
6249 GetterUtil.getLong(screenName));
6250
6251 if (group != null) {
6252 throw new UserScreenNameException();
6253 }
6254 }
6255 }
6256
6257 for (char c : screenName.toCharArray()) {
6258 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6259 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6260 (c != CharPool.UNDERLINE)) {
6261
6262 throw new UserScreenNameException();
6263 }
6264 }
6265
6266 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6267
6268 for (String anonymousName : anonymousNames) {
6269 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6270 throw new UserScreenNameException();
6271 }
6272 }
6273
6274 User user = userPersistence.fetchByC_SN(companyId, screenName);
6275
6276 if ((user != null) && (user.getUserId() != userId)) {
6277 throw new DuplicateUserScreenNameException(
6278 "{userId=" + userId + "}");
6279 }
6280
6281 String friendlyURL = StringPool.SLASH + screenName;
6282
6283 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6284
6285 if ((group != null) && (group.getClassPK() != userId)) {
6286 throw new GroupFriendlyURLException(
6287 GroupFriendlyURLException.DUPLICATE);
6288 }
6289
6290 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6291
6292 if (exceptionType != -1) {
6293 throw new UserScreenNameException(
6294 new GroupFriendlyURLException(exceptionType));
6295 }
6296
6297 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6298 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6299 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6300
6301 for (String reservedScreenName : reservedScreenNames) {
6302 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6303 throw new ReservedUserScreenNameException();
6304 }
6305 }
6306 }
6307
6308 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6309
6310 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6311
6312 }