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.dao.shard.ShardCallable;
047 import com.liferay.portal.kernel.exception.PortalException;
048 import com.liferay.portal.kernel.exception.SystemException;
049 import com.liferay.portal.kernel.image.ImageBag;
050 import com.liferay.portal.kernel.image.ImageToolUtil;
051 import com.liferay.portal.kernel.language.LanguageUtil;
052 import com.liferay.portal.kernel.log.Log;
053 import com.liferay.portal.kernel.log.LogFactoryUtil;
054 import com.liferay.portal.kernel.messaging.DestinationNames;
055 import com.liferay.portal.kernel.messaging.Message;
056 import com.liferay.portal.kernel.messaging.MessageBusUtil;
057 import com.liferay.portal.kernel.search.Hits;
058 import com.liferay.portal.kernel.search.Indexer;
059 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
060 import com.liferay.portal.kernel.search.QueryConfig;
061 import com.liferay.portal.kernel.search.SearchContext;
062 import com.liferay.portal.kernel.search.Sort;
063 import com.liferay.portal.kernel.spring.aop.Skip;
064 import com.liferay.portal.kernel.transaction.Propagation;
065 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
066 import com.liferay.portal.kernel.transaction.Transactional;
067 import com.liferay.portal.kernel.util.ArrayUtil;
068 import com.liferay.portal.kernel.util.CharPool;
069 import com.liferay.portal.kernel.util.Digester;
070 import com.liferay.portal.kernel.util.DigesterUtil;
071 import com.liferay.portal.kernel.util.GetterUtil;
072 import com.liferay.portal.kernel.util.KeyValuePair;
073 import com.liferay.portal.kernel.util.LocaleUtil;
074 import com.liferay.portal.kernel.util.OrderByComparator;
075 import com.liferay.portal.kernel.util.ParamUtil;
076 import com.liferay.portal.kernel.util.PropsKeys;
077 import com.liferay.portal.kernel.util.StringBundler;
078 import com.liferay.portal.kernel.util.StringPool;
079 import com.liferay.portal.kernel.util.StringUtil;
080 import com.liferay.portal.kernel.util.UnicodeProperties;
081 import com.liferay.portal.kernel.util.Validator;
082 import com.liferay.portal.kernel.workflow.WorkflowConstants;
083 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
084 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
085 import com.liferay.portal.model.Account;
086 import com.liferay.portal.model.Company;
087 import com.liferay.portal.model.CompanyConstants;
088 import com.liferay.portal.model.Contact;
089 import com.liferay.portal.model.ContactConstants;
090 import com.liferay.portal.model.Group;
091 import com.liferay.portal.model.GroupConstants;
092 import com.liferay.portal.model.Layout;
093 import com.liferay.portal.model.Organization;
094 import com.liferay.portal.model.PasswordPolicy;
095 import com.liferay.portal.model.ResourceConstants;
096 import com.liferay.portal.model.Role;
097 import com.liferay.portal.model.RoleConstants;
098 import com.liferay.portal.model.Team;
099 import com.liferay.portal.model.Ticket;
100 import com.liferay.portal.model.TicketConstants;
101 import com.liferay.portal.model.User;
102 import com.liferay.portal.model.UserGroup;
103 import com.liferay.portal.model.UserGroupRole;
104 import com.liferay.portal.model.impl.LayoutImpl;
105 import com.liferay.portal.security.auth.AuthPipeline;
106 import com.liferay.portal.security.auth.Authenticator;
107 import com.liferay.portal.security.auth.EmailAddressGenerator;
108 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
109 import com.liferay.portal.security.auth.EmailAddressValidator;
110 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
111 import com.liferay.portal.security.auth.FullNameGenerator;
112 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
113 import com.liferay.portal.security.auth.FullNameValidator;
114 import com.liferay.portal.security.auth.FullNameValidatorFactory;
115 import com.liferay.portal.security.auth.PrincipalException;
116 import com.liferay.portal.security.auth.ScreenNameGenerator;
117 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
118 import com.liferay.portal.security.auth.ScreenNameValidator;
119 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
120 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
121 import com.liferay.portal.security.permission.PermissionCacheUtil;
122 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
123 import com.liferay.portal.security.pwd.PwdAuthenticator;
124 import com.liferay.portal.security.pwd.PwdToolkitUtil;
125 import com.liferay.portal.security.pwd.RegExpToolkit;
126 import com.liferay.portal.service.BaseServiceImpl;
127 import com.liferay.portal.service.ServiceContext;
128 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
129 import com.liferay.portal.util.PortalUtil;
130 import com.liferay.portal.util.PrefsPropsUtil;
131 import com.liferay.portal.util.PropsValues;
132 import com.liferay.portal.util.SubscriptionSender;
133 import com.liferay.portlet.documentlibrary.ImageSizeException;
134 import com.liferay.portlet.messageboards.model.MBMessage;
135 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
136 import com.liferay.util.Encryptor;
137 import com.liferay.util.EncryptorException;
138 import com.liferay.util.PwdGenerator;
139
140 import java.awt.image.RenderedImage;
141
142 import java.io.IOException;
143 import java.io.Serializable;
144
145 import java.util.ArrayList;
146 import java.util.Arrays;
147 import java.util.Calendar;
148 import java.util.Date;
149 import java.util.HashMap;
150 import java.util.HashSet;
151 import java.util.LinkedHashMap;
152 import java.util.List;
153 import java.util.Locale;
154 import java.util.Map;
155 import java.util.Set;
156 import java.util.concurrent.Callable;
157 import java.util.concurrent.ConcurrentHashMap;
158
159
171 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
172
173
187 @Override
188 public User addDefaultAdminUser(
189 long companyId, String screenName, String emailAddress,
190 Locale locale, String firstName, String middleName, String lastName)
191 throws PortalException, SystemException {
192
193 long creatorUserId = 0;
194 boolean autoPassword = false;
195 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
196 String password2 = password1;
197 boolean autoScreenName = false;
198
199 screenName = getLogin(screenName);
200
201 for (int i = 1;; i++) {
202 User screenNameUser = userPersistence.fetchByC_SN(
203 companyId, screenName);
204
205 if (screenNameUser == null) {
206 break;
207 }
208
209 screenName = screenName + i;
210 }
211
212 long facebookId = 0;
213 String openId = StringPool.BLANK;
214 int prefixId = 0;
215 int suffixId = 0;
216 boolean male = true;
217 int birthdayMonth = Calendar.JANUARY;
218 int birthdayDay = 1;
219 int birthdayYear = 1970;
220 String jobTitle = StringPool.BLANK;
221
222 Group guestGroup = groupLocalService.getGroup(
223 companyId, GroupConstants.GUEST);
224
225 long[] groupIds = {guestGroup.getGroupId()};
226
227 long[] organizationIds = null;
228
229 Role adminRole = roleLocalService.getRole(
230 companyId, RoleConstants.ADMINISTRATOR);
231
232 Role powerUserRole = roleLocalService.getRole(
233 companyId, RoleConstants.POWER_USER);
234
235 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
236
237 long[] userGroupIds = null;
238 boolean sendEmail = false;
239 ServiceContext serviceContext = new ServiceContext();
240
241 User defaultAdminUser = addUser(
242 creatorUserId, companyId, autoPassword, password1, password2,
243 autoScreenName, screenName, emailAddress, facebookId, openId,
244 locale, firstName, middleName, lastName, prefixId, suffixId, male,
245 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
246 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
247
248 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
249
250 updateLastLogin(
251 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
252
253 updatePasswordReset(defaultAdminUser.getUserId(), false);
254
255 return defaultAdminUser;
256 }
257
258
268 @Override
269 public void addDefaultGroups(long userId)
270 throws PortalException, SystemException {
271
272 User user = userPersistence.findByPrimaryKey(userId);
273
274 Set<Long> groupIdsSet = new HashSet<Long>();
275
276 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
277 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
278 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
279
280 for (String defaultGroupName : defaultGroupNames) {
281 Company company = companyPersistence.findByPrimaryKey(
282 user.getCompanyId());
283
284 Account account = company.getAccount();
285
286 if (StringUtil.equalsIgnoreCase(
287 defaultGroupName, account.getName())) {
288
289 defaultGroupName = GroupConstants.GUEST;
290 }
291
292 Group group = groupPersistence.fetchByC_N(
293 user.getCompanyId(), defaultGroupName);
294
295 if ((group != null) &&
296 !userPersistence.containsGroup(
297 userId, group.getGroupId())) {
298
299 groupIdsSet.add(group.getGroupId());
300 }
301 }
302
303 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
304 user.getCompanyId(),
305 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
306 StringPool.NEW_LINE,
307 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
308
309 for (String defaultOrganizationGroupName :
310 defaultOrganizationGroupNames) {
311
312 defaultOrganizationGroupName +=
313 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
314
315 Group group = groupPersistence.fetchByC_N(
316 user.getCompanyId(), defaultOrganizationGroupName);
317
318 if ((group != null) &&
319 !userPersistence.containsGroup(
320 userId, group.getGroupId())) {
321
322 groupIdsSet.add(group.getGroupId());
323 }
324 }
325
326 long[] groupIds = ArrayUtil.toArray(
327 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
328
329 groupLocalService.addUserGroups(userId, groupIds);
330 }
331
332
342 @Override
343 public void addDefaultRoles(long userId)
344 throws PortalException, SystemException {
345
346 User user = userPersistence.findByPrimaryKey(userId);
347
348 Set<Long> roleIdSet = new HashSet<Long>();
349
350 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
351 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
352 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
353
354 for (String defaultRoleName : defaultRoleNames) {
355 try {
356 Role role = rolePersistence.findByC_N(
357 user.getCompanyId(), defaultRoleName);
358
359 if (!userPersistence.containsRole(userId, role.getRoleId())) {
360 roleIdSet.add(role.getRoleId());
361 }
362 }
363 catch (NoSuchRoleException nsre) {
364 }
365 }
366
367 long[] roleIds = ArrayUtil.toArray(
368 roleIdSet.toArray(new Long[roleIdSet.size()]));
369
370 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
371
372 userPersistence.addRoles(userId, roleIds);
373 }
374
375
385 @Override
386 @SuppressWarnings("deprecation")
387 public void addDefaultUserGroups(long userId)
388 throws PortalException, SystemException {
389
390 User user = userPersistence.findByPrimaryKey(userId);
391
392 Set<Long> userGroupIdSet = new HashSet<Long>();
393
394 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
395 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
396 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
397
398 for (String defaultUserGroupName : defaultUserGroupNames) {
399 try {
400 UserGroup userGroup = userGroupPersistence.findByC_N(
401 user.getCompanyId(), defaultUserGroupName);
402
403 if (!userPersistence.containsUserGroup(
404 userId, userGroup.getUserGroupId())) {
405
406 userGroupIdSet.add(userGroup.getUserGroupId());
407 }
408 }
409 catch (NoSuchUserGroupException nsuge) {
410 }
411 }
412
413 long[] userGroupIds = ArrayUtil.toArray(
414 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
415
416 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
417 for (long userGroupId : userGroupIds) {
418 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
419 }
420 }
421
422 userPersistence.addUserGroups(userId, userGroupIds);
423 }
424
425
434 @Override
435 public void addGroupUsers(long groupId, long[] userIds)
436 throws PortalException, SystemException {
437
438 groupPersistence.addUsers(groupId, userIds);
439
440 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
441
442 indexer.reindex(userIds);
443
444 PermissionCacheUtil.clearCache();
445
446 addDefaultRolesAndTeams(groupId, userIds);
447 }
448
449
458 @Override
459 public void addOrganizationUsers(long organizationId, long[] userIds)
460 throws PortalException, SystemException {
461
462 organizationPersistence.addUsers(organizationId, userIds);
463
464 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
465
466 indexer.reindex(userIds);
467
468 PermissionCacheUtil.clearCache();
469 }
470
471
479 @Override
480 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
481 throws SystemException {
482
483 passwordPolicyRelLocalService.addPasswordPolicyRels(
484 passwordPolicyId, User.class.getName(), userIds);
485 }
486
487
496 @Override
497 public void addRoleUsers(long roleId, long[] userIds)
498 throws PortalException, SystemException {
499
500 rolePersistence.addUsers(roleId, userIds);
501
502 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
503
504 indexer.reindex(userIds);
505
506 PermissionCacheUtil.clearCache();
507 }
508
509
518 @Override
519 public void addTeamUsers(long teamId, long[] userIds)
520 throws PortalException, SystemException {
521
522 teamPersistence.addUsers(teamId, userIds);
523
524 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
525
526 indexer.reindex(userIds);
527
528 PermissionCacheUtil.clearCache();
529 }
530
531
579 @Override
580 public User addUser(
581 long creatorUserId, long companyId, boolean autoPassword,
582 String password1, String password2, boolean autoScreenName,
583 String screenName, String emailAddress, long facebookId,
584 String openId, Locale locale, String firstName, String middleName,
585 String lastName, int prefixId, int suffixId, boolean male,
586 int birthdayMonth, int birthdayDay, int birthdayYear,
587 String jobTitle, long[] groupIds, long[] organizationIds,
588 long[] roleIds, long[] userGroupIds, boolean sendEmail,
589 ServiceContext serviceContext)
590 throws PortalException, SystemException {
591
592 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
593
594 try {
595 WorkflowThreadLocal.setEnabled(false);
596
597 if (serviceContext == null) {
598 serviceContext = new ServiceContext();
599 }
600
601 if (serviceContext.getWorkflowAction() !=
602 WorkflowConstants.ACTION_PUBLISH) {
603
604 serviceContext.setWorkflowAction(
605 WorkflowConstants.ACTION_PUBLISH);
606 }
607
608 return addUserWithWorkflow(
609 creatorUserId, companyId, autoPassword, password1, password2,
610 autoScreenName, screenName, emailAddress, facebookId, openId,
611 locale, firstName, middleName, lastName, prefixId, suffixId,
612 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
613 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
614 serviceContext);
615 }
616 finally {
617 WorkflowThreadLocal.setEnabled(workflowEnabled);
618 }
619 }
620
621
630 @Override
631 @SuppressWarnings("deprecation")
632 public void addUserGroupUsers(long userGroupId, long[] userIds)
633 throws PortalException, SystemException {
634
635 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
636 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
637 }
638
639 userGroupPersistence.addUsers(userGroupId, userIds);
640
641 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
642
643 indexer.reindex(userIds);
644
645 PermissionCacheUtil.clearCache();
646 }
647
648
696 @Override
697 @SuppressWarnings("deprecation")
698 public User addUserWithWorkflow(
699 long creatorUserId, long companyId, boolean autoPassword,
700 String password1, String password2, boolean autoScreenName,
701 String screenName, String emailAddress, long facebookId,
702 String openId, Locale locale, String firstName, String middleName,
703 String lastName, int prefixId, int suffixId, boolean male,
704 int birthdayMonth, int birthdayDay, int birthdayYear,
705 String jobTitle, long[] groupIds, long[] organizationIds,
706 long[] roleIds, long[] userGroupIds, boolean sendEmail,
707 ServiceContext serviceContext)
708 throws PortalException, SystemException {
709
710
711
712 Company company = companyPersistence.findByPrimaryKey(companyId);
713 screenName = getLogin(screenName);
714 openId = StringUtil.trim(openId);
715 Date now = new Date();
716
717 if (PrefsPropsUtil.getBoolean(
718 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
719
720 autoScreenName = true;
721 }
722
723
724
725 long userId = counterLocalService.increment();
726
727 EmailAddressGenerator emailAddressGenerator =
728 EmailAddressGeneratorFactory.getInstance();
729
730 if ((emailAddress == null) ||
731 emailAddressGenerator.isGenerated(emailAddress)) {
732
733 emailAddress = StringPool.BLANK;
734 }
735 else {
736 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
737 }
738
739 if (!PrefsPropsUtil.getBoolean(
740 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
741 Validator.isNull(emailAddress)) {
742
743 emailAddress = emailAddressGenerator.generate(companyId, userId);
744 }
745
746 validate(
747 companyId, userId, autoPassword, password1, password2,
748 autoScreenName, screenName, emailAddress, openId, firstName,
749 middleName, lastName, organizationIds);
750
751 if (!autoPassword) {
752 if (Validator.isNull(password1) || Validator.isNull(password2)) {
753 throw new UserPasswordException(
754 UserPasswordException.PASSWORD_INVALID);
755 }
756 }
757
758 if (autoScreenName) {
759 ScreenNameGenerator screenNameGenerator =
760 ScreenNameGeneratorFactory.getInstance();
761
762 try {
763 screenName = screenNameGenerator.generate(
764 companyId, userId, emailAddress);
765 }
766 catch (Exception e) {
767 throw new SystemException(e);
768 }
769 }
770
771 User defaultUser = getDefaultUser(companyId);
772
773 FullNameGenerator fullNameGenerator =
774 FullNameGeneratorFactory.getInstance();
775
776 String fullName = fullNameGenerator.getFullName(
777 firstName, middleName, lastName);
778
779 String greeting = LanguageUtil.format(
780 locale, "welcome-x", " " + fullName, false);
781
782 User user = userPersistence.create(userId);
783
784 if (serviceContext != null) {
785 String uuid = serviceContext.getUuid();
786
787 if (Validator.isNotNull(uuid)) {
788 user.setUuid(uuid);
789 }
790 }
791
792 user.setCompanyId(companyId);
793 user.setCreateDate(now);
794 user.setModifiedDate(now);
795 user.setDefaultUser(false);
796 user.setContactId(counterLocalService.increment());
797
798 if (Validator.isNotNull(password1)) {
799 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
800 user.setPasswordUnencrypted(password1);
801 }
802
803 user.setPasswordEncrypted(true);
804
805 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
806
807 boolean passwordReset = false;
808
809 if (passwordPolicy != null) {
810 if (passwordPolicy.isChangeable() &&
811 passwordPolicy.isChangeRequired()) {
812
813 passwordReset = true;
814 }
815
816 addPasswordPolicyUsers(
817 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
818 }
819
820 user.setPasswordReset(passwordReset);
821
822 user.setDigest(StringPool.BLANK);
823 user.setScreenName(screenName);
824 user.setEmailAddress(emailAddress);
825 user.setFacebookId(facebookId);
826
827 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
828
829 if (ldapServerId != null) {
830 user.setLdapServerId(ldapServerId);
831 }
832 else {
833 user.setLdapServerId(-1);
834 }
835
836 user.setOpenId(openId);
837 user.setLanguageId(LocaleUtil.toLanguageId(locale));
838 user.setTimeZoneId(defaultUser.getTimeZoneId());
839 user.setGreeting(greeting);
840 user.setFirstName(firstName);
841 user.setMiddleName(middleName);
842 user.setLastName(lastName);
843 user.setJobTitle(jobTitle);
844 user.setStatus(WorkflowConstants.STATUS_DRAFT);
845 user.setExpandoBridgeAttributes(serviceContext);
846
847 userPersistence.update(user, serviceContext);
848
849
850
851 String creatorUserName = StringPool.BLANK;
852
853 if (creatorUserId <= 0) {
854 creatorUserId = user.getUserId();
855
856
857
858
859
860 }
861 else {
862 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
863
864 creatorUserName = creatorUser.getFullName();
865 }
866
867 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
868
869 Contact contact = contactPersistence.create(user.getContactId());
870
871 contact.setCompanyId(user.getCompanyId());
872 contact.setUserId(creatorUserId);
873 contact.setUserName(creatorUserName);
874 contact.setCreateDate(now);
875 contact.setModifiedDate(now);
876 contact.setClassName(User.class.getName());
877 contact.setClassPK(user.getUserId());
878 contact.setAccountId(company.getAccountId());
879 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
880 contact.setEmailAddress(user.getEmailAddress());
881 contact.setFirstName(firstName);
882 contact.setMiddleName(middleName);
883 contact.setLastName(lastName);
884 contact.setPrefixId(prefixId);
885 contact.setSuffixId(suffixId);
886 contact.setMale(male);
887 contact.setBirthday(birthday);
888 contact.setJobTitle(jobTitle);
889
890 contactPersistence.update(contact, serviceContext);
891
892
893
894 groupLocalService.addGroup(
895 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
896 User.class.getName(), user.getUserId(), null, null, 0,
897 StringPool.SLASH + screenName, false, true, null);
898
899
900
901 if (groupIds != null) {
902 List<Group> groups = new ArrayList<Group>();
903
904 for (long groupId : groupIds) {
905 Group group = groupLocalService.fetchGroup(groupId);
906
907 if (group != null) {
908 groups.add(group);
909 }
910 else {
911 if (_log.isWarnEnabled()) {
912 _log.warn("Group " + groupId + " does not exist");
913 }
914 }
915 }
916
917 groupLocalService.addUserGroups(userId, groups);
918 }
919
920 addDefaultGroups(userId);
921
922
923
924 updateOrganizations(userId, organizationIds, false);
925
926
927
928 if (roleIds != null) {
929 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
930
931 userPersistence.setRoles(userId, roleIds);
932 }
933
934 addDefaultRoles(userId);
935
936
937
938 if (userGroupIds != null) {
939 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
940 for (long userGroupId : userGroupIds) {
941 userGroupLocalService.copyUserGroupLayouts(
942 userGroupId, new long[] {userId});
943 }
944 }
945
946 userPersistence.setUserGroups(userId, userGroupIds);
947 }
948
949 addDefaultUserGroups(userId);
950
951
952
953 resourceLocalService.addResources(
954 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
955 false, false, false);
956
957
958
959 if (serviceContext != null) {
960 updateAsset(
961 creatorUserId, user, serviceContext.getAssetCategoryIds(),
962 serviceContext.getAssetTagNames());
963 }
964
965
966
967 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
968 reindex(user);
969 }
970
971
972
973 long workflowUserId = creatorUserId;
974
975 if (workflowUserId == userId) {
976 workflowUserId = defaultUser.getUserId();
977 }
978
979 ServiceContext workflowServiceContext = serviceContext;
980
981 if (workflowServiceContext == null) {
982 workflowServiceContext = new ServiceContext();
983 }
984
985 workflowServiceContext.setAttribute("autoPassword", autoPassword);
986 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
987 workflowServiceContext.setAttribute("sendEmail", sendEmail);
988
989 WorkflowHandlerRegistryUtil.startWorkflowInstance(
990 companyId, workflowUserId, User.class.getName(), userId, user,
991 workflowServiceContext);
992
993 if (serviceContext != null) {
994 String passwordUnencrypted = (String)serviceContext.getAttribute(
995 "passwordUnencrypted");
996
997 if (Validator.isNotNull(passwordUnencrypted)) {
998 user.setPasswordUnencrypted(passwordUnencrypted);
999 }
1000 }
1001
1002 return user;
1003 }
1004
1005
1029 @Override
1030 public int authenticateByEmailAddress(
1031 long companyId, String emailAddress, String password,
1032 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1033 Map<String, Object> resultsMap)
1034 throws PortalException, SystemException {
1035
1036 return authenticate(
1037 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1038 headerMap, parameterMap, resultsMap);
1039 }
1040
1041
1065 @Override
1066 public int authenticateByScreenName(
1067 long companyId, String screenName, String password,
1068 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1069 Map<String, Object> resultsMap)
1070 throws PortalException, SystemException {
1071
1072 return authenticate(
1073 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1074 headerMap, parameterMap, resultsMap);
1075 }
1076
1077
1101 @Override
1102 public int authenticateByUserId(
1103 long companyId, long userId, String password,
1104 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1105 Map<String, Object> resultsMap)
1106 throws PortalException, SystemException {
1107
1108 return authenticate(
1109 companyId, String.valueOf(userId), password,
1110 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1111 }
1112
1113
1153 @Override
1154 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1155 public long authenticateForBasic(
1156 long companyId, String authType, String login, String password)
1157 throws PortalException, SystemException {
1158
1159 if (PropsValues.AUTH_LOGIN_DISABLED) {
1160 return 0;
1161 }
1162
1163 User user = null;
1164
1165 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1166 user = fetchUserByEmailAddress(companyId, login);
1167 }
1168 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1169 user = fetchUserByScreenName(companyId, login);
1170 }
1171 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1172 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1173 }
1174
1175 if (user == null) {
1176 return 0;
1177 }
1178
1179 if (user.isDefaultUser()) {
1180 if (_log.isInfoEnabled()) {
1181 _log.info(
1182 "Basic authentication is disabled for the default " +
1183 "user");
1184 }
1185
1186 return 0;
1187 }
1188 else if (!user.isActive()) {
1189 if (_log.isInfoEnabled()) {
1190 _log.info(
1191 "Basic authentication is disabled for inactive user " +
1192 user.getUserId());
1193 }
1194
1195 return 0;
1196 }
1197
1198 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1199 return user.getUserId();
1200 }
1201
1202 String userPassword = user.getPassword();
1203
1204 if (!user.isPasswordEncrypted()) {
1205 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1206 }
1207
1208 String encPassword = PasswordEncryptorUtil.encrypt(
1209 password, userPassword);
1210
1211 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1212 return user.getUserId();
1213 }
1214
1215 return 0;
1216 }
1217
1218
1236 @Override
1237 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1238 public long authenticateForDigest(
1239 long companyId, String username, String realm, String nonce,
1240 String method, String uri, String response)
1241 throws PortalException, SystemException {
1242
1243 if (PropsValues.AUTH_LOGIN_DISABLED) {
1244 return 0;
1245 }
1246
1247
1248
1249 User user = fetchUserByEmailAddress(companyId, username);
1250
1251 if (user == null) {
1252 user = fetchUserByScreenName(companyId, username);
1253 }
1254
1255 if (user == null) {
1256 user = userPersistence.fetchByPrimaryKey(
1257 GetterUtil.getLong(username));
1258 }
1259
1260 if (user == null) {
1261 return 0;
1262 }
1263
1264 if (user.isDefaultUser()) {
1265 if (_log.isInfoEnabled()) {
1266 _log.info(
1267 "Digest authentication is disabled for the default user");
1268 }
1269
1270 return 0;
1271 }
1272 else if (!user.isActive()) {
1273 if (_log.isInfoEnabled()) {
1274 _log.info(
1275 "Digest authentication is disabled for inactive user " +
1276 user.getUserId());
1277 }
1278
1279 return 0;
1280 }
1281
1282
1283
1284 String digest = user.getDigest();
1285
1286 if (Validator.isNull(digest)) {
1287 _log.error(
1288 "User must first login through the portal " + user.getUserId());
1289
1290 return 0;
1291 }
1292
1293 String[] digestArray = StringUtil.split(user.getDigest());
1294
1295 for (String ha1 : digestArray) {
1296 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1297
1298 String curResponse = DigesterUtil.digestHex(
1299 Digester.MD5, ha1, nonce, ha2);
1300
1301 if (response.equals(curResponse)) {
1302 return user.getUserId();
1303 }
1304 }
1305
1306 return 0;
1307 }
1308
1309
1318 @Override
1319 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1320 public boolean authenticateForJAAS(long userId, String encPassword) {
1321 if (PropsValues.AUTH_LOGIN_DISABLED) {
1322 return false;
1323 }
1324
1325 try {
1326 User user = userPersistence.findByPrimaryKey(userId);
1327
1328 if (user.isDefaultUser()) {
1329 if (_log.isInfoEnabled()) {
1330 _log.info(
1331 "JAAS authentication is disabled for the default user");
1332 }
1333
1334 return false;
1335 }
1336 else if (!user.isActive()) {
1337 if (_log.isInfoEnabled()) {
1338 _log.info(
1339 "JAAS authentication is disabled for inactive user " +
1340 userId);
1341 }
1342
1343 return false;
1344 }
1345
1346 String userPassword = user.getPassword();
1347
1348 if (user.isPasswordEncrypted()) {
1349 if (userPassword.equals(encPassword)) {
1350 return true;
1351 }
1352
1353 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1354 encPassword = PasswordEncryptorUtil.encrypt(
1355 encPassword, userPassword);
1356
1357 if (userPassword.equals(encPassword)) {
1358 return true;
1359 }
1360 }
1361 }
1362 else {
1363 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1364 if (userPassword.equals(encPassword)) {
1365 return true;
1366 }
1367 }
1368
1369 userPassword = PasswordEncryptorUtil.encrypt(
1370 userPassword, encPassword);
1371
1372 if (userPassword.equals(encPassword)) {
1373 return true;
1374 }
1375 }
1376 }
1377 catch (Exception e) {
1378 _log.error(e);
1379 }
1380
1381 return false;
1382 }
1383
1384
1392 @Override
1393 public void checkLockout(User user)
1394 throws PortalException, SystemException {
1395
1396 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1397 return;
1398 }
1399
1400 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1401
1402 if (!passwordPolicy.isLockout()) {
1403 return;
1404 }
1405
1406
1407
1408 Date now = new Date();
1409 int failedLoginAttempts = user.getFailedLoginAttempts();
1410
1411 if (failedLoginAttempts > 0) {
1412 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1413 long elapsedTime = now.getTime() - failedLoginTime;
1414 long requiredElapsedTime =
1415 passwordPolicy.getResetFailureCount() * 1000;
1416
1417 if ((requiredElapsedTime != 0) &&
1418 (elapsedTime > requiredElapsedTime)) {
1419
1420 user.setFailedLoginAttempts(0);
1421
1422 userPersistence.update(user);
1423 }
1424 }
1425
1426
1427
1428 if (user.isLockout()) {
1429 long lockoutTime = user.getLockoutDate().getTime();
1430 long elapsedTime = now.getTime() - lockoutTime;
1431 long requiredElapsedTime =
1432 passwordPolicy.getLockoutDuration() * 1000;
1433
1434 if ((requiredElapsedTime != 0) &&
1435 (elapsedTime > requiredElapsedTime)) {
1436
1437 user.setLockout(false);
1438 user.setLockoutDate(null);
1439
1440 userPersistence.update(user);
1441 }
1442 }
1443
1444 if (user.isLockout()) {
1445 throw new UserLockoutException();
1446 }
1447 }
1448
1449
1456 @Override
1457 public void checkLoginFailure(User user) throws SystemException {
1458 Date now = new Date();
1459
1460 int failedLoginAttempts = user.getFailedLoginAttempts();
1461
1462 user.setLastFailedLoginDate(now);
1463 user.setFailedLoginAttempts(++failedLoginAttempts);
1464
1465 userPersistence.update(user);
1466 }
1467
1468
1478 @Override
1479 public void checkLoginFailureByEmailAddress(
1480 long companyId, String emailAddress)
1481 throws PortalException, SystemException {
1482
1483 User user = getUserByEmailAddress(companyId, emailAddress);
1484
1485 checkLoginFailure(user);
1486 }
1487
1488
1496 @Override
1497 public void checkLoginFailureById(long userId)
1498 throws PortalException, SystemException {
1499
1500 User user = userPersistence.findByPrimaryKey(userId);
1501
1502 checkLoginFailure(user);
1503 }
1504
1505
1514 @Override
1515 public void checkLoginFailureByScreenName(long companyId, String screenName)
1516 throws PortalException, SystemException {
1517
1518 User user = getUserByScreenName(companyId, screenName);
1519
1520 checkLoginFailure(user);
1521 }
1522
1523
1533 @Override
1534 public void checkPasswordExpired(User user)
1535 throws PortalException, SystemException {
1536
1537 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1538 return;
1539 }
1540
1541 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1542
1543
1544
1545 if (isPasswordExpired(user)) {
1546 int graceLoginCount = user.getGraceLoginCount();
1547
1548 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1549 user.setGraceLoginCount(++graceLoginCount);
1550
1551 userPersistence.update(user);
1552 }
1553 else {
1554 user.setDigest(StringPool.BLANK);
1555
1556 userPersistence.update(user);
1557
1558 throw new PasswordExpiredException();
1559 }
1560 }
1561
1562
1563
1564 if (passwordPolicy.isChangeable() &&
1565 passwordPolicy.isChangeRequired()) {
1566
1567 if (user.getLastLoginDate() == null) {
1568 user.setPasswordReset(true);
1569
1570 userPersistence.update(user);
1571 }
1572 }
1573 }
1574
1575
1581 @Override
1582 public void clearOrganizationUsers(long organizationId)
1583 throws SystemException {
1584
1585 organizationPersistence.clearUsers(organizationId);
1586
1587 PermissionCacheUtil.clearCache();
1588 }
1589
1590
1596 @Override
1597 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1598 userGroupPersistence.clearUsers(userGroupId);
1599
1600 PermissionCacheUtil.clearCache();
1601 }
1602
1603
1618 @Override
1619 public void completeUserRegistration(
1620 User user, ServiceContext serviceContext)
1621 throws PortalException, SystemException {
1622
1623 boolean autoPassword = ParamUtil.getBoolean(
1624 serviceContext, "autoPassword");
1625
1626 String password = (String)serviceContext.getAttribute(
1627 "passwordUnencrypted");
1628
1629 if (autoPassword) {
1630 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1631 if (_log.isWarnEnabled()) {
1632 StringBundler sb = new StringBundler(4);
1633
1634 sb.append("When LDAP password policy is enabled, it is ");
1635 sb.append("possible that portal generated passwords will ");
1636 sb.append("not match the LDAP policy. Using ");
1637 sb.append("RegExpToolkit to generate new password.");
1638
1639 _log.warn(sb.toString());
1640 }
1641
1642 RegExpToolkit regExpToolkit = new RegExpToolkit();
1643
1644 password = regExpToolkit.generate(null);
1645 }
1646 else {
1647 PasswordPolicy passwordPolicy =
1648 passwordPolicyLocalService.getPasswordPolicy(
1649 user.getCompanyId(), user.getOrganizationIds());
1650
1651 password = PwdToolkitUtil.generate(passwordPolicy);
1652 }
1653
1654 serviceContext.setAttribute("passwordUnencrypted", password);
1655
1656 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1657 user.setPasswordUnencrypted(password);
1658 user.setPasswordEncrypted(true);
1659 user.setPasswordModified(true);
1660 user.setPasswordModifiedDate(new Date());
1661
1662 userPersistence.update(user);
1663
1664 user.setPasswordModified(false);
1665 }
1666
1667 if (user.hasCompanyMx()) {
1668 mailService.addUser(
1669 user.getCompanyId(), user.getUserId(), password,
1670 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1671 user.getEmailAddress());
1672 }
1673
1674 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1675
1676 if (sendEmail) {
1677 sendEmail(user, password, serviceContext);
1678 }
1679
1680 Company company = companyPersistence.findByPrimaryKey(
1681 user.getCompanyId());
1682
1683 if (company.isStrangersVerify()) {
1684 sendEmailAddressVerification(
1685 user, user.getEmailAddress(), serviceContext);
1686 }
1687 }
1688
1689
1702 @Override
1703 public KeyValuePair decryptUserId(
1704 long companyId, String name, String password)
1705 throws PortalException, SystemException {
1706
1707 Company company = companyPersistence.findByPrimaryKey(companyId);
1708
1709 try {
1710 name = Encryptor.decrypt(company.getKeyObj(), name);
1711 }
1712 catch (EncryptorException ee) {
1713 throw new SystemException(ee);
1714 }
1715
1716 long userId = GetterUtil.getLong(name);
1717
1718 User user = userPersistence.findByPrimaryKey(userId);
1719
1720 try {
1721 password = Encryptor.decrypt(company.getKeyObj(), password);
1722 }
1723 catch (EncryptorException ee) {
1724 throw new SystemException(ee);
1725 }
1726
1727 String userPassword = user.getPassword();
1728 String encPassword = PasswordEncryptorUtil.encrypt(
1729 password, userPassword);
1730
1731 if (userPassword.equals(encPassword)) {
1732 if (isPasswordExpired(user)) {
1733 user.setPasswordReset(true);
1734
1735 userPersistence.update(user);
1736 }
1737
1738 return new KeyValuePair(name, password);
1739 }
1740 else {
1741 throw new PrincipalException();
1742 }
1743 }
1744
1745
1753 @Override
1754 public void deletePortrait(long userId)
1755 throws PortalException, SystemException {
1756
1757 User user = userPersistence.findByPrimaryKey(userId);
1758
1759 long portraitId = user.getPortraitId();
1760
1761 if (portraitId > 0) {
1762 user.setPortraitId(0);
1763
1764 userPersistence.update(user);
1765
1766 imageLocalService.deleteImage(portraitId);
1767 }
1768 }
1769
1770
1779 @Override
1780 public void deleteRoleUser(long roleId, long userId)
1781 throws PortalException, SystemException {
1782
1783 rolePersistence.removeUser(roleId, userId);
1784
1785 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1786
1787 indexer.reindex(userId);
1788
1789 PermissionCacheUtil.clearCache();
1790 }
1791
1792
1800 @Override
1801 public User deleteUser(long userId)
1802 throws PortalException, SystemException {
1803
1804 User user = userPersistence.findByPrimaryKey(userId);
1805
1806 return deleteUser(user);
1807 }
1808
1809
1817 @Override
1818 public User deleteUser(User user) throws PortalException, SystemException {
1819 if (!PropsValues.USERS_DELETE) {
1820 throw new RequiredUserException();
1821 }
1822
1823
1824
1825 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1826
1827
1828
1829 Group group = null;
1830
1831 if (!user.isDefaultUser()) {
1832 group = user.getGroup();
1833 }
1834
1835 if (group != null) {
1836 groupLocalService.deleteGroup(group);
1837 }
1838
1839
1840
1841 try {
1842 imageLocalService.deleteImage(user.getPortraitId());
1843 }
1844 catch (NoSuchImageException nsie) {
1845 if (_log.isWarnEnabled()) {
1846 _log.warn("Unable to delete image " + user.getPortraitId());
1847 }
1848 }
1849
1850
1851
1852 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1853 User.class.getName(), user.getUserId());
1854
1855
1856
1857 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1858
1859
1860
1861 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1862
1863
1864
1865 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1866
1867
1868
1869 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1870
1871
1872
1873 assetEntryLocalService.deleteEntry(
1874 User.class.getName(), user.getUserId());
1875
1876
1877
1878 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1879
1880
1881
1882 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1883
1884
1885
1886 expandoRowLocalService.deleteRows(user.getUserId());
1887
1888
1889
1890 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1891 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1892 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1893
1894
1895
1896 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1897 user.getUserId());
1898
1899
1900
1901 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1902
1903
1904
1905 socialActivityLocalService.deleteUserActivities(user.getUserId());
1906 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1907 socialRequestLocalService.deleteUserRequests(user.getUserId());
1908
1909
1910
1911 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1912
1913
1914
1915 Contact contact = contactLocalService.fetchContact(user.getContactId());
1916
1917 if (contact != null) {
1918 contactLocalService.deleteContact(contact);
1919 }
1920
1921
1922
1923 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1924 user.getUserId());
1925
1926
1927
1928 resourceLocalService.deleteResource(
1929 user.getCompanyId(), User.class.getName(),
1930 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1931
1932
1933
1934 userPersistence.remove(user);
1935
1936
1937
1938 PermissionCacheUtil.clearCache();
1939
1940
1941
1942 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1943 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1944
1945 return user;
1946 }
1947
1948
1956 @Override
1957 public void deleteUserGroupUser(long userGroupId, long userId)
1958 throws PortalException, SystemException {
1959
1960 userGroupPersistence.removeUser(userGroupId, userId);
1961
1962 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1963
1964 indexer.reindex(userId);
1965
1966 PermissionCacheUtil.clearCache();
1967 }
1968
1969
1978 @Override
1979 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1980 public String encryptUserId(String name)
1981 throws PortalException, SystemException {
1982
1983 long userId = GetterUtil.getLong(name);
1984
1985 User user = userPersistence.findByPrimaryKey(userId);
1986
1987 Company company = companyPersistence.findByPrimaryKey(
1988 user.getCompanyId());
1989
1990 try {
1991 return Encryptor.encrypt(company.getKeyObj(), name);
1992 }
1993 catch (EncryptorException ee) {
1994 throw new SystemException(ee);
1995 }
1996 }
1997
1998
2007 @Override
2008 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2009 throws SystemException {
2010
2011 emailAddress = getLogin(emailAddress);
2012
2013 return userPersistence.fetchByC_EA(companyId, emailAddress);
2014 }
2015
2016
2025 @Override
2026 public User fetchUserByFacebookId(long companyId, long facebookId)
2027 throws SystemException {
2028
2029 return userPersistence.fetchByC_FID(companyId, facebookId);
2030 }
2031
2032
2040 @Override
2041 public User fetchUserById(long userId) throws SystemException {
2042 return userPersistence.fetchByPrimaryKey(userId);
2043 }
2044
2045
2054 @Override
2055 public User fetchUserByOpenId(long companyId, String openId)
2056 throws SystemException {
2057
2058 return userPersistence.fetchByC_O(companyId, openId);
2059 }
2060
2061
2070 @Override
2071 public User fetchUserByScreenName(long companyId, String screenName)
2072 throws SystemException {
2073
2074 screenName = getLogin(screenName);
2075
2076 return userPersistence.fetchByC_SN(companyId, screenName);
2077 }
2078
2079
2098 @Override
2099 public List<User> getCompanyUsers(long companyId, int start, int end)
2100 throws SystemException {
2101
2102 return userPersistence.findByCompanyId(companyId, start, end);
2103 }
2104
2105
2112 @Override
2113 public int getCompanyUsersCount(long companyId) throws SystemException {
2114 return userPersistence.countByCompanyId(companyId);
2115 }
2116
2117
2126 @Override
2127 @Skip
2128 public User getDefaultUser(long companyId)
2129 throws PortalException, SystemException {
2130
2131 User userModel = _defaultUsers.get(companyId);
2132
2133 if (userModel == null) {
2134 userModel = userLocalService.loadGetDefaultUser(companyId);
2135
2136 _defaultUsers.put(companyId, userModel);
2137 }
2138
2139 return userModel;
2140 }
2141
2142
2151 @Override
2152 @Skip
2153 public long getDefaultUserId(long companyId)
2154 throws PortalException, SystemException {
2155
2156 User user = getDefaultUser(companyId);
2157
2158 return user.getUserId();
2159 }
2160
2161
2168 @Override
2169 public long[] getGroupUserIds(long groupId) throws SystemException {
2170 return getUserIds(getGroupUsers(groupId));
2171 }
2172
2173
2183 @Override
2184 public int getGroupUsersCount(long groupId, int status)
2185 throws PortalException, SystemException {
2186
2187 Group group = groupPersistence.findByPrimaryKey(groupId);
2188
2189 LinkedHashMap<String, Object> params =
2190 new LinkedHashMap<String, Object>();
2191
2192 params.put("usersGroups", new Long(groupId));
2193
2194 return searchCount(group.getCompanyId(), null, status, params);
2195 }
2196
2197 @Override
2198 public List<User> getInheritedRoleUsers(
2199 long roleId, int start, int end, OrderByComparator obc)
2200 throws PortalException, SystemException {
2201
2202 Role role = rolePersistence.findByPrimaryKey(roleId);
2203
2204 LinkedHashMap<String, Object> params =
2205 new LinkedHashMap<String, Object>();
2206
2207 params.put("inherit", Boolean.TRUE);
2208 params.put("usersRoles", roleId);
2209
2210 return search(
2211 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2212 params, start, end, obc);
2213 }
2214
2215
2223 @Override
2224 public List<User> getNoAnnouncementsDeliveries(String type)
2225 throws SystemException {
2226
2227 return userFinder.findByNoAnnouncementsDeliveries(type);
2228 }
2229
2230
2236 @Override
2237 public List<User> getNoContacts() throws SystemException {
2238 return userFinder.findByNoContacts();
2239 }
2240
2241
2248 @Override
2249 public List<User> getNoGroups() throws SystemException {
2250 return userFinder.findByNoGroups();
2251 }
2252
2253
2260 @Override
2261 public long[] getOrganizationUserIds(long organizationId)
2262 throws SystemException {
2263
2264 return getUserIds(getOrganizationUsers(organizationId));
2265 }
2266
2267
2278 @Override
2279 public int getOrganizationUsersCount(long organizationId, int status)
2280 throws PortalException, SystemException {
2281
2282 Organization organization = organizationPersistence.findByPrimaryKey(
2283 organizationId);
2284
2285 LinkedHashMap<String, Object> params =
2286 new LinkedHashMap<String, Object>();
2287
2288 params.put("usersOrgs", new Long(organizationId));
2289
2290 return searchCount(organization.getCompanyId(), null, status, params);
2291 }
2292
2293
2300 @Override
2301 public long[] getRoleUserIds(long roleId) throws SystemException {
2302 return getUserIds(getRoleUsers(roleId));
2303 }
2304
2305
2315 @Override
2316 public int getRoleUsersCount(long roleId, int status)
2317 throws PortalException, SystemException {
2318
2319 Role role = rolePersistence.findByPrimaryKey(roleId);
2320
2321 LinkedHashMap<String, Object> params =
2322 new LinkedHashMap<String, Object>();
2323
2324 params.put("usersRoles", new Long(roleId));
2325
2326 return searchCount(role.getCompanyId(), null, status, params);
2327 }
2328
2329
2356 @Override
2357 public List<User> getSocialUsers(
2358 long userId, int type, int start, int end, OrderByComparator obc)
2359 throws PortalException, SystemException {
2360
2361 User user = userPersistence.findByPrimaryKey(userId);
2362
2363 LinkedHashMap<String, Object> params =
2364 new LinkedHashMap<String, Object>();
2365
2366 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2367
2368 return search(
2369 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2370 params, start, end, obc);
2371 }
2372
2373
2396 @Override
2397 public List<User> getSocialUsers(
2398 long userId, int start, int end, OrderByComparator obc)
2399 throws PortalException, SystemException {
2400
2401 User user = userPersistence.findByPrimaryKey(userId);
2402
2403 LinkedHashMap<String, Object> params =
2404 new LinkedHashMap<String, Object>();
2405
2406 params.put("socialRelation", new Long[] {userId});
2407
2408 return search(
2409 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2410 params, start, end, obc);
2411 }
2412
2413
2441 @Override
2442 public List<User> getSocialUsers(
2443 long userId1, long userId2, int type, int start, int end,
2444 OrderByComparator obc)
2445 throws PortalException, SystemException {
2446
2447 User user1 = userPersistence.findByPrimaryKey(userId1);
2448
2449 LinkedHashMap<String, Object> params =
2450 new LinkedHashMap<String, Object>();
2451
2452 params.put(
2453 "socialMutualRelationType",
2454 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2455
2456 return search(
2457 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2458 params, start, end, obc);
2459 }
2460
2461
2486 @Override
2487 public List<User> getSocialUsers(
2488 long userId1, long userId2, int start, int end,
2489 OrderByComparator obc)
2490 throws PortalException, SystemException {
2491
2492 User user1 = userPersistence.findByPrimaryKey(userId1);
2493
2494 LinkedHashMap<String, Object> params =
2495 new LinkedHashMap<String, Object>();
2496
2497 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2498
2499 return search(
2500 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2501 params, start, end, obc);
2502 }
2503
2504
2512 @Override
2513 public int getSocialUsersCount(long userId)
2514 throws PortalException, SystemException {
2515
2516 User user = userPersistence.findByPrimaryKey(userId);
2517
2518 LinkedHashMap<String, Object> params =
2519 new LinkedHashMap<String, Object>();
2520
2521 params.put("socialRelation", new Long[] {userId});
2522
2523 return searchCount(
2524 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2525 params);
2526 }
2527
2528
2541 @Override
2542 public int getSocialUsersCount(long userId, int type)
2543 throws PortalException, SystemException {
2544
2545 User user = userPersistence.findByPrimaryKey(userId);
2546
2547 LinkedHashMap<String, Object> params =
2548 new LinkedHashMap<String, Object>();
2549
2550 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2551
2552 return searchCount(
2553 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2554 params);
2555 }
2556
2557
2567 @Override
2568 public int getSocialUsersCount(long userId1, long userId2)
2569 throws PortalException, SystemException {
2570
2571 User user1 = userPersistence.findByPrimaryKey(userId1);
2572
2573 LinkedHashMap<String, Object> params =
2574 new LinkedHashMap<String, Object>();
2575
2576 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2577
2578 return searchCount(
2579 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2580 params);
2581 }
2582
2583
2597 @Override
2598 public int getSocialUsersCount(long userId1, long userId2, int type)
2599 throws PortalException, SystemException {
2600
2601 User user1 = userPersistence.findByPrimaryKey(userId1);
2602
2603 LinkedHashMap<String, Object> params =
2604 new LinkedHashMap<String, Object>();
2605
2606 params.put(
2607 "socialMutualRelationType",
2608 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2609
2610 return searchCount(
2611 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2612 params);
2613 }
2614
2615
2623 @Override
2624 public User getUserByContactId(long contactId)
2625 throws PortalException, SystemException {
2626
2627 return userPersistence.findByContactId(contactId);
2628 }
2629
2630
2640 @Override
2641 public User getUserByEmailAddress(long companyId, String emailAddress)
2642 throws PortalException, SystemException {
2643
2644 emailAddress = getLogin(emailAddress);
2645
2646 return userPersistence.findByC_EA(companyId, emailAddress);
2647 }
2648
2649
2658 @Override
2659 public User getUserByFacebookId(long companyId, long facebookId)
2660 throws PortalException, SystemException {
2661
2662 return userPersistence.findByC_FID(companyId, facebookId);
2663 }
2664
2665
2673 @Override
2674 public User getUserById(long userId)
2675 throws PortalException, SystemException {
2676
2677 return userPersistence.findByPrimaryKey(userId);
2678 }
2679
2680
2690 @Override
2691 public User getUserById(long companyId, long userId)
2692 throws PortalException, SystemException {
2693
2694 return userPersistence.findByC_U(companyId, userId);
2695 }
2696
2697
2706 @Override
2707 public User getUserByOpenId(long companyId, String openId)
2708 throws PortalException, SystemException {
2709
2710 return userPersistence.findByC_O(companyId, openId);
2711 }
2712
2713
2721 @Override
2722 public User getUserByPortraitId(long portraitId)
2723 throws PortalException, SystemException {
2724
2725 return userPersistence.findByPortraitId(portraitId);
2726 }
2727
2728
2737 @Override
2738 public User getUserByScreenName(long companyId, String screenName)
2739 throws PortalException, SystemException {
2740
2741 screenName = getLogin(screenName);
2742
2743 return userPersistence.findByC_SN(companyId, screenName);
2744 }
2745
2746
2756 @Override
2757 public User getUserByUuid(String uuid)
2758 throws PortalException, SystemException {
2759
2760 List<User> users = userPersistence.findByUuid(uuid);
2761
2762 if (users.isEmpty()) {
2763 throw new NoSuchUserException("{uuid=" + uuid + "}");
2764 }
2765 else {
2766 return users.get(0);
2767 }
2768 }
2769
2770
2779 @Override
2780 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2781 throws PortalException, SystemException {
2782
2783 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2784
2785 if (users.isEmpty()) {
2786 StringBundler sb = new StringBundler(5);
2787
2788 sb.append("{uuid=");
2789 sb.append(uuid);
2790 sb.append(", companyId=");
2791 sb.append(companyId);
2792 sb.append("}");
2793
2794 throw new NoSuchUserException(sb.toString());
2795 }
2796 else {
2797 return users.get(0);
2798 }
2799 }
2800
2801
2811 @Override
2812 public int getUserGroupUsersCount(long userGroupId, int status)
2813 throws PortalException, SystemException {
2814
2815 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2816 userGroupId);
2817
2818 LinkedHashMap<String, Object> params =
2819 new LinkedHashMap<String, Object>();
2820
2821 params.put("usersUserGroups", new Long(userGroupId));
2822
2823 return searchCount(userGroup.getCompanyId(), null, status, params);
2824 }
2825
2826
2836 @Override
2837 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2838 throws PortalException, SystemException {
2839
2840 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2841
2842 User user = userPersistence.findByC_EA(companyId, emailAddress);
2843
2844 return user.getUserId();
2845 }
2846
2847
2856 @Override
2857 public long getUserIdByScreenName(long companyId, String screenName)
2858 throws PortalException, SystemException {
2859
2860 screenName = getLogin(screenName);
2861
2862 User user = userPersistence.findByC_SN(companyId, screenName);
2863
2864 return user.getUserId();
2865 }
2866
2867
2877 @Override
2878 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2879 throws SystemException {
2880
2881 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2882 passwordPolicyId, User.class.getName(), userId);
2883 }
2884
2885
2900 @Override
2901 public boolean hasRoleUser(
2902 long companyId, String name, long userId, boolean inherited)
2903 throws PortalException, SystemException {
2904
2905 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2906 }
2907
2908
2918 @Override
2919 public boolean isPasswordExpired(User user)
2920 throws PortalException, SystemException {
2921
2922 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2923
2924 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2925 Date now = new Date();
2926
2927 if (user.getPasswordModifiedDate() == null) {
2928 user.setPasswordModifiedDate(now);
2929
2930 userLocalService.updateUser(user);
2931 }
2932
2933 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2934 long elapsedTime = now.getTime() - passwordStartTime;
2935
2936 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2937 return true;
2938 }
2939 else {
2940 return false;
2941 }
2942 }
2943
2944 return false;
2945 }
2946
2947
2959 @Override
2960 public boolean isPasswordExpiringSoon(User user)
2961 throws PortalException, SystemException {
2962
2963 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2964
2965 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2966 (passwordPolicy.getWarningTime() > 0)) {
2967
2968 Date now = new Date();
2969
2970 if (user.getPasswordModifiedDate() == null) {
2971 user.setPasswordModifiedDate(now);
2972
2973 userLocalService.updateUser(user);
2974 }
2975
2976 long timeModified = user.getPasswordModifiedDate().getTime();
2977 long passwordExpiresOn =
2978 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2979
2980 long timeStartWarning =
2981 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2982
2983 if (now.getTime() > timeStartWarning) {
2984 return true;
2985 }
2986 else {
2987 return false;
2988 }
2989 }
2990
2991 return false;
2992 }
2993
2994
3002 @Override
3003 public User loadGetDefaultUser(long companyId)
3004 throws PortalException, SystemException {
3005
3006 return userPersistence.findByC_DU(companyId, true);
3007 }
3008
3009
3041 @Override
3042 public List<User> search(
3043 long companyId, String keywords, int status,
3044 LinkedHashMap<String, Object> params, int start, int end,
3045 OrderByComparator obc)
3046 throws SystemException {
3047
3048 return userFinder.findByKeywords(
3049 companyId, keywords, status, params, start, end, obc);
3050 }
3051
3052
3083 @Override
3084 public Hits search(
3085 long companyId, String keywords, int status,
3086 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3087 throws SystemException {
3088
3089 String firstName = null;
3090 String middleName = null;
3091 String lastName = null;
3092 String fullName = null;
3093 String screenName = null;
3094 String emailAddress = null;
3095 String street = null;
3096 String city = null;
3097 String zip = null;
3098 String region = null;
3099 String country = null;
3100 boolean andOperator = false;
3101
3102 if (Validator.isNotNull(keywords)) {
3103 firstName = keywords;
3104 middleName = keywords;
3105 lastName = keywords;
3106 fullName = keywords;
3107 screenName = keywords;
3108 emailAddress = keywords;
3109 street = keywords;
3110 city = keywords;
3111 zip = keywords;
3112 region = keywords;
3113 country = keywords;
3114 }
3115 else {
3116 andOperator = true;
3117 }
3118
3119 if (params != null) {
3120 params.put("keywords", keywords);
3121 }
3122
3123 return search(
3124 companyId, firstName, middleName, lastName, fullName, screenName,
3125 emailAddress, street, city, zip, region, country, status, params,
3126 andOperator, start, end, sort);
3127 }
3128
3129
3169 @Override
3170 public List<User> search(
3171 long companyId, String firstName, String middleName,
3172 String lastName, String screenName, String emailAddress, int status,
3173 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3174 int end, OrderByComparator obc)
3175 throws SystemException {
3176
3177 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3178 companyId, firstName, middleName, lastName, screenName,
3179 emailAddress, status, params, andSearch, start, end, obc);
3180 }
3181
3182
3221 @Override
3222 public Hits search(
3223 long companyId, String firstName, String middleName,
3224 String lastName, String screenName, String emailAddress, int status,
3225 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3226 int end, Sort sort)
3227 throws SystemException {
3228
3229 return search(
3230 companyId, firstName, middleName, lastName, null, screenName,
3231 emailAddress, null, null, null, null, null, status, params,
3232 andSearch, start, end, sort);
3233 }
3234
3235
3249 @Override
3250 public int searchCount(
3251 long companyId, String keywords, int status,
3252 LinkedHashMap<String, Object> params)
3253 throws SystemException {
3254
3255 return userFinder.countByKeywords(companyId, keywords, status, params);
3256 }
3257
3258
3280 @Override
3281 public int searchCount(
3282 long companyId, String firstName, String middleName,
3283 String lastName, String screenName, String emailAddress, int status,
3284 LinkedHashMap<String, Object> params, boolean andSearch)
3285 throws SystemException {
3286
3287 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3288 companyId, firstName, middleName, lastName, screenName,
3289 emailAddress, status, params, andSearch);
3290 }
3291
3292
3303 @Override
3304 public void sendEmailAddressVerification(
3305 User user, String emailAddress, ServiceContext serviceContext)
3306 throws PortalException, SystemException {
3307
3308 if (user.isEmailAddressVerified() &&
3309 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3310
3311 return;
3312 }
3313
3314 Ticket ticket = ticketLocalService.addTicket(
3315 user.getCompanyId(), User.class.getName(), user.getUserId(),
3316 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3317 serviceContext);
3318
3319 String verifyEmailAddressURL =
3320 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3321 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3322
3323 long plid = serviceContext.getPlid();
3324
3325 if (plid > 0) {
3326 Layout layout = layoutLocalService.fetchLayout(plid);
3327
3328 if (layout != null) {
3329 Group group = layout.getGroup();
3330
3331 if (!layout.isPrivateLayout() && !group.isUser()) {
3332 verifyEmailAddressURL +=
3333 "&p_l_id=" + serviceContext.getPlid();
3334 }
3335 }
3336 }
3337
3338 String fromName = PrefsPropsUtil.getString(
3339 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3340 String fromAddress = PrefsPropsUtil.getString(
3341 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3342
3343 String toName = user.getFullName();
3344 String toAddress = emailAddress;
3345
3346 String subject = PrefsPropsUtil.getContent(
3347 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3348
3349 String body = PrefsPropsUtil.getContent(
3350 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3351
3352 SubscriptionSender subscriptionSender = new SubscriptionSender();
3353
3354 subscriptionSender.setBody(body);
3355 subscriptionSender.setCompanyId(user.getCompanyId());
3356 subscriptionSender.setContextAttributes(
3357 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3358 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3359 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3360 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3361 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3362 subscriptionSender.setFrom(fromAddress, fromName);
3363 subscriptionSender.setHtmlFormat(true);
3364 subscriptionSender.setMailId(
3365 "user", user.getUserId(), System.currentTimeMillis(),
3366 PwdGenerator.getPassword());
3367 subscriptionSender.setServiceContext(serviceContext);
3368 subscriptionSender.setSubject(subject);
3369 subscriptionSender.setUserId(user.getUserId());
3370
3371 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3372
3373 subscriptionSender.flushNotificationsAsync();
3374 }
3375
3376
3395 @Override
3396 public void sendPassword(
3397 long companyId, String emailAddress, String fromName,
3398 String fromAddress, String subject, String body,
3399 ServiceContext serviceContext)
3400 throws PortalException, SystemException {
3401
3402 Company company = companyPersistence.findByPrimaryKey(companyId);
3403
3404 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3405 return;
3406 }
3407
3408 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3409
3410 if (Validator.isNull(emailAddress)) {
3411 throw new UserEmailAddressException();
3412 }
3413
3414 User user = userPersistence.findByC_EA(companyId, emailAddress);
3415
3416 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3417
3418 String newPassword = StringPool.BLANK;
3419 String passwordResetURL = StringPool.BLANK;
3420
3421 if (company.isSendPasswordResetLink()) {
3422 Date expirationDate = null;
3423
3424 if ((passwordPolicy != null) &&
3425 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3426
3427 expirationDate = new Date(
3428 System.currentTimeMillis() +
3429 (passwordPolicy.getResetTicketMaxAge() * 1000));
3430 }
3431
3432 Ticket ticket = ticketLocalService.addTicket(
3433 companyId, User.class.getName(), user.getUserId(),
3434 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3435 serviceContext);
3436
3437 passwordResetURL =
3438 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3439 "/portal/update_password?p_l_id="+
3440 serviceContext.getPlid() +
3441 "&ticketKey=" + ticket.getKey();
3442 }
3443 else {
3444 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3445 PasswordEncryptorUtil.TYPE_NONE)) {
3446
3447 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3448 user.getCompanyId())) {
3449
3450 if (_log.isWarnEnabled()) {
3451 StringBundler sb = new StringBundler(5);
3452
3453 sb.append("When LDAP password policy is enabled, ");
3454 sb.append("it is possible that portal generated ");
3455 sb.append("passwords will not match the LDAP policy.");
3456 sb.append("Using RegExpToolkit to generate new ");
3457 sb.append("password.");
3458
3459 _log.warn(sb.toString());
3460 }
3461
3462 RegExpToolkit regExpToolkit = new RegExpToolkit();
3463
3464 newPassword = regExpToolkit.generate(null);
3465 }
3466 else {
3467 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3468 }
3469
3470 boolean passwordReset = false;
3471
3472 if (passwordPolicy.getChangeable() &&
3473 passwordPolicy.getChangeRequired()) {
3474
3475 passwordReset = true;
3476 }
3477
3478 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3479 user.setPasswordUnencrypted(newPassword);
3480 user.setPasswordEncrypted(true);
3481 user.setPasswordReset(passwordReset);
3482 user.setPasswordModified(true);
3483 user.setPasswordModifiedDate(new Date());
3484
3485 userPersistence.update(user);
3486
3487 user.setPasswordModified(false);
3488 }
3489 else {
3490 newPassword = user.getPassword();
3491 }
3492 }
3493
3494 if (Validator.isNull(fromName)) {
3495 fromName = PrefsPropsUtil.getString(
3496 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3497 }
3498
3499 if (Validator.isNull(fromAddress)) {
3500 fromAddress = PrefsPropsUtil.getString(
3501 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3502 }
3503
3504 String toName = user.getFullName();
3505 String toAddress = user.getEmailAddress();
3506
3507 if (Validator.isNull(subject)) {
3508 if (company.isSendPasswordResetLink()) {
3509 subject = PrefsPropsUtil.getContent(
3510 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3511 }
3512 else {
3513 subject = PrefsPropsUtil.getContent(
3514 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3515 }
3516 }
3517
3518 if (Validator.isNull(body)) {
3519 if (company.isSendPasswordResetLink()) {
3520 body = PrefsPropsUtil.getContent(
3521 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3522 }
3523 else {
3524 body = PrefsPropsUtil.getContent(
3525 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3526 }
3527 }
3528
3529 SubscriptionSender subscriptionSender = new SubscriptionSender();
3530
3531 subscriptionSender.setBody(body);
3532 subscriptionSender.setCompanyId(companyId);
3533 subscriptionSender.setContextAttributes(
3534 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3535 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3536 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3537 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3538 user.getScreenName());
3539 subscriptionSender.setFrom(fromAddress, fromName);
3540 subscriptionSender.setHtmlFormat(true);
3541 subscriptionSender.setMailId(
3542 "user", user.getUserId(), System.currentTimeMillis(),
3543 PwdGenerator.getPassword());
3544 subscriptionSender.setServiceContext(serviceContext);
3545 subscriptionSender.setSubject(subject);
3546 subscriptionSender.setUserId(user.getUserId());
3547
3548 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3549
3550 subscriptionSender.flushNotificationsAsync();
3551 }
3552
3553
3562 @Override
3563 public void setRoleUsers(long roleId, long[] userIds)
3564 throws PortalException, SystemException {
3565
3566 rolePersistence.setUsers(roleId, userIds);
3567
3568 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3569
3570 indexer.reindex(userIds);
3571
3572 PermissionCacheUtil.clearCache();
3573 }
3574
3575
3584 @Override
3585 @SuppressWarnings("deprecation")
3586 public void setUserGroupUsers(long userGroupId, long[] userIds)
3587 throws PortalException, SystemException {
3588
3589 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3590 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3591 }
3592
3593 userGroupPersistence.setUsers(userGroupId, userIds);
3594
3595 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3596
3597 indexer.reindex(userIds);
3598
3599 PermissionCacheUtil.clearCache();
3600 }
3601
3602
3610 @Override
3611 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3612 throws PortalException, SystemException {
3613
3614 List<Team> teams = teamPersistence.findByGroupId(groupId);
3615
3616 for (Team team : teams) {
3617 unsetTeamUsers(team.getTeamId(), userIds);
3618 }
3619
3620 PermissionCacheUtil.clearCache();
3621 }
3622
3623
3633 @Override
3634 public void unsetGroupUsers(
3635 final long groupId, final long[] userIds,
3636 ServiceContext serviceContext)
3637 throws PortalException, SystemException {
3638
3639 userGroupRoleLocalService.deleteUserGroupRoles(
3640 userIds, groupId, RoleConstants.TYPE_SITE);
3641
3642 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3643
3644 groupPersistence.removeUsers(groupId, userIds);
3645
3646 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3647
3648 indexer.reindex(userIds);
3649
3650 PermissionCacheUtil.clearCache();
3651
3652 Callable<Void> callable = new Callable<Void>() {
3653
3654 @Override
3655 public Void call() throws Exception {
3656 Message message = new Message();
3657
3658 message.put("groupId", groupId);
3659 message.put("userIds", userIds);
3660
3661 MessageBusUtil.sendMessage(
3662 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3663
3664 return null;
3665 }
3666
3667 };
3668
3669 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3670 }
3671
3672
3680 @Override
3681 public void unsetOrganizationUsers(
3682 long organizationId, final long[] userIds)
3683 throws PortalException, SystemException {
3684
3685 Organization organization = organizationPersistence.findByPrimaryKey(
3686 organizationId);
3687
3688 final Group group = organization.getGroup();
3689
3690 userGroupRoleLocalService.deleteUserGroupRoles(
3691 userIds, group.getGroupId());
3692
3693 organizationPersistence.removeUsers(organizationId, userIds);
3694
3695 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3696
3697 indexer.reindex(userIds);
3698
3699 PermissionCacheUtil.clearCache();
3700
3701 Callable<Void> callable = new Callable<Void>() {
3702
3703 @Override
3704 public Void call() throws Exception {
3705 Message message = new Message();
3706
3707 message.put("groupId", group.getGroupId());
3708 message.put("userIds", userIds);
3709
3710 MessageBusUtil.sendMessage(
3711 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3712
3713 return null;
3714 }
3715
3716 };
3717
3718 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3719 }
3720
3721
3728 @Override
3729 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3730 throws SystemException {
3731
3732 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3733 passwordPolicyId, User.class.getName(), userIds);
3734 }
3735
3736
3744 @Override
3745 public void unsetRoleUsers(long roleId, List<User> users)
3746 throws PortalException, SystemException {
3747
3748 Role role = rolePersistence.findByPrimaryKey(roleId);
3749
3750 String roleName = role.getName();
3751
3752 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3753 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3754 roleName.equals(RoleConstants.USER)) {
3755
3756 return;
3757 }
3758
3759 rolePersistence.removeUsers(roleId, users);
3760
3761 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3762
3763 indexer.reindex(users);
3764
3765 PermissionCacheUtil.clearCache();
3766 }
3767
3768
3776 @Override
3777 public void unsetRoleUsers(long roleId, long[] userIds)
3778 throws PortalException, SystemException {
3779
3780 Role role = rolePersistence.findByPrimaryKey(roleId);
3781
3782 String roleName = role.getName();
3783
3784 if (roleName.equals(RoleConstants.USER) ||
3785 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3786 getRoleUsersCount(role.getRoleId()) <= 1)) {
3787
3788 return;
3789 }
3790
3791 rolePersistence.removeUsers(roleId, userIds);
3792
3793 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3794
3795 indexer.reindex(userIds);
3796
3797 PermissionCacheUtil.clearCache();
3798 }
3799
3800
3808 @Override
3809 public void unsetTeamUsers(long teamId, long[] userIds)
3810 throws PortalException, SystemException {
3811
3812 teamPersistence.removeUsers(teamId, userIds);
3813
3814 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3815
3816 indexer.reindex(userIds);
3817
3818 PermissionCacheUtil.clearCache();
3819 }
3820
3821
3829 @Override
3830 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3831 throws PortalException, SystemException {
3832
3833 userGroupPersistence.removeUsers(userGroupId, userIds);
3834
3835 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3836
3837 indexer.reindex(userIds);
3838
3839 PermissionCacheUtil.clearCache();
3840 }
3841
3842
3852 @Override
3853 public User updateAgreedToTermsOfUse(
3854 long userId, boolean agreedToTermsOfUse)
3855 throws PortalException, SystemException {
3856
3857 User user = userPersistence.findByPrimaryKey(userId);
3858
3859 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3860
3861 userPersistence.update(user);
3862
3863 return user;
3864 }
3865
3866
3877 @Override
3878 public void updateAsset(
3879 long userId, User user, long[] assetCategoryIds,
3880 String[] assetTagNames)
3881 throws PortalException, SystemException {
3882
3883 User owner = userPersistence.findByPrimaryKey(userId);
3884
3885 Company company = companyPersistence.findByPrimaryKey(
3886 owner.getCompanyId());
3887
3888 Group companyGroup = company.getGroup();
3889
3890 assetEntryLocalService.updateEntry(
3891 userId, companyGroup.getGroupId(), user.getCreateDate(),
3892 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3893 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3894 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3895 null, false);
3896 }
3897
3898
3907 @Override
3908 public User updateCreateDate(long userId, Date createDate)
3909 throws PortalException, SystemException {
3910
3911 User user = userPersistence.findByPrimaryKey(userId);
3912
3913 user.setCreateDate(createDate);
3914
3915 userPersistence.update(user);
3916
3917 return user;
3918 }
3919
3920
3931 @Override
3932 public User updateEmailAddress(
3933 long userId, String password, String emailAddress1,
3934 String emailAddress2)
3935 throws PortalException, SystemException {
3936
3937 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
3938 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
3939
3940 User user = userPersistence.findByPrimaryKey(userId);
3941
3942 validateEmailAddress(user, emailAddress1, emailAddress2);
3943
3944 setEmailAddress(
3945 user, password, user.getFirstName(), user.getMiddleName(),
3946 user.getLastName(), emailAddress1);
3947
3948 userPersistence.update(user);
3949
3950 Contact contact = user.getContact();
3951
3952 contact.setEmailAddress(user.getEmailAddress());
3953
3954 contactPersistence.update(contact);
3955
3956 return user;
3957 }
3958
3959
3973 @Override
3974 public User updateEmailAddress(
3975 long userId, String password, String emailAddress1,
3976 String emailAddress2, ServiceContext serviceContext)
3977 throws PortalException, SystemException {
3978
3979 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
3980 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
3981
3982 User user = userPersistence.findByPrimaryKey(userId);
3983
3984 validateEmailAddress(user, emailAddress1, emailAddress2);
3985
3986 Company company = companyPersistence.findByPrimaryKey(
3987 user.getCompanyId());
3988
3989 if (!company.isStrangersVerify()) {
3990 setEmailAddress(
3991 user, password, user.getFirstName(), user.getMiddleName(),
3992 user.getLastName(), emailAddress1);
3993
3994 userPersistence.update(user);
3995
3996 Contact contact = user.getContact();
3997
3998 contact.setEmailAddress(user.getEmailAddress());
3999
4000 contactPersistence.update(contact);
4001 }
4002 else {
4003 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4004 }
4005
4006 return user;
4007 }
4008
4009
4018 @Override
4019 public User updateEmailAddressVerified(
4020 long userId, boolean emailAddressVerified)
4021 throws PortalException, SystemException {
4022
4023 User user = userPersistence.findByPrimaryKey(userId);
4024
4025 user.setEmailAddressVerified(emailAddressVerified);
4026
4027 userPersistence.update(user);
4028
4029 return user;
4030 }
4031
4032
4041 @Override
4042 public User updateFacebookId(long userId, long facebookId)
4043 throws PortalException, SystemException {
4044
4045 User user = userPersistence.findByPrimaryKey(userId);
4046
4047 user.setFacebookId(facebookId);
4048
4049 userPersistence.update(user);
4050
4051 return user;
4052 }
4053
4054
4064 @Override
4065 public void updateGroups(
4066 long userId, long[] newGroupIds, ServiceContext serviceContext)
4067 throws PortalException, SystemException {
4068
4069 updateGroups(
4070 userId, newGroupIds, serviceContext,
4071 serviceContext.isIndexingEnabled());
4072 }
4073
4074
4113 @Override
4114 public User updateIncompleteUser(
4115 long creatorUserId, long companyId, boolean autoPassword,
4116 String password1, String password2, boolean autoScreenName,
4117 String screenName, String emailAddress, long facebookId,
4118 String openId, Locale locale, String firstName, String middleName,
4119 String lastName, int prefixId, int suffixId, boolean male,
4120 int birthdayMonth, int birthdayDay, int birthdayYear,
4121 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4122 ServiceContext serviceContext)
4123 throws PortalException, SystemException {
4124
4125 User user = getUserByEmailAddress(companyId, emailAddress);
4126
4127 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4128 throw new PortalException("Invalid user status");
4129 }
4130
4131 User defaultUser = getDefaultUser(companyId);
4132
4133 if (facebookId > 0) {
4134 autoPassword = false;
4135
4136 if ((password1 == null) || (password2 == null)) {
4137 password1 = PwdGenerator.getPassword();
4138 password2 = password1;
4139 }
4140
4141 sendEmail = false;
4142 }
4143
4144 if (updateUserInformation) {
4145 autoScreenName = false;
4146
4147 if (PrefsPropsUtil.getBoolean(
4148 companyId,
4149 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4150
4151 autoScreenName = true;
4152 }
4153
4154 validate(
4155 companyId, user.getUserId(), autoPassword, password1, password2,
4156 autoScreenName, screenName, emailAddress, openId, firstName,
4157 middleName, lastName, null);
4158
4159 if (!autoPassword) {
4160 if (Validator.isNull(password1) ||
4161 Validator.isNull(password2)) {
4162 throw new UserPasswordException(
4163 UserPasswordException.PASSWORD_INVALID);
4164 }
4165 }
4166
4167 if (autoScreenName) {
4168 ScreenNameGenerator screenNameGenerator =
4169 ScreenNameGeneratorFactory.getInstance();
4170
4171 try {
4172 screenName = screenNameGenerator.generate(
4173 companyId, user.getUserId(), emailAddress);
4174 }
4175 catch (Exception e) {
4176 throw new SystemException(e);
4177 }
4178 }
4179
4180 FullNameGenerator fullNameGenerator =
4181 FullNameGeneratorFactory.getInstance();
4182
4183 String fullName = fullNameGenerator.getFullName(
4184 firstName, middleName, lastName);
4185
4186 String greeting = LanguageUtil.format(
4187 locale, "welcome-x", " " + fullName, false);
4188
4189 if (Validator.isNotNull(password1)) {
4190 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4191 user.setPasswordUnencrypted(password1);
4192 }
4193
4194 user.setPasswordEncrypted(true);
4195
4196 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4197
4198 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4199 passwordPolicy.isChangeRequired()) {
4200
4201 user.setPasswordReset(true);
4202 }
4203 else {
4204 user.setPasswordReset(false);
4205 }
4206
4207 user.setScreenName(screenName);
4208 user.setFacebookId(facebookId);
4209 user.setOpenId(openId);
4210 user.setLanguageId(locale.toString());
4211 user.setTimeZoneId(defaultUser.getTimeZoneId());
4212 user.setGreeting(greeting);
4213 user.setFirstName(firstName);
4214 user.setMiddleName(middleName);
4215 user.setLastName(lastName);
4216 user.setJobTitle(jobTitle);
4217 user.setExpandoBridgeAttributes(serviceContext);
4218
4219 Date birthday = getBirthday(
4220 birthdayMonth, birthdayDay, birthdayYear);
4221
4222 Contact contact = user.getContact();
4223
4224 contact.setFirstName(firstName);
4225 contact.setMiddleName(middleName);
4226 contact.setLastName(lastName);
4227 contact.setPrefixId(prefixId);
4228 contact.setSuffixId(suffixId);
4229 contact.setMale(male);
4230 contact.setBirthday(birthday);
4231 contact.setJobTitle(jobTitle);
4232
4233 contactPersistence.update(contact, serviceContext);
4234
4235
4236
4237 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4238 User.class);
4239
4240 indexer.reindex(user);
4241 }
4242
4243 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4244
4245 userPersistence.update(user, serviceContext);
4246
4247
4248
4249 long workflowUserId = creatorUserId;
4250
4251 if (workflowUserId == user.getUserId()) {
4252 workflowUserId = defaultUser.getUserId();
4253 }
4254
4255 ServiceContext workflowServiceContext = serviceContext;
4256
4257 if (workflowServiceContext == null) {
4258 workflowServiceContext = new ServiceContext();
4259 }
4260
4261 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4262 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4263 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4264
4265 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4266 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4267 user, workflowServiceContext);
4268
4269 return getUserByEmailAddress(companyId, emailAddress);
4270 }
4271
4272
4282 @Override
4283 public User updateJobTitle(long userId, String jobTitle)
4284 throws PortalException, SystemException {
4285
4286 User user = userPersistence.findByPrimaryKey(userId);
4287
4288 user.setJobTitle(jobTitle);
4289
4290 userPersistence.update(user);
4291
4292 Contact contact = contactPersistence.findByPrimaryKey(
4293 user.getContactId());
4294
4295 contact.setJobTitle(jobTitle);
4296
4297 contactPersistence.update(contact);
4298
4299 return user;
4300 }
4301
4302
4311 @Override
4312 public User updateLastLogin(long userId, String loginIP)
4313 throws PortalException, SystemException {
4314
4315 User user = userPersistence.findByPrimaryKey(userId);
4316
4317 Date lastLoginDate = user.getLoginDate();
4318
4319 if (lastLoginDate == null) {
4320 lastLoginDate = new Date();
4321 }
4322
4323 user.setLoginDate(new Date());
4324 user.setLoginIP(loginIP);
4325 user.setLastLoginDate(lastLoginDate);
4326 user.setLastLoginIP(user.getLoginIP());
4327 user.setFailedLoginAttempts(0);
4328
4329 userPersistence.update(user);
4330
4331 return user;
4332 }
4333
4334
4343 @Override
4344 public User updateLockout(User user, boolean lockout)
4345 throws PortalException, SystemException {
4346
4347 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4348
4349 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4350 return user;
4351 }
4352
4353 Date lockoutDate = null;
4354
4355 if (lockout) {
4356 lockoutDate = new Date();
4357 }
4358
4359 user.setLockout(lockout);
4360 user.setLockoutDate(lockoutDate);
4361
4362 if (!lockout) {
4363 user.setLastFailedLoginDate(lockoutDate);
4364 user.setFailedLoginAttempts(0);
4365 }
4366
4367 userPersistence.update(user);
4368
4369 return user;
4370 }
4371
4372
4383 @Override
4384 public User updateLockoutByEmailAddress(
4385 long companyId, String emailAddress, boolean lockout)
4386 throws PortalException, SystemException {
4387
4388 User user = getUserByEmailAddress(companyId, emailAddress);
4389
4390 return updateLockout(user, lockout);
4391 }
4392
4393
4402 @Override
4403 public User updateLockoutById(long userId, boolean lockout)
4404 throws PortalException, SystemException {
4405
4406 User user = userPersistence.findByPrimaryKey(userId);
4407
4408 return updateLockout(user, lockout);
4409 }
4410
4411
4421 @Override
4422 public User updateLockoutByScreenName(
4423 long companyId, String screenName, boolean lockout)
4424 throws PortalException, SystemException {
4425
4426 User user = getUserByScreenName(companyId, screenName);
4427
4428 return updateLockout(user, lockout);
4429 }
4430
4431
4440 @Override
4441 public User updateModifiedDate(long userId, Date modifiedDate)
4442 throws PortalException, SystemException {
4443
4444 User user = userPersistence.findByPrimaryKey(userId);
4445
4446 user.setModifiedDate(modifiedDate);
4447
4448 userPersistence.update(user);
4449
4450 return user;
4451 }
4452
4453
4462 @Override
4463 public User updateOpenId(long userId, String openId)
4464 throws PortalException, SystemException {
4465
4466 openId = openId.trim();
4467
4468 User user = userPersistence.findByPrimaryKey(userId);
4469
4470 user.setOpenId(openId);
4471
4472 userPersistence.update(user);
4473
4474 return user;
4475 }
4476
4477
4488 @Override
4489 public void updateOrganizations(
4490 long userId, long[] newOrganizationIds,
4491 ServiceContext serviceContext)
4492 throws PortalException, SystemException {
4493
4494 updateOrganizations(
4495 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4496 }
4497
4498
4510 @Override
4511 public User updatePassword(
4512 long userId, String password1, String password2,
4513 boolean passwordReset)
4514 throws PortalException, SystemException {
4515
4516 return updatePassword(
4517 userId, password1, password2, passwordReset, false);
4518 }
4519
4520
4535 @Override
4536 public User updatePassword(
4537 long userId, String password1, String password2,
4538 boolean passwordReset, boolean silentUpdate)
4539 throws PortalException, SystemException {
4540
4541 User user = userPersistence.findByPrimaryKey(userId);
4542
4543 if (!silentUpdate) {
4544 validatePassword(user.getCompanyId(), userId, password1, password2);
4545 }
4546
4547 String oldEncPwd = user.getPassword();
4548
4549 if (!user.isPasswordEncrypted()) {
4550 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4551 }
4552
4553 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4554
4555 if (user.hasCompanyMx()) {
4556 mailService.updatePassword(user.getCompanyId(), userId, password1);
4557 }
4558
4559 user.setPassword(newEncPwd);
4560 user.setPasswordUnencrypted(password1);
4561 user.setPasswordEncrypted(true);
4562 user.setPasswordReset(passwordReset);
4563 user.setPasswordModifiedDate(new Date());
4564 user.setDigest(StringPool.BLANK);
4565 user.setGraceLoginCount(0);
4566
4567 if (!silentUpdate) {
4568 user.setPasswordModified(true);
4569 }
4570
4571 try {
4572 userPersistence.update(user);
4573 }
4574 catch (ModelListenerException mle) {
4575 String msg = GetterUtil.getString(mle.getCause().getMessage());
4576
4577 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4578 String passwordHistory = PrefsPropsUtil.getString(
4579 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4580
4581 if (msg.contains(passwordHistory)) {
4582 throw new UserPasswordException(
4583 UserPasswordException.PASSWORD_ALREADY_USED);
4584 }
4585 }
4586
4587 throw new UserPasswordException(
4588 UserPasswordException.PASSWORD_INVALID);
4589 }
4590
4591 if (!silentUpdate) {
4592 user.setPasswordModified(false);
4593
4594 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4595 }
4596
4597 return user;
4598 }
4599
4600
4614 @Override
4615 public User updatePasswordManually(
4616 long userId, String password, boolean passwordEncrypted,
4617 boolean passwordReset, Date passwordModifiedDate)
4618 throws PortalException, SystemException {
4619
4620
4621
4622 User user = userPersistence.findByPrimaryKey(userId);
4623
4624 user.setPassword(password);
4625 user.setPasswordEncrypted(passwordEncrypted);
4626 user.setPasswordReset(passwordReset);
4627 user.setPasswordModifiedDate(passwordModifiedDate);
4628 user.setDigest(StringPool.BLANK);
4629
4630 userPersistence.update(user);
4631
4632 return user;
4633 }
4634
4635
4646 @Override
4647 public User updatePasswordReset(long userId, boolean passwordReset)
4648 throws PortalException, SystemException {
4649
4650 User user = userPersistence.findByPrimaryKey(userId);
4651
4652 user.setPasswordReset(passwordReset);
4653
4654 userPersistence.update(user);
4655
4656 return user;
4657 }
4658
4659
4669 @Override
4670 public User updatePortrait(long userId, byte[] bytes)
4671 throws PortalException, SystemException {
4672
4673 User user = userPersistence.findByPrimaryKey(userId);
4674
4675 long imageMaxSize = PrefsPropsUtil.getLong(
4676 PropsKeys.USERS_IMAGE_MAX_SIZE);
4677
4678 if ((imageMaxSize > 0) &&
4679 ((bytes == null) || (bytes.length > imageMaxSize))) {
4680
4681 throw new UserPortraitSizeException();
4682 }
4683
4684 long portraitId = user.getPortraitId();
4685
4686 if (portraitId <= 0) {
4687 portraitId = counterLocalService.increment();
4688
4689 user.setPortraitId(portraitId);
4690 }
4691
4692 try {
4693 ImageBag imageBag = ImageToolUtil.read(bytes);
4694
4695 RenderedImage renderedImage = imageBag.getRenderedImage();
4696
4697 if (renderedImage == null) {
4698 throw new UserPortraitTypeException();
4699 }
4700
4701 renderedImage = ImageToolUtil.scale(
4702 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4703 PropsValues.USERS_IMAGE_MAX_WIDTH);
4704
4705 String contentType = imageBag.getType();
4706
4707 imageLocalService.updateImage(
4708 portraitId,
4709 ImageToolUtil.getBytes(renderedImage, contentType));
4710 }
4711 catch (IOException ioe) {
4712 throw new ImageSizeException(ioe);
4713 }
4714
4715 userPersistence.update(user);
4716
4717 return user;
4718 }
4719
4720
4731 @Override
4732 public User updateReminderQuery(long userId, String question, String answer)
4733 throws PortalException, SystemException {
4734
4735 validateReminderQuery(question, answer);
4736
4737 User user = userPersistence.findByPrimaryKey(userId);
4738
4739 user.setReminderQueryQuestion(question);
4740 user.setReminderQueryAnswer(answer);
4741
4742 userPersistence.update(user);
4743
4744 return user;
4745 }
4746
4747
4757 @Override
4758 public User updateScreenName(long userId, String screenName)
4759 throws PortalException, SystemException {
4760
4761
4762
4763 User user = userPersistence.findByPrimaryKey(userId);
4764
4765 screenName = getLogin(screenName);
4766
4767 validateScreenName(user.getCompanyId(), userId, screenName);
4768
4769 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4770 user.setDigest(StringPool.BLANK);
4771 }
4772
4773 user.setScreenName(screenName);
4774
4775 userPersistence.update(user);
4776
4777
4778
4779 Group group = groupLocalService.getUserGroup(
4780 user.getCompanyId(), userId);
4781
4782 group.setFriendlyURL(StringPool.SLASH + screenName);
4783
4784 groupPersistence.update(group);
4785
4786 return user;
4787 }
4788
4789
4801 @Deprecated
4802 @Override
4803 public User updateStatus(long userId, int status)
4804 throws PortalException, SystemException {
4805
4806 return updateStatus(userId, status, new ServiceContext());
4807 }
4808
4809
4821 @Override
4822 public User updateStatus(
4823 long userId, int status, ServiceContext serviceContext)
4824 throws PortalException, SystemException {
4825
4826 User user = userPersistence.findByPrimaryKey(userId);
4827
4828 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4829 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4830
4831 validateCompanyMaxUsers(user.getCompanyId());
4832 }
4833
4834 String passwordUnencrypted = (String)serviceContext.getAttribute(
4835 "passwordUnencrypted");
4836
4837 if (Validator.isNotNull(passwordUnencrypted)) {
4838 user.setPasswordUnencrypted(passwordUnencrypted);
4839 }
4840
4841 user.setStatus(status);
4842
4843 userPersistence.update(user);
4844
4845 reindex(user);
4846
4847 return user;
4848 }
4849
4850
4906 @Override
4907 @SuppressWarnings("deprecation")
4908 public User updateUser(
4909 long userId, String oldPassword, String newPassword1,
4910 String newPassword2, boolean passwordReset,
4911 String reminderQueryQuestion, String reminderQueryAnswer,
4912 String screenName, String emailAddress, long facebookId,
4913 String openId, String languageId, String timeZoneId,
4914 String greeting, String comments, String firstName,
4915 String middleName, String lastName, int prefixId, int suffixId,
4916 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4917 String smsSn, String aimSn, String facebookSn, String icqSn,
4918 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4919 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4920 long[] organizationIds, long[] roleIds,
4921 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4922 ServiceContext serviceContext)
4923 throws PortalException, SystemException {
4924
4925
4926
4927 User user = userPersistence.findByPrimaryKey(userId);
4928 Company company = companyPersistence.findByPrimaryKey(
4929 user.getCompanyId());
4930 String password = oldPassword;
4931 screenName = getLogin(screenName);
4932 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
4933 openId = openId.trim();
4934 String oldFullName = user.getFullName();
4935 aimSn = StringUtil.toLowerCase(aimSn.trim());
4936 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
4937 icqSn = StringUtil.toLowerCase(icqSn.trim());
4938 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
4939 msnSn = StringUtil.toLowerCase(msnSn.trim());
4940 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
4941 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
4942 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
4943 ymSn = StringUtil.toLowerCase(ymSn.trim());
4944 Date now = new Date();
4945
4946 EmailAddressGenerator emailAddressGenerator =
4947 EmailAddressGeneratorFactory.getInstance();
4948
4949 if (emailAddressGenerator.isGenerated(emailAddress)) {
4950 emailAddress = StringPool.BLANK;
4951 }
4952
4953 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4954 Validator.isNull(emailAddress)) {
4955
4956 emailAddress = emailAddressGenerator.generate(
4957 user.getCompanyId(), userId);
4958 }
4959
4960 validate(
4961 userId, screenName, emailAddress, openId, firstName, middleName,
4962 lastName, smsSn);
4963
4964 if (Validator.isNotNull(newPassword1) ||
4965 Validator.isNotNull(newPassword2)) {
4966
4967 user = updatePassword(
4968 userId, newPassword1, newPassword2, passwordReset);
4969
4970 password = newPassword1;
4971
4972 user.setDigest(StringPool.BLANK);
4973 }
4974
4975 user.setModifiedDate(now);
4976
4977 if (user.getContactId() <= 0) {
4978 user.setContactId(counterLocalService.increment());
4979 }
4980
4981 user.setPasswordReset(passwordReset);
4982
4983 if (Validator.isNotNull(reminderQueryQuestion) &&
4984 Validator.isNotNull(reminderQueryAnswer)) {
4985
4986 user.setReminderQueryQuestion(reminderQueryQuestion);
4987 user.setReminderQueryAnswer(reminderQueryAnswer);
4988 }
4989
4990 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4991 user.setScreenName(screenName);
4992
4993 user.setDigest(StringPool.BLANK);
4994 }
4995
4996 boolean sendEmailAddressVerification = false;
4997
4998 if (!company.isStrangersVerify()) {
4999 setEmailAddress(
5000 user, password, firstName, middleName, lastName, emailAddress);
5001 }
5002 else {
5003 sendEmailAddressVerification = true;
5004 }
5005
5006 if (serviceContext != null) {
5007 String uuid = serviceContext.getUuid();
5008
5009 if (Validator.isNotNull(uuid)) {
5010 user.setUuid(uuid);
5011 }
5012 }
5013
5014 user.setFacebookId(facebookId);
5015
5016 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5017
5018 if (ldapServerId != null) {
5019 user.setLdapServerId(ldapServerId);
5020 }
5021
5022 user.setOpenId(openId);
5023 user.setLanguageId(languageId);
5024 user.setTimeZoneId(timeZoneId);
5025 user.setGreeting(greeting);
5026 user.setComments(comments);
5027 user.setFirstName(firstName);
5028 user.setMiddleName(middleName);
5029 user.setLastName(lastName);
5030 user.setJobTitle(jobTitle);
5031 user.setExpandoBridgeAttributes(serviceContext);
5032
5033 userPersistence.update(user, serviceContext);
5034
5035
5036
5037 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5038
5039 long contactId = user.getContactId();
5040
5041 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5042
5043 if (contact == null) {
5044 contact = contactPersistence.create(contactId);
5045
5046 contact.setCompanyId(user.getCompanyId());
5047 contact.setUserName(StringPool.BLANK);
5048 contact.setCreateDate(now);
5049 contact.setClassName(User.class.getName());
5050 contact.setClassPK(user.getUserId());
5051 contact.setAccountId(company.getAccountId());
5052 contact.setParentContactId(
5053 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5054 }
5055
5056 contact.setModifiedDate(now);
5057 contact.setEmailAddress(user.getEmailAddress());
5058 contact.setFirstName(firstName);
5059 contact.setMiddleName(middleName);
5060 contact.setLastName(lastName);
5061 contact.setPrefixId(prefixId);
5062 contact.setSuffixId(suffixId);
5063 contact.setMale(male);
5064 contact.setBirthday(birthday);
5065 contact.setSmsSn(smsSn);
5066 contact.setAimSn(aimSn);
5067 contact.setFacebookSn(facebookSn);
5068 contact.setIcqSn(icqSn);
5069 contact.setJabberSn(jabberSn);
5070 contact.setMsnSn(msnSn);
5071 contact.setMySpaceSn(mySpaceSn);
5072 contact.setSkypeSn(skypeSn);
5073 contact.setTwitterSn(twitterSn);
5074 contact.setYmSn(ymSn);
5075 contact.setJobTitle(jobTitle);
5076
5077 contactPersistence.update(contact, serviceContext);
5078
5079
5080
5081 Group group = groupLocalService.getUserGroup(
5082 user.getCompanyId(), userId);
5083
5084 group.setFriendlyURL(StringPool.SLASH + screenName);
5085
5086 groupPersistence.update(group);
5087
5088
5089
5090
5091
5092
5093
5094 List<UserGroupRole> previousUserGroupRoles =
5095 userGroupRolePersistence.findByUserId(userId);
5096
5097 updateGroups(userId, groupIds, serviceContext, false);
5098 updateOrganizations(userId, organizationIds, false);
5099
5100
5101
5102 if (roleIds != null) {
5103 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5104
5105 userPersistence.setRoles(userId, roleIds);
5106 }
5107
5108
5109
5110 updateUserGroupRoles(
5111 user, groupIds, organizationIds, userGroupRoles,
5112 previousUserGroupRoles);
5113
5114
5115
5116 if (userGroupIds != null) {
5117 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5118 userGroupLocalService.copyUserGroupLayouts(
5119 userGroupIds, userId);
5120 }
5121
5122 userPersistence.setUserGroups(userId, userGroupIds);
5123 }
5124
5125
5126
5127 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5128
5129
5130
5131 if (serviceContext != null) {
5132 updateAsset(
5133 userId, user, serviceContext.getAssetCategoryIds(),
5134 serviceContext.getAssetTagNames());
5135 }
5136
5137
5138
5139 if (GetterUtil.getBoolean(
5140 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5141 !oldFullName.equals(user.getFullName())) {
5142
5143 mbMessageLocalService.updateUserName(userId, user.getFullName());
5144 }
5145
5146
5147
5148 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5149 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5150 User.class);
5151
5152 indexer.reindex(user);
5153 }
5154
5155
5156
5157 if ((serviceContext != null) && sendEmailAddressVerification) {
5158 sendEmailAddressVerification(user, emailAddress, serviceContext);
5159 }
5160
5161
5162
5163 PermissionCacheUtil.clearCache();
5164
5165 return user;
5166 }
5167
5168
5177 @Override
5178 public void verifyEmailAddress(String ticketKey)
5179 throws PortalException, SystemException {
5180
5181 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5182
5183 if (ticket.isExpired() ||
5184 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5185
5186 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5187 }
5188
5189 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5190
5191 String emailAddress = ticket.getExtraInfo();
5192
5193 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5194
5195 if (!emailAddress.equals(user.getEmailAddress())) {
5196 if (userPersistence.fetchByC_EA(
5197 user.getCompanyId(), emailAddress) != null) {
5198
5199 throw new DuplicateUserEmailAddressException(
5200 "{userId=" + user.getUserId() + "}");
5201 }
5202
5203 setEmailAddress(
5204 user, StringPool.BLANK, user.getFirstName(),
5205 user.getMiddleName(), user.getLastName(), emailAddress);
5206
5207 Contact contact = user.getContact();
5208
5209 contact.setEmailAddress(user.getEmailAddress());
5210
5211 contactPersistence.update(contact);
5212 }
5213
5214 user.setEmailAddressVerified(true);
5215
5216 userPersistence.update(user);
5217
5218 ticketLocalService.deleteTicket(ticket);
5219 }
5220
5221 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5222 throws PortalException, SystemException {
5223
5224 List<Role> defaultSiteRoles = new ArrayList<Role>();
5225
5226 Group group = groupLocalService.getGroup(groupId);
5227
5228 UnicodeProperties typeSettingsProperties =
5229 group.getTypeSettingsProperties();
5230
5231 long[] defaultSiteRoleIds = StringUtil.split(
5232 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5233
5234 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5235 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5236 defaultSiteRoleId);
5237
5238 if (defaultSiteRole == null) {
5239 if (_log.isWarnEnabled()) {
5240 _log.warn("Unable to find role " + defaultSiteRoleId);
5241 }
5242
5243 continue;
5244 }
5245
5246 defaultSiteRoles.add(defaultSiteRole);
5247 }
5248
5249 List<Team> defaultTeams = new ArrayList<Team>();
5250
5251 long[] defaultTeamIds = StringUtil.split(
5252 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5253
5254 for (long defaultTeamId : defaultTeamIds) {
5255 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5256
5257 if (defaultTeam == null) {
5258 if (_log.isWarnEnabled()) {
5259 _log.warn("Unable to find team " + defaultTeamId);
5260 }
5261
5262 continue;
5263 }
5264
5265 defaultTeams.add(defaultTeam);
5266 }
5267
5268 for (long userId : userIds) {
5269 Set<Long> userRoleIdsSet = new HashSet<Long>();
5270
5271 for (Role role : defaultSiteRoles) {
5272 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5273 userRoleIdsSet.add(role.getRoleId());
5274 }
5275 }
5276
5277 long[] userRoleIds = ArrayUtil.toArray(
5278 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5279
5280 userGroupRoleLocalService.addUserGroupRoles(
5281 userId, groupId, userRoleIds);
5282
5283 Set<Long> userTeamIdsSet = new HashSet<Long>();
5284
5285 for (Team team : defaultTeams) {
5286 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5287 userTeamIdsSet.add(team.getTeamId());
5288 }
5289 }
5290
5291 long[] userTeamIds = ArrayUtil.toArray(
5292 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5293
5294 userPersistence.addTeams(userId, userTeamIds);
5295 }
5296 }
5297
5298
5344 protected int authenticate(
5345 long companyId, String login, String password, String authType,
5346 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5347 Map<String, Object> resultsMap)
5348 throws PortalException, SystemException {
5349
5350 if (PropsValues.AUTH_LOGIN_DISABLED) {
5351 return Authenticator.FAILURE;
5352 }
5353
5354 login = StringUtil.toLowerCase(login.trim());
5355
5356 long userId = GetterUtil.getLong(login);
5357
5358
5359
5360 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5361 if (Validator.isNull(login)) {
5362 throw new UserEmailAddressException();
5363 }
5364 }
5365 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5366 if (Validator.isNull(login)) {
5367 throw new UserScreenNameException();
5368 }
5369 }
5370 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5371 if (Validator.isNull(login)) {
5372 throw new UserIdException();
5373 }
5374 }
5375
5376 if (Validator.isNull(password)) {
5377 throw new UserPasswordException(
5378 UserPasswordException.PASSWORD_INVALID);
5379 }
5380
5381 int authResult = Authenticator.FAILURE;
5382
5383
5384
5385 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5386 authResult = AuthPipeline.authenticateByEmailAddress(
5387 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5388 headerMap, parameterMap);
5389 }
5390 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5391 authResult = AuthPipeline.authenticateByScreenName(
5392 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5393 headerMap, parameterMap);
5394 }
5395 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5396 authResult = AuthPipeline.authenticateByUserId(
5397 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5398 headerMap, parameterMap);
5399 }
5400
5401
5402
5403 User user = null;
5404
5405 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5406 user = fetchUserByEmailAddress(companyId, login);
5407 }
5408 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5409 user = fetchUserByScreenName(companyId, login);
5410 }
5411 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5412 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5413 }
5414
5415 if (user == null) {
5416 return Authenticator.DNE;
5417 }
5418
5419 if (user.isDefaultUser()) {
5420 if (_log.isInfoEnabled()) {
5421 _log.info("Authentication is disabled for the default user");
5422 }
5423
5424 return Authenticator.DNE;
5425 }
5426 else if (!user.isActive()) {
5427 if (_log.isInfoEnabled()) {
5428 _log.info(
5429 "Authentication is disabled for inactive user " +
5430 user.getUserId());
5431 }
5432
5433 return Authenticator.FAILURE;
5434 }
5435
5436 if (!user.isPasswordEncrypted()) {
5437 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5438 user.setPasswordEncrypted(true);
5439
5440 userPersistence.update(user);
5441 }
5442
5443
5444
5445
5446 checkLockout(user);
5447
5448 checkPasswordExpired(user);
5449
5450
5451
5452 boolean skipLiferayCheck = false;
5453
5454 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5455 authResult = Authenticator.SUCCESS;
5456
5457 skipLiferayCheck = true;
5458 }
5459 else if ((authResult == Authenticator.SUCCESS) &&
5460 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5461
5462 boolean authenticated = PwdAuthenticator.authenticate(
5463 login, password, user.getPassword());
5464
5465 if (authenticated) {
5466 authResult = Authenticator.SUCCESS;
5467 }
5468 else {
5469 authResult = Authenticator.FAILURE;
5470 }
5471 }
5472
5473
5474
5475 if (authResult == Authenticator.SUCCESS) {
5476 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5477 authResult = AuthPipeline.authenticateByEmailAddress(
5478 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5479 headerMap, parameterMap);
5480 }
5481 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5482 authResult = AuthPipeline.authenticateByScreenName(
5483 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5484 headerMap, parameterMap);
5485 }
5486 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5487 authResult = AuthPipeline.authenticateByUserId(
5488 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5489 headerMap, parameterMap);
5490 }
5491 }
5492
5493 if (authResult == Authenticator.SUCCESS) {
5494 if (resultsMap != null) {
5495 resultsMap.put("userId", user.getUserId());
5496 }
5497
5498
5499
5500 if (skipLiferayCheck ||
5501 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5502 Validator.isNull(user.getDigest())) {
5503
5504 String digest = user.getDigest(password);
5505
5506 user.setDigest(digest);
5507
5508 userPersistence.update(user);
5509 }
5510 }
5511
5512
5513
5514 if (authResult == Authenticator.FAILURE) {
5515 try {
5516 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5517 AuthPipeline.onFailureByEmailAddress(
5518 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5519 parameterMap);
5520 }
5521 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5522 AuthPipeline.onFailureByScreenName(
5523 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5524 parameterMap);
5525 }
5526 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5527 AuthPipeline.onFailureByUserId(
5528 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5529 parameterMap);
5530 }
5531
5532 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5533
5534 if (user == null) {
5535 return Authenticator.DNE;
5536 }
5537
5538
5539
5540 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5541 user.getCompanyId())) {
5542
5543 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5544
5545 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5546
5547 int failedLoginAttempts = user.getFailedLoginAttempts();
5548 int maxFailures = passwordPolicy.getMaxFailure();
5549
5550 if ((failedLoginAttempts >= maxFailures) &&
5551 (maxFailures != 0)) {
5552
5553 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5554 AuthPipeline.onMaxFailuresByEmailAddress(
5555 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5556 headerMap, parameterMap);
5557 }
5558 else if (authType.equals(
5559 CompanyConstants.AUTH_TYPE_SN)) {
5560
5561 AuthPipeline.onMaxFailuresByScreenName(
5562 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5563 headerMap, parameterMap);
5564 }
5565 else if (authType.equals(
5566 CompanyConstants.AUTH_TYPE_ID)) {
5567
5568 AuthPipeline.onMaxFailuresByUserId(
5569 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5570 headerMap, parameterMap);
5571 }
5572 }
5573 }
5574 }
5575 catch (Exception e) {
5576 _log.error(e, e);
5577 }
5578 }
5579
5580
5581
5582 return authResult;
5583 }
5584
5585 protected Date getBirthday(
5586 int birthdayMonth, int birthdayDay, int birthdayYear)
5587 throws PortalException {
5588
5589 Date birthday = PortalUtil.getDate(
5590 birthdayMonth, birthdayDay, birthdayYear,
5591 ContactBirthdayException.class);
5592
5593 Date now = new Date();
5594
5595 if (birthday.after(now)) {
5596 throw new ContactBirthdayException();
5597 }
5598
5599 return birthday;
5600 }
5601
5602 protected String getLogin(String login) {
5603 return StringUtil.lowerCase(StringUtil.trim(login));
5604 }
5605
5606 protected long[] getUserIds(List<User> users) {
5607 long[] userIds = new long[users.size()];
5608
5609 for (int i = 0; i < users.size(); i++) {
5610 User user = users.get(i);
5611
5612 userIds[i] = user.getUserId();
5613 }
5614
5615 return userIds;
5616 }
5617
5618 protected void reindex(final User user) {
5619 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5620 User.class);
5621
5622 Callable<Void> callable = new ShardCallable<Void>(
5623 user.getCompanyId()) {
5624
5625 @Override
5626 protected Void doCall() throws Exception {
5627 indexer.reindex(user);
5628
5629 return null;
5630 }
5631
5632 };
5633
5634 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5635 }
5636
5637 protected Hits search(
5638 long companyId, String firstName, String middleName,
5639 String lastName, String fullName, String screenName,
5640 String emailAddress, String street, String city, String zip,
5641 String region, String country, int status,
5642 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5643 int end, Sort sort)
5644 throws SystemException {
5645
5646 try {
5647 SearchContext searchContext = new SearchContext();
5648
5649 searchContext.setAndSearch(andSearch);
5650
5651 Map<String, Serializable> attributes =
5652 new HashMap<String, Serializable>();
5653
5654 attributes.put("city", city);
5655 attributes.put("country", country);
5656 attributes.put("emailAddress", emailAddress);
5657 attributes.put("firstName", firstName);
5658 attributes.put("fullName", fullName);
5659 attributes.put("lastName", lastName);
5660 attributes.put("middleName", middleName);
5661 attributes.put("params", params);
5662 attributes.put("region", region);
5663 attributes.put("screenName", screenName);
5664 attributes.put("street", street);
5665 attributes.put("status", status);
5666 attributes.put("zip", zip);
5667
5668 searchContext.setAttributes(attributes);
5669
5670 searchContext.setCompanyId(companyId);
5671 searchContext.setEnd(end);
5672
5673 if (params != null) {
5674 String keywords = (String)params.remove("keywords");
5675
5676 if (Validator.isNotNull(keywords)) {
5677 searchContext.setKeywords(keywords);
5678 }
5679 }
5680
5681 QueryConfig queryConfig = new QueryConfig();
5682
5683 queryConfig.setHighlightEnabled(false);
5684 queryConfig.setScoreEnabled(false);
5685
5686 searchContext.setQueryConfig(queryConfig);
5687
5688 if (sort != null) {
5689 searchContext.setSorts(sort);
5690 }
5691
5692 searchContext.setStart(start);
5693
5694 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5695 User.class);
5696
5697 return indexer.search(searchContext);
5698 }
5699 catch (Exception e) {
5700 throw new SystemException(e);
5701 }
5702 }
5703
5704 protected void sendEmail(
5705 User user, String password, ServiceContext serviceContext)
5706 throws SystemException {
5707
5708 if (!PrefsPropsUtil.getBoolean(
5709 user.getCompanyId(),
5710 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5711
5712 return;
5713 }
5714
5715 String fromName = PrefsPropsUtil.getString(
5716 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5717 String fromAddress = PrefsPropsUtil.getString(
5718 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5719
5720 String toName = user.getFullName();
5721 String toAddress = user.getEmailAddress();
5722
5723 String subject = PrefsPropsUtil.getContent(
5724 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5725
5726 String body = null;
5727
5728 if (Validator.isNotNull(password)) {
5729 body = PrefsPropsUtil.getContent(
5730 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5731 }
5732 else {
5733 body = PrefsPropsUtil.getContent(
5734 user.getCompanyId(),
5735 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5736 }
5737
5738 SubscriptionSender subscriptionSender = new SubscriptionSender();
5739
5740 subscriptionSender.setBody(body);
5741 subscriptionSender.setCompanyId(user.getCompanyId());
5742 subscriptionSender.setContextAttributes(
5743 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5744 "[$USER_SCREENNAME$]", user.getScreenName());
5745 subscriptionSender.setFrom(fromAddress, fromName);
5746 subscriptionSender.setHtmlFormat(true);
5747 subscriptionSender.setMailId(
5748 "user", user.getUserId(), System.currentTimeMillis(),
5749 PwdGenerator.getPassword());
5750 subscriptionSender.setServiceContext(serviceContext);
5751 subscriptionSender.setSubject(subject);
5752 subscriptionSender.setUserId(user.getUserId());
5753
5754 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5755
5756 subscriptionSender.flushNotificationsAsync();
5757 }
5758
5759 protected void setEmailAddress(
5760 User user, String password, String firstName, String middleName,
5761 String lastName, String emailAddress)
5762 throws PortalException, SystemException {
5763
5764 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
5765 return;
5766 }
5767
5768 long userId = user.getUserId();
5769
5770
5771
5772 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5773 Validator.isNotNull(password)) {
5774
5775 mailService.addUser(
5776 user.getCompanyId(), userId, password, firstName, middleName,
5777 lastName, emailAddress);
5778 }
5779
5780
5781
5782 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5783 mailService.updateEmailAddress(
5784 user.getCompanyId(), userId, emailAddress);
5785 }
5786
5787
5788
5789 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5790 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5791 }
5792
5793 user.setEmailAddress(emailAddress);
5794 user.setDigest(StringPool.BLANK);
5795 }
5796
5797 protected void updateGroups(
5798 long userId, long[] newGroupIds, ServiceContext serviceContext,
5799 boolean indexingEnabled)
5800 throws PortalException, SystemException {
5801
5802 if (newGroupIds == null) {
5803 return;
5804 }
5805
5806 List<Group> oldGroups = userPersistence.getGroups(userId);
5807
5808 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5809
5810 for (Group oldGroup : oldGroups) {
5811 long oldGroupId = oldGroup.getGroupId();
5812
5813 oldGroupIds.add(oldGroupId);
5814
5815 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5816 unsetGroupUsers(
5817 oldGroupId, new long[] {userId}, serviceContext);
5818 }
5819 }
5820
5821 for (long newGroupId : newGroupIds) {
5822 if (!oldGroupIds.contains(newGroupId)) {
5823 addGroupUsers(newGroupId, new long[] {userId});
5824 }
5825 }
5826
5827 if (indexingEnabled) {
5828 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5829 User.class);
5830
5831 indexer.reindex(new long[] {userId});
5832 }
5833
5834 PermissionCacheUtil.clearCache();
5835 }
5836
5837 protected void updateOrganizations(
5838 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5839 throws PortalException, SystemException {
5840
5841 if (newOrganizationIds == null) {
5842 return;
5843 }
5844
5845 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5846 userId);
5847
5848 Set<Long> oldOrganizationIds = new HashSet<Long>(
5849 oldOrganizations.size());
5850
5851 for (Organization oldOrganization : oldOrganizations) {
5852 long oldOrganizationId = oldOrganization.getOrganizationId();
5853
5854 oldOrganizationIds.add(oldOrganizationId);
5855
5856 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5857 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5858 }
5859 }
5860
5861 for (long newOrganizationId : newOrganizationIds) {
5862 if (!oldOrganizationIds.contains(newOrganizationId)) {
5863 addOrganizationUsers(newOrganizationId, new long[] {userId});
5864 }
5865 }
5866
5867 if (indexingEnabled) {
5868 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5869 User.class);
5870
5871 indexer.reindex(new long[] {userId});
5872 }
5873
5874 PermissionCacheUtil.clearCache();
5875 }
5876
5877 protected void updateUserGroupRoles(
5878 User user, long[] groupIds, long[] organizationIds,
5879 List<UserGroupRole> userGroupRoles,
5880 List<UserGroupRole> previousUserGroupRoles)
5881 throws PortalException, SystemException {
5882
5883 if (userGroupRoles == null) {
5884 return;
5885 }
5886
5887 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
5888
5889 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5890 if (userGroupRoles.contains(userGroupRole)) {
5891 userGroupRoles.remove(userGroupRole);
5892 }
5893 else {
5894 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5895 }
5896 }
5897
5898 if (userGroupRoles.isEmpty()) {
5899 return;
5900 }
5901
5902 long[] validGroupIds = null;
5903
5904 if (groupIds != null) {
5905 validGroupIds = ArrayUtil.clone(groupIds);
5906 }
5907 else {
5908 validGroupIds = user.getGroupIds();
5909 }
5910
5911 if (organizationIds == null) {
5912 organizationIds = user.getOrganizationIds();
5913 }
5914
5915 long[] organizationGroupIds = new long[organizationIds.length];
5916
5917 for (int i = 0; i < organizationIds.length; i++) {
5918 long organizationId = organizationIds[i];
5919
5920 Organization organization =
5921 organizationPersistence.findByPrimaryKey(organizationId);
5922
5923 organizationGroupIds[i] = organization.getGroupId();
5924 }
5925
5926 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5927
5928 Arrays.sort(validGroupIds);
5929
5930 for (UserGroupRole userGroupRole : userGroupRoles) {
5931 if (Arrays.binarySearch(
5932 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5933
5934 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5935 }
5936 }
5937 }
5938
5939 protected void validate(
5940 long companyId, long userId, boolean autoPassword, String password1,
5941 String password2, boolean autoScreenName, String screenName,
5942 String emailAddress, String openId, String firstName,
5943 String middleName, String lastName, long[] organizationIds)
5944 throws PortalException, SystemException {
5945
5946 validateCompanyMaxUsers(companyId);
5947
5948 if (!autoScreenName) {
5949 validateScreenName(companyId, userId, screenName);
5950 }
5951
5952 if (!autoPassword) {
5953 PasswordPolicy passwordPolicy =
5954 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5955
5956 PwdToolkitUtil.validate(
5957 companyId, 0, password1, password2, passwordPolicy);
5958 }
5959
5960 validateEmailAddress(companyId, emailAddress);
5961
5962 if (Validator.isNotNull(emailAddress)) {
5963 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5964
5965 if ((user != null) && (user.getUserId() != userId)) {
5966 throw new DuplicateUserEmailAddressException(
5967 "{userId=" + userId + "}");
5968 }
5969 }
5970
5971 validateOpenId(companyId, userId, openId);
5972
5973 validateFullName(companyId, firstName, middleName, lastName);
5974
5975 if (organizationIds != null) {
5976 for (long organizationId : organizationIds) {
5977 Organization organization =
5978 organizationPersistence.fetchByPrimaryKey(organizationId);
5979
5980 if (organization == null) {
5981 throw new NoSuchOrganizationException(
5982 "{organizationId=" + organizationId + "}");
5983 }
5984 }
5985 }
5986 }
5987
5988 protected void validate(
5989 long userId, String screenName, String emailAddress, String openId,
5990 String firstName, String middleName, String lastName, String smsSn)
5991 throws PortalException, SystemException {
5992
5993 User user = userPersistence.findByPrimaryKey(userId);
5994
5995 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5996 validateScreenName(user.getCompanyId(), userId, screenName);
5997 }
5998
5999 validateEmailAddress(user.getCompanyId(), emailAddress);
6000
6001 validateOpenId(user.getCompanyId(), userId, openId);
6002
6003 if (!user.isDefaultUser()) {
6004 if (Validator.isNotNull(emailAddress) &&
6005 !StringUtil.equalsIgnoreCase(
6006 user.getEmailAddress(), emailAddress)) {
6007
6008 if (userPersistence.fetchByC_EA(
6009 user.getCompanyId(), emailAddress) != null) {
6010
6011 throw new DuplicateUserEmailAddressException(
6012 "{userId=" + userId + "}");
6013 }
6014 }
6015
6016 validateFullName(
6017 user.getCompanyId(), firstName, middleName, lastName);
6018 }
6019
6020 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6021 throw new UserSmsException();
6022 }
6023 }
6024
6025 protected void validateCompanyMaxUsers(long companyId)
6026 throws PortalException, SystemException {
6027
6028 Company company = companyPersistence.findByPrimaryKey(companyId);
6029
6030 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6031 return;
6032 }
6033
6034 int userCount = searchCount(
6035 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6036
6037 if (userCount >= company.getMaxUsers()) {
6038 throw new CompanyMaxUsersException();
6039 }
6040 }
6041
6042 protected void validateEmailAddress(long companyId, String emailAddress)
6043 throws PortalException, SystemException {
6044
6045 if (Validator.isNull(emailAddress) &&
6046 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6047
6048 return;
6049 }
6050
6051 EmailAddressValidator emailAddressValidator =
6052 EmailAddressValidatorFactory.getInstance();
6053
6054 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6055 throw new UserEmailAddressException();
6056 }
6057
6058 String pop3User = PrefsPropsUtil.getString(
6059 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6060 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6061
6062 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6063 throw new ReservedUserEmailAddressException();
6064 }
6065
6066 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6067 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6068 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6069
6070 for (String reservedEmailAddress : reservedEmailAddresses) {
6071 if (StringUtil.equalsIgnoreCase(
6072 emailAddress, reservedEmailAddress)) {
6073
6074 throw new ReservedUserEmailAddressException();
6075 }
6076 }
6077 }
6078
6079 protected void validateEmailAddress(
6080 User user, String emailAddress1, String emailAddress2)
6081 throws PortalException, SystemException {
6082
6083 if (!emailAddress1.equals(emailAddress2)) {
6084 throw new UserEmailAddressException();
6085 }
6086
6087 validateEmailAddress(user.getCompanyId(), emailAddress1);
6088 validateEmailAddress(user.getCompanyId(), emailAddress2);
6089
6090 if (!StringUtil.equalsIgnoreCase(
6091 emailAddress1, user.getEmailAddress())) {
6092
6093 if (userPersistence.fetchByC_EA(
6094 user.getCompanyId(), emailAddress1) != null) {
6095
6096 throw new DuplicateUserEmailAddressException(
6097 "{userId=" + user.getUserId() + "}");
6098 }
6099 }
6100 }
6101
6102 protected void validateFullName(
6103 long companyId, String firstName, String middleName,
6104 String lastName)
6105 throws PortalException, SystemException {
6106
6107 if (Validator.isNull(firstName)) {
6108 throw new ContactFirstNameException();
6109 }
6110 else if (Validator.isNull(lastName) &&
6111 PrefsPropsUtil.getBoolean(
6112 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6113 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6114
6115 throw new ContactLastNameException();
6116 }
6117
6118 FullNameValidator fullNameValidator =
6119 FullNameValidatorFactory.getInstance();
6120
6121 if (!fullNameValidator.validate(
6122 companyId, firstName, middleName, lastName)) {
6123
6124 throw new ContactFullNameException();
6125 }
6126 }
6127
6128 protected void validateOpenId(long companyId, long userId, String openId)
6129 throws PortalException, SystemException {
6130
6131 if (Validator.isNull(openId)) {
6132 return;
6133 }
6134
6135 User user = userPersistence.fetchByC_O(companyId, openId);
6136
6137 if ((user != null) && (user.getUserId() != userId)) {
6138 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6139 }
6140 }
6141
6142 protected void validatePassword(
6143 long companyId, long userId, String password1, String password2)
6144 throws PortalException, SystemException {
6145
6146 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6147 throw new UserPasswordException(
6148 UserPasswordException.PASSWORD_INVALID);
6149 }
6150
6151 if (!password1.equals(password2)) {
6152 throw new UserPasswordException(
6153 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6154 }
6155
6156 PasswordPolicy passwordPolicy =
6157 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6158
6159 PwdToolkitUtil.validate(
6160 companyId, userId, password1, password2, passwordPolicy);
6161 }
6162
6163 protected void validateReminderQuery(String question, String answer)
6164 throws PortalException {
6165
6166 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6167 return;
6168 }
6169
6170 if (Validator.isNull(question)) {
6171 throw new UserReminderQueryException("Question is null");
6172 }
6173
6174 if (Validator.isNull(answer)) {
6175 throw new UserReminderQueryException("Answer is null");
6176 }
6177 }
6178
6179 protected void validateScreenName(
6180 long companyId, long userId, String screenName)
6181 throws PortalException, SystemException {
6182
6183 if (Validator.isNull(screenName)) {
6184 throw new UserScreenNameException();
6185 }
6186
6187 ScreenNameValidator screenNameValidator =
6188 ScreenNameValidatorFactory.getInstance();
6189
6190 if (!screenNameValidator.validate(companyId, screenName)) {
6191 throw new UserScreenNameException();
6192 }
6193
6194 if (Validator.isNumber(screenName)) {
6195 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6196 throw new UserScreenNameException();
6197 }
6198
6199 if (!screenName.equals(String.valueOf(userId))) {
6200 Group group = groupPersistence.fetchByPrimaryKey(
6201 GetterUtil.getLong(screenName));
6202
6203 if (group != null) {
6204 throw new UserScreenNameException();
6205 }
6206 }
6207 }
6208
6209 for (char c : screenName.toCharArray()) {
6210 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6211 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6212 (c != CharPool.UNDERLINE)) {
6213
6214 throw new UserScreenNameException();
6215 }
6216 }
6217
6218 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6219
6220 for (String anonymousName : anonymousNames) {
6221 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6222 throw new UserScreenNameException();
6223 }
6224 }
6225
6226 User user = userPersistence.fetchByC_SN(companyId, screenName);
6227
6228 if ((user != null) && (user.getUserId() != userId)) {
6229 throw new DuplicateUserScreenNameException(
6230 "{userId=" + userId + "}");
6231 }
6232
6233 String friendlyURL = StringPool.SLASH + screenName;
6234
6235 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6236
6237 if ((group != null) && (group.getClassPK() != userId)) {
6238 throw new GroupFriendlyURLException(
6239 GroupFriendlyURLException.DUPLICATE);
6240 }
6241
6242 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6243
6244 if (exceptionType != -1) {
6245 throw new UserScreenNameException(
6246 new GroupFriendlyURLException(exceptionType));
6247 }
6248
6249 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6250 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6251 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6252
6253 for (String reservedScreenName : reservedScreenNames) {
6254 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6255 throw new ReservedUserScreenNameException();
6256 }
6257 }
6258 }
6259
6260 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6261
6262 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6263
6264 }