1
22
23 package com.liferay.portal.service.impl;
24
25 import com.liferay.portal.ContactBirthdayException;
26 import com.liferay.portal.ContactFirstNameException;
27 import com.liferay.portal.ContactLastNameException;
28 import com.liferay.portal.DuplicateUserEmailAddressException;
29 import com.liferay.portal.DuplicateUserScreenNameException;
30 import com.liferay.portal.GroupFriendlyURLException;
31 import com.liferay.portal.ModelListenerException;
32 import com.liferay.portal.NoSuchContactException;
33 import com.liferay.portal.NoSuchGroupException;
34 import com.liferay.portal.NoSuchRoleException;
35 import com.liferay.portal.NoSuchUserException;
36 import com.liferay.portal.NoSuchUserGroupException;
37 import com.liferay.portal.PasswordExpiredException;
38 import com.liferay.portal.PortalException;
39 import com.liferay.portal.RequiredUserException;
40 import com.liferay.portal.ReservedUserEmailAddressException;
41 import com.liferay.portal.ReservedUserScreenNameException;
42 import com.liferay.portal.SystemException;
43 import com.liferay.portal.UserEmailAddressException;
44 import com.liferay.portal.UserIdException;
45 import com.liferay.portal.UserLockoutException;
46 import com.liferay.portal.UserPasswordException;
47 import com.liferay.portal.UserPortraitException;
48 import com.liferay.portal.UserScreenNameException;
49 import com.liferay.portal.UserSmsException;
50 import com.liferay.portal.kernel.annotation.Propagation;
51 import com.liferay.portal.kernel.annotation.Transactional;
52 import com.liferay.portal.kernel.language.LanguageUtil;
53 import com.liferay.portal.kernel.log.Log;
54 import com.liferay.portal.kernel.log.LogFactoryUtil;
55 import com.liferay.portal.kernel.mail.MailMessage;
56 import com.liferay.portal.kernel.util.ArrayUtil;
57 import com.liferay.portal.kernel.util.Base64;
58 import com.liferay.portal.kernel.util.CharPool;
59 import com.liferay.portal.kernel.util.GetterUtil;
60 import com.liferay.portal.kernel.util.HtmlUtil;
61 import com.liferay.portal.kernel.util.InstancePool;
62 import com.liferay.portal.kernel.util.KeyValuePair;
63 import com.liferay.portal.kernel.util.OrderByComparator;
64 import com.liferay.portal.kernel.util.StringPool;
65 import com.liferay.portal.kernel.util.StringUtil;
66 import com.liferay.portal.kernel.util.Validator;
67 import com.liferay.portal.lar.PortletDataHandlerKeys;
68 import com.liferay.portal.lar.UserIdStrategy;
69 import com.liferay.portal.model.Company;
70 import com.liferay.portal.model.CompanyConstants;
71 import com.liferay.portal.model.Contact;
72 import com.liferay.portal.model.ContactConstants;
73 import com.liferay.portal.model.Group;
74 import com.liferay.portal.model.Organization;
75 import com.liferay.portal.model.PasswordPolicy;
76 import com.liferay.portal.model.ResourceConstants;
77 import com.liferay.portal.model.Role;
78 import com.liferay.portal.model.RoleConstants;
79 import com.liferay.portal.model.User;
80 import com.liferay.portal.model.UserGroup;
81 import com.liferay.portal.model.impl.LayoutImpl;
82 import com.liferay.portal.security.auth.AuthPipeline;
83 import com.liferay.portal.security.auth.Authenticator;
84 import com.liferay.portal.security.auth.PrincipalException;
85 import com.liferay.portal.security.auth.ScreenNameGenerator;
86 import com.liferay.portal.security.auth.ScreenNameValidator;
87 import com.liferay.portal.security.ldap.PortalLDAPUtil;
88 import com.liferay.portal.security.permission.PermissionCacheUtil;
89 import com.liferay.portal.security.pwd.PwdEncryptor;
90 import com.liferay.portal.security.pwd.PwdToolkitUtil;
91 import com.liferay.portal.service.base.PrincipalBean;
92 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
93 import com.liferay.portal.util.PortalUtil;
94 import com.liferay.portal.util.PrefsPropsUtil;
95 import com.liferay.portal.util.PropsKeys;
96 import com.liferay.portal.util.PropsUtil;
97 import com.liferay.portal.util.PropsValues;
98 import com.liferay.util.Encryptor;
99 import com.liferay.util.EncryptorException;
100
101 import java.io.ByteArrayInputStream;
102 import java.io.IOException;
103 import java.io.UnsupportedEncodingException;
104
105 import java.security.MessageDigest;
106 import java.security.NoSuchAlgorithmException;
107
108 import java.util.ArrayList;
109 import java.util.Date;
110 import java.util.HashSet;
111 import java.util.LinkedHashMap;
112 import java.util.List;
113 import java.util.Locale;
114 import java.util.Map;
115 import java.util.Set;
116 import java.util.concurrent.ConcurrentHashMap;
117
118 import javax.mail.internet.InternetAddress;
119
120
129 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
130
131 public void addGroupUsers(long groupId, long[] userIds)
132 throws PortalException, SystemException {
133
134 groupPersistence.addUsers(groupId, userIds);
135
136 Group group = groupPersistence.findByPrimaryKey(groupId);
137
138 Role role = rolePersistence.findByC_N(
139 group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
140
141 for (int i = 0; i < userIds.length; i++) {
142 long userId = userIds[i];
143
144 userGroupRoleLocalService.addUserGroupRoles(
145 userId, groupId, new long[] {role.getRoleId()});
146 }
147
148 PermissionCacheUtil.clearCache();
149 }
150
151 public void addOrganizationUsers(long organizationId, long[] userIds)
152 throws PortalException, SystemException {
153
154 organizationPersistence.addUsers(organizationId, userIds);
155
156 Organization organization = organizationPersistence.findByPrimaryKey(
157 organizationId);
158
159 Group group = organization.getGroup();
160
161 long groupId = group.getGroupId();
162
163 Role role = rolePersistence.findByC_N(
164 group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
165
166 for (int i = 0; i < userIds.length; i++) {
167 long userId = userIds[i];
168
169 userGroupRoleLocalService.addUserGroupRoles(
170 userId, groupId, new long[] {role.getRoleId()});
171 }
172
173 PermissionCacheUtil.clearCache();
174 }
175
176 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
177 throws SystemException {
178
179 passwordPolicyRelLocalService.addPasswordPolicyRels(
180 passwordPolicyId, User.class.getName(), userIds);
181 }
182
183 public void addRoleUsers(long roleId, long[] userIds)
184 throws SystemException {
185
186 rolePersistence.addUsers(roleId, userIds);
187
188 PermissionCacheUtil.clearCache();
189 }
190
191 public void addUserGroupUsers(long userGroupId, long[] userIds)
192 throws PortalException, SystemException {
193
194 copyUserGroupLayouts(userGroupId, userIds);
195
196 userGroupPersistence.addUsers(userGroupId, userIds);
197
198 PermissionCacheUtil.clearCache();
199 }
200
201 public User addUser(
202 long creatorUserId, long companyId, boolean autoPassword,
203 String password1, String password2, boolean autoScreenName,
204 String screenName, String emailAddress, Locale locale,
205 String firstName, String middleName, String lastName, int prefixId,
206 int suffixId, boolean male, int birthdayMonth, int birthdayDay,
207 int birthdayYear, String jobTitle, long[] organizationIds,
208 boolean sendEmail)
209 throws PortalException, SystemException {
210
211
213 Company company = companyPersistence.findByPrimaryKey(companyId);
214 screenName = getScreenName(screenName);
215 emailAddress = emailAddress.trim().toLowerCase();
216 Date now = new Date();
217
218 if (PropsValues.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE) {
219 autoScreenName = true;
220 }
221
222 long userId = counterLocalService.increment();
223
224 validate(
225 companyId, userId, autoPassword, password1, password2,
226 autoScreenName, screenName, emailAddress, firstName, lastName,
227 organizationIds);
228
229 if (autoPassword) {
230 password1 = PwdToolkitUtil.generate();
231 }
232 else {
233 if (Validator.isNull(password1) || Validator.isNull(password2)) {
234 throw new UserPasswordException(
235 UserPasswordException.PASSWORD_INVALID);
236 }
237 }
238
239 if (autoScreenName) {
240 ScreenNameGenerator screenNameGenerator =
241 (ScreenNameGenerator)InstancePool.get(
242 PropsValues.USERS_SCREEN_NAME_GENERATOR);
243
244 try {
245 screenName = screenNameGenerator.generate(
246 companyId, userId, emailAddress);
247 }
248 catch (Exception e) {
249 throw new SystemException(e);
250 }
251 }
252
253 User defaultUser = getDefaultUser(companyId);
254
255 String fullName = ContactConstants.getFullName(
256 firstName, middleName, lastName);
257
258 String greeting = LanguageUtil.format(
259 companyId, locale, "welcome-x", " " + fullName, false);
260
261 User user = userPersistence.create(userId);
262
263 user.setCompanyId(companyId);
264 user.setCreateDate(now);
265 user.setModifiedDate(now);
266 user.setDefaultUser(false);
267 user.setContactId(counterLocalService.increment());
268 user.setPassword(PwdEncryptor.encrypt(password1));
269 user.setPasswordUnencrypted(password1);
270 user.setPasswordEncrypted(true);
271 user.setPasswordReset(false);
272 user.setScreenName(screenName);
273 user.setEmailAddress(emailAddress);
274 user.setLanguageId(locale.toString());
275 user.setTimeZoneId(defaultUser.getTimeZoneId());
276 user.setGreeting(greeting);
277 user.setFirstName(firstName);
278 user.setMiddleName(middleName);
279 user.setLastName(lastName);
280 user.setJobTitle(jobTitle);
281 user.setActive(true);
282
283 userPersistence.update(user, false);
284
285
287 String creatorUserName = StringPool.BLANK;
288
289 if (creatorUserId <= 0) {
290 creatorUserId = user.getUserId();
291
292
295 }
297 else {
298 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
299
300 creatorUserName = creatorUser.getFullName();
301 }
302
303 resourceLocalService.addResources(
304 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
305 false, false, false);
306
307
309 if (user.hasCompanyMx()) {
310 mailService.addUser(
311 companyId, userId, password1, firstName, middleName, lastName,
312 emailAddress);
313 }
314
315
317 Date birthday = PortalUtil.getDate(
318 birthdayMonth, birthdayDay, birthdayYear,
319 new ContactBirthdayException());
320
321 Contact contact = contactPersistence.create(user.getContactId());
322
323 contact.setCompanyId(user.getCompanyId());
324 contact.setUserId(creatorUserId);
325 contact.setUserName(creatorUserName);
326 contact.setCreateDate(now);
327 contact.setModifiedDate(now);
328 contact.setAccountId(company.getAccountId());
329 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
330 contact.setFirstName(firstName);
331 contact.setMiddleName(middleName);
332 contact.setLastName(lastName);
333 contact.setPrefixId(prefixId);
334 contact.setSuffixId(suffixId);
335 contact.setMale(male);
336 contact.setBirthday(birthday);
337 contact.setJobTitle(jobTitle);
338
339 contactPersistence.update(contact, false);
340
341
343 updateOrganizations(userId, organizationIds);
344
345
347 groupLocalService.addGroup(
348 user.getUserId(), User.class.getName(), user.getUserId(), null,
349 null, 0, StringPool.SLASH + screenName, true);
350
351
353 Set<Long> groupIdsSet = new HashSet<Long>();
354
355 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
356 companyId, PropsKeys.ADMIN_DEFAULT_GROUP_NAMES, StringPool.NEW_LINE,
357 PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
358
359 for (String defaultGroupName : defaultGroupNames) {
360 try {
361 Group group = groupPersistence.findByC_N(
362 companyId, defaultGroupName);
363
364 groupIdsSet.add(group.getGroupId());
365 }
366 catch (NoSuchGroupException nsge) {
367 }
368 }
369
370 long[] groupIds = ArrayUtil.toArray(
371 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
372
373 groupLocalService.addUserGroups(userId, groupIds);
374
375
377 List<Role> roles = new ArrayList<Role>();
378
379 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
380 companyId, PropsKeys.ADMIN_DEFAULT_ROLE_NAMES, StringPool.NEW_LINE,
381 PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
382
383 for (String defaultRoleName : defaultRoleNames) {
384 try {
385 Role role = rolePersistence.findByC_N(
386 companyId, defaultRoleName);
387
388 roles.add(role);
389 }
390 catch (NoSuchRoleException nsge) {
391 }
392 }
393
394 userPersistence.setRoles(userId, roles);
395
396
398 List<UserGroup> userGroups = new ArrayList<UserGroup>();
399
400 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
401 companyId, PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
402 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
403
404 for (String defaultUserGroupName : defaultUserGroupNames) {
405 try {
406 UserGroup userGroup = userGroupPersistence.findByC_N(
407 companyId, defaultUserGroupName);
408
409 userGroups.add(userGroup);
410
411 copyUserGroupLayouts(
412 userGroup.getUserGroupId(), new long[] {userId});
413 }
414 catch (NoSuchUserGroupException nsuge) {
415 }
416 }
417
418 userPersistence.setUserGroups(userId, userGroups);
419
420
422 if (sendEmail) {
423 try {
424 sendEmail(user, password1);
425 }
426 catch (IOException ioe) {
427 throw new SystemException(ioe);
428 }
429 }
430
431 return user;
432 }
433
434 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
435 public int authenticateByEmailAddress(
436 long companyId, String emailAddress, String password,
437 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
438 throws PortalException, SystemException {
439
440 return authenticate(
441 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
442 headerMap, parameterMap);
443 }
444
445 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
446 public int authenticateByScreenName(
447 long companyId, String screenName, String password,
448 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
449 throws PortalException, SystemException {
450
451 return authenticate(
452 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
453 headerMap, parameterMap);
454 }
455
456 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
457 public int authenticateByUserId(
458 long companyId, long userId, String password,
459 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
460 throws PortalException, SystemException {
461
462 return authenticate(
463 companyId, String.valueOf(userId), password,
464 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
465 }
466
467 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
468 public long authenticateForBasic(
469 long companyId, String authType, String login, String password)
470 throws PortalException, SystemException {
471
472 try {
473 User user = null;
474
475 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
476 user = getUserByEmailAddress(companyId, login);
477 }
478 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
479 user = getUserByScreenName(companyId, login);
480 }
481 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
482 user = getUserById(companyId, GetterUtil.getLong(login));
483 }
484
485 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
486 return user.getUserId();
487 }
488
489 String userPassword = user.getPassword();
490
491 if (!user.isPasswordEncrypted()) {
492 userPassword = PwdEncryptor.encrypt(userPassword);
493 }
494
495 String encPassword = PwdEncryptor.encrypt(password);
496
497 if (userPassword.equals(password) ||
498 userPassword.equals(encPassword)) {
499
500 return user.getUserId();
501 }
502 }
503 catch (NoSuchUserException nsue) {
504 }
505
506 return 0;
507 }
508
509 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
510 public boolean authenticateForJAAS(long userId, String encPassword) {
511 try {
512 User user = userPersistence.findByPrimaryKey(userId);
513
514 if (user.isDefaultUser()) {
515 _log.error(
516 "The default user should never be allowed to authenticate");
517
518 return false;
519 }
520
521 String password = user.getPassword();
522
523 if (user.isPasswordEncrypted()) {
524 if (password.equals(encPassword)) {
525 return true;
526 }
527
528 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
529 encPassword = PwdEncryptor.encrypt(encPassword, password);
530
531 if (password.equals(encPassword)) {
532 return true;
533 }
534 }
535 }
536 else {
537 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
538 if (password.equals(encPassword)) {
539 return true;
540 }
541 }
542
543 password = PwdEncryptor.encrypt(password);
544
545 if (password.equals(encPassword)) {
546 return true;
547 }
548 }
549 }
550 catch (Exception e) {
551 _log.error(e);
552 }
553
554 return false;
555 }
556
557 public void checkLockout(User user)
558 throws PortalException, SystemException {
559
560 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
561 return;
562 }
563
564 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
565
566 if (passwordPolicy.isLockout()) {
567
568
570 Date now = new Date();
571 int failedLoginAttempts = user.getFailedLoginAttempts();
572
573 if (failedLoginAttempts > 0) {
574 long failedLoginTime = user.getLastFailedLoginDate().getTime();
575 long elapsedTime = now.getTime() - failedLoginTime;
576 long requiredElapsedTime =
577 passwordPolicy.getResetFailureCount() * 1000;
578
579 if ((requiredElapsedTime != 0) &&
580 (elapsedTime > requiredElapsedTime)) {
581
582 user.setLastFailedLoginDate(null);
583 user.setFailedLoginAttempts(0);
584 }
585 }
586
587
589 if (user.isLockout()) {
590 long lockoutTime = user.getLockoutDate().getTime();
591 long elapsedTime = now.getTime() - lockoutTime;
592 long requiredElapsedTime =
593 passwordPolicy.getLockoutDuration() * 1000;
594
595 if ((requiredElapsedTime != 0) &&
596 (elapsedTime > requiredElapsedTime)) {
597
598 user.setLockout(false);
599 user.setLockoutDate(null);
600 }
601 }
602
603 if (user.isLockout()) {
604 throw new UserLockoutException();
605 }
606 }
607 }
608
609 public void checkLoginFailure(User user) throws SystemException {
610 Date now = new Date();
611
612 int failedLoginAttempts = user.getFailedLoginAttempts();
613
614 user.setLastFailedLoginDate(now);
615 user.setFailedLoginAttempts(++failedLoginAttempts);
616
617 userPersistence.update(user, false);
618 }
619
620 public void checkLoginFailureByEmailAddress(
621 long companyId, String emailAddress)
622 throws PortalException, SystemException {
623
624 User user = getUserByEmailAddress(companyId, emailAddress);
625
626 checkLoginFailure(user);
627 }
628
629 public void checkLoginFailureById(long userId)
630 throws PortalException, SystemException {
631
632 User user = userPersistence.findByPrimaryKey(userId);
633
634 checkLoginFailure(user);
635 }
636
637 public void checkLoginFailureByScreenName(long companyId, String screenName)
638 throws PortalException, SystemException {
639
640 User user = getUserByScreenName(companyId, screenName);
641
642 checkLoginFailure(user);
643 }
644
645 public void checkPasswordExpired(User user)
646 throws PortalException, SystemException {
647
648 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
649 return;
650 }
651
652 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
653
654
656 if (isPasswordExpired(user)) {
657 int graceLoginCount = user.getGraceLoginCount();
658
659 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
660 user.setGraceLoginCount(++graceLoginCount);
661
662 userPersistence.update(user, false);
663 }
664 else {
665 throw new PasswordExpiredException();
666 }
667 }
668
669
671 if (isPasswordExpiringSoon(user)) {
672 user.setPasswordReset(true);
673
674 userPersistence.update(user, false);
675 }
676
677
679 if (passwordPolicy.isChangeable() &&
680 passwordPolicy.isChangeRequired()) {
681
682 if (user.getLastLoginDate() == null) {
683 boolean passwordReset = false;
684
685 if (passwordPolicy.isChangeable() &&
686 passwordPolicy.isChangeRequired()) {
687
688 passwordReset = true;
689 }
690
691 user.setPasswordReset(passwordReset);
692
693 userPersistence.update(user, false);
694 }
695 }
696 }
697
698 public void clearOrganizationUsers(long organizationId)
699 throws SystemException {
700
701 organizationPersistence.clearUsers(organizationId);
702
703 PermissionCacheUtil.clearCache();
704 }
705
706 public void clearUserGroupUsers(long userGroupId) throws SystemException {
707 userGroupPersistence.clearUsers(userGroupId);
708
709 PermissionCacheUtil.clearCache();
710 }
711
712 public KeyValuePair decryptUserId(
713 long companyId, String name, String password)
714 throws PortalException, SystemException {
715
716 Company company = companyPersistence.findByPrimaryKey(companyId);
717
718 try {
719 name = Encryptor.decrypt(company.getKeyObj(), name);
720 }
721 catch (EncryptorException ee) {
722 throw new SystemException(ee);
723 }
724
725 long userId = GetterUtil.getLong(name);
726
727 User user = userPersistence.findByPrimaryKey(userId);
728
729 try {
730 password = Encryptor.decrypt(company.getKeyObj(), password);
731 }
732 catch (EncryptorException ee) {
733 throw new SystemException(ee);
734 }
735
736 String encPassword = PwdEncryptor.encrypt(password);
737
738 if (user.getPassword().equals(encPassword)) {
739 if (isPasswordExpired(user)) {
740 user.setPasswordReset(true);
741
742 userPersistence.update(user, false);
743 }
744
745 return new KeyValuePair(name, password);
746 }
747 else {
748 throw new PrincipalException();
749 }
750 }
751
752 public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
753 throws SystemException {
754
755 passwordPolicyRelLocalService.deletePasswordPolicyRel(
756 passwordPolicyId, User.class.getName(), userId);
757 }
758
759 public void deleteRoleUser(long roleId, long userId)
760 throws SystemException {
761
762 rolePersistence.removeUser(roleId, userId);
763
764 PermissionCacheUtil.clearCache();
765 }
766
767 public void deleteUser(long userId)
768 throws PortalException, SystemException {
769
770 if (!PropsValues.USERS_DELETE) {
771 throw new RequiredUserException();
772 }
773
774 User user = userPersistence.findByPrimaryKey(userId);
775
776
778 browserTrackerLocalService.deleteUserBrowserTracker(userId);
779
780
782 Group group = user.getGroup();
783
784 if (group != null) {
785 groupLocalService.deleteGroup(group.getGroupId());
786 }
787
788
790 imageLocalService.deleteImage(user.getPortraitId());
791
792
794 passwordPolicyRelLocalService.deletePasswordPolicyRel(
795 User.class.getName(), userId);
796
797
799 passwordTrackerLocalService.deletePasswordTrackers(userId);
800
801
803 subscriptionLocalService.deleteSubscriptions(userId);
804
805
807 userIdMapperLocalService.deleteUserIdMappers(userId);
808
809
811 announcementsDeliveryLocalService.deleteDeliveries(userId);
812
813
815 blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
816
817
819 dlFileRankLocalService.deleteFileRanks(userId);
820
821
823 expandoValueLocalService.deleteValues(User.class.getName(), userId);
824
825
827 mbBanLocalService.deleteBansByBanUserId(userId);
828 mbMessageFlagLocalService.deleteFlags(userId);
829 mbStatsUserLocalService.deleteStatsUsersByUserId(userId);
830
831
833 shoppingCartLocalService.deleteUserCarts(userId);
834
835
837 socialActivityLocalService.deleteUserActivities(userId);
838 socialRequestLocalService.deleteReceiverUserRequests(userId);
839 socialRequestLocalService.deleteUserRequests(userId);
840
841
843 mailService.deleteUser(user.getCompanyId(), userId);
844
845
847 try {
848 contactLocalService.deleteContact(user.getContactId());
849 }
850 catch (NoSuchContactException nsce) {
851 }
852
853
855 resourceLocalService.deleteResource(
856 user.getCompanyId(), User.class.getName(),
857 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
858
859
861 userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
862
863
865 userPersistence.remove(userId);
866
867
869 PermissionCacheUtil.clearCache();
870 }
871
872 public String encryptUserId(String name)
873 throws PortalException, SystemException {
874
875 long userId = GetterUtil.getLong(name);
876
877 User user = userPersistence.findByPrimaryKey(userId);
878
879 Company company = companyPersistence.findByPrimaryKey(
880 user.getCompanyId());
881
882 try {
883 return Encryptor.encrypt(company.getKeyObj(), name);
884 }
885 catch (EncryptorException ee) {
886 throw new SystemException(ee);
887 }
888 }
889
890 public User getDefaultUser(long companyId)
891 throws PortalException, SystemException {
892
893 User userModel = _defaultUsers.get(companyId);
894
895 if (userModel == null) {
896 userModel = userPersistence.findByC_DU(companyId, true);
897
898 _defaultUsers.put(companyId, userModel);
899 }
900
901 return userModel;
902 }
903
904 public long getDefaultUserId(long companyId)
905 throws PortalException, SystemException {
906
907 User user = getDefaultUser(companyId);
908
909 return user.getUserId();
910 }
911
912 public long[] getGroupUserIds(long groupId) throws SystemException {
913 return getUserIds(getGroupUsers(groupId));
914 }
915
916 public List<User> getGroupUsers(long groupId) throws SystemException {
917 return groupPersistence.getUsers(groupId);
918 }
919
920 public int getGroupUsersCount(long groupId) throws SystemException {
921 return groupPersistence.getUsersSize(groupId);
922 }
923
924 public int getGroupUsersCount(long groupId, boolean active)
925 throws PortalException, SystemException {
926
927 Group group = groupPersistence.findByPrimaryKey(groupId);
928
929 LinkedHashMap<String, Object> params =
930 new LinkedHashMap<String, Object>();
931
932 params.put("usersGroups", new Long(groupId));
933
934 return searchCount(group.getCompanyId(), null, active, params);
935 }
936
937 public List<User> getNoAnnouncementsDeliveries(String type)
938 throws SystemException {
939
940 return userFinder.findByNoAnnouncementsDeliveries(type);
941 }
942
943 public List<User> getNoContacts() throws SystemException {
944 return userFinder.findByNoContacts();
945 }
946
947 public List<User> getNoGroups() throws SystemException {
948 return userFinder.findByNoGroups();
949 }
950
951 public long[] getOrganizationUserIds(long organizationId)
952 throws SystemException {
953
954 return getUserIds(getOrganizationUsers(organizationId));
955 }
956
957 public List<User> getOrganizationUsers(long organizationId)
958 throws SystemException {
959
960 return organizationPersistence.getUsers(organizationId);
961 }
962
963 public int getOrganizationUsersCount(long organizationId)
964 throws SystemException {
965
966 return organizationPersistence.getUsersSize(organizationId);
967 }
968
969 public int getOrganizationUsersCount(long organizationId, boolean active)
970 throws PortalException, SystemException {
971
972 Organization organization = organizationPersistence.findByPrimaryKey(
973 organizationId);
974
975 LinkedHashMap<String, Object> params =
976 new LinkedHashMap<String, Object>();
977
978 params.put("usersOrgs", new Long(organizationId));
979
980 return searchCount(organization.getCompanyId(), null, active, params);
981 }
982
983 public List<User> getPermissionUsers(
984 long companyId, long groupId, String name, String primKey,
985 String actionId, String firstName, String middleName,
986 String lastName, String emailAddress, boolean andOperator,
987 int start, int end)
988 throws SystemException {
989
990 int orgGroupPermissionsCount =
991 permissionUserFinder.countByOrgGroupPermissions(
992 companyId, name, primKey, actionId);
993
994 if (orgGroupPermissionsCount > 0) {
995 return permissionUserFinder.findByUserAndOrgGroupPermission(
996 companyId, name, primKey, actionId, firstName, middleName,
997 lastName, emailAddress, andOperator, start, end);
998 }
999 else {
1000 return permissionUserFinder.findByPermissionAndRole(
1001 companyId, groupId, name, primKey, actionId, firstName,
1002 middleName, lastName, emailAddress, andOperator, start, end);
1003 }
1004 }
1005
1006 public int getPermissionUsersCount(
1007 long companyId, long groupId, String name, String primKey,
1008 String actionId, String firstName, String middleName,
1009 String lastName, String emailAddress, boolean andOperator)
1010 throws SystemException {
1011
1012 int orgGroupPermissionsCount =
1013 permissionUserFinder.countByOrgGroupPermissions(
1014 companyId, name, primKey, actionId);
1015
1016 if (orgGroupPermissionsCount > 0) {
1017 return permissionUserFinder.countByUserAndOrgGroupPermission(
1018 companyId, name, primKey, actionId, firstName, middleName,
1019 lastName, emailAddress, andOperator);
1020 }
1021 else {
1022 return permissionUserFinder.countByPermissionAndRole(
1023 companyId, groupId, name, primKey, actionId, firstName,
1024 middleName, lastName, emailAddress, andOperator);
1025 }
1026 }
1027
1028 public long[] getRoleUserIds(long roleId) throws SystemException {
1029 return getUserIds(getRoleUsers(roleId));
1030 }
1031
1032 public List<User> getRoleUsers(long roleId) throws SystemException {
1033 return rolePersistence.getUsers(roleId);
1034 }
1035
1036 public List<User> getRoleUsers(long roleId, int start, int end)
1037 throws SystemException {
1038
1039 return rolePersistence.getUsers(roleId, start, end);
1040 }
1041
1042 public int getRoleUsersCount(long roleId) throws SystemException {
1043 return rolePersistence.getUsersSize(roleId);
1044 }
1045
1046 public int getRoleUsersCount(long roleId, boolean active)
1047 throws PortalException, SystemException {
1048
1049 Role role = rolePersistence.findByPrimaryKey(
1050 roleId);
1051
1052 LinkedHashMap<String, Object> params =
1053 new LinkedHashMap<String, Object>();
1054
1055 params.put("usersRoles", new Long(roleId));
1056
1057 return searchCount(role.getCompanyId(), null, active, params);
1058 }
1059
1060 public List<User> getSocialUsers(
1061 long userId, int start, int end, OrderByComparator obc)
1062 throws PortalException, SystemException {
1063
1064 User user = userPersistence.findByPrimaryKey(userId);
1065
1066 LinkedHashMap<String, Object> params =
1067 new LinkedHashMap<String, Object>();
1068
1069 params.put("socialRelation", new Long[] {userId});
1070
1071 return search(
1072 user.getCompanyId(), null, true, params, start, end, obc);
1073 }
1074
1075 public List<User> getSocialUsers(
1076 long userId, int type, int start, int end, OrderByComparator obc)
1077 throws PortalException, SystemException {
1078
1079 User user = userPersistence.findByPrimaryKey(userId);
1080
1081 LinkedHashMap<String, Object> params =
1082 new LinkedHashMap<String, Object>();
1083
1084 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1085
1086 return search(user.getCompanyId(), null, true, params, start, end, obc);
1087 }
1088
1089 public List<User> getSocialUsers(
1090 long userId1, long userId2, int start, int end,
1091 OrderByComparator obc)
1092 throws PortalException, SystemException {
1093
1094 User user1 = userPersistence.findByPrimaryKey(userId1);
1095
1096 LinkedHashMap<String, Object> params =
1097 new LinkedHashMap<String, Object>();
1098
1099 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1100
1101 return search(
1102 user1.getCompanyId(), null, true, params, start, end, obc);
1103 }
1104
1105 public List<User> getSocialUsers(
1106 long userId1, long userId2, int type, int start, int end,
1107 OrderByComparator obc)
1108 throws PortalException, SystemException {
1109
1110 User user1 = userPersistence.findByPrimaryKey(userId1);
1111
1112 LinkedHashMap<String, Object> params =
1113 new LinkedHashMap<String, Object>();
1114
1115 params.put(
1116 "socialMutualRelationType",
1117 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1118
1119 return search(
1120 user1.getCompanyId(), null, true, params, start, end, obc);
1121 }
1122
1123 public int getSocialUsersCount(long userId)
1124 throws PortalException, SystemException {
1125
1126 User user = userPersistence.findByPrimaryKey(userId);
1127
1128 LinkedHashMap<String, Object> params =
1129 new LinkedHashMap<String, Object>();
1130
1131 params.put("socialRelation", new Long[] {userId});
1132
1133 return searchCount(user.getCompanyId(), null, true, params);
1134 }
1135
1136 public int getSocialUsersCount(long userId, int type)
1137 throws PortalException, SystemException {
1138
1139 User user = userPersistence.findByPrimaryKey(userId);
1140
1141 LinkedHashMap<String, Object> params =
1142 new LinkedHashMap<String, Object>();
1143
1144 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1145
1146 return searchCount(user.getCompanyId(), null, true, params);
1147 }
1148
1149 public int getSocialUsersCount(long userId1, long userId2)
1150 throws PortalException, SystemException {
1151
1152 User user1 = userPersistence.findByPrimaryKey(userId1);
1153
1154 LinkedHashMap<String, Object> params =
1155 new LinkedHashMap<String, Object>();
1156
1157 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1158
1159 return searchCount(user1.getCompanyId(), null, true, params);
1160 }
1161
1162 public int getSocialUsersCount(long userId1, long userId2, int type)
1163 throws PortalException, SystemException {
1164
1165 User user1 = userPersistence.findByPrimaryKey(userId1);
1166
1167 LinkedHashMap<String, Object> params =
1168 new LinkedHashMap<String, Object>();
1169
1170 params.put(
1171 "socialMutualRelationType",
1172 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1173
1174 return searchCount(user1.getCompanyId(), null, true, params);
1175 }
1176
1177 public List<User> getUserGroupUsers(long userGroupId)
1178 throws SystemException {
1179
1180 return userGroupPersistence.getUsers(userGroupId);
1181 }
1182
1183 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1184 return userGroupPersistence.getUsersSize(userGroupId);
1185 }
1186
1187 public int getUserGroupUsersCount(long userGroupId, boolean active)
1188 throws PortalException, SystemException {
1189
1190 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1191 userGroupId);
1192
1193 LinkedHashMap<String, Object> params =
1194 new LinkedHashMap<String, Object>();
1195
1196 params.put("usersUserGroups", new Long(userGroupId));
1197
1198 return searchCount(userGroup.getCompanyId(), null, active, params);
1199 }
1200
1201 public User getUserByContactId(long contactId)
1202 throws PortalException, SystemException {
1203
1204 return userPersistence.findByContactId(contactId);
1205 }
1206
1207 public User getUserByEmailAddress(long companyId, String emailAddress)
1208 throws PortalException, SystemException {
1209
1210 emailAddress = emailAddress.trim().toLowerCase();
1211
1212 return userPersistence.findByC_EA(companyId, emailAddress);
1213 }
1214
1215 public User getUserById(long userId)
1216 throws PortalException, SystemException {
1217
1218 return userPersistence.findByPrimaryKey(userId);
1219 }
1220
1221 public User getUserById(long companyId, long userId)
1222 throws PortalException, SystemException {
1223
1224 return userPersistence.findByC_U(companyId, userId);
1225 }
1226
1227 public User getUserByOpenId(String openId)
1228 throws PortalException, SystemException {
1229
1230 return userPersistence.findByOpenId(openId);
1231 }
1232
1233 public User getUserByPortraitId(long portraitId)
1234 throws PortalException, SystemException {
1235
1236 return userPersistence.findByPortraitId(portraitId);
1237 }
1238
1239 public User getUserByScreenName(long companyId, String screenName)
1240 throws PortalException, SystemException {
1241
1242 screenName = getScreenName(screenName);
1243
1244 return userPersistence.findByC_SN(companyId, screenName);
1245 }
1246
1247 public long getUserIdByEmailAddress(long companyId, String emailAddress)
1248 throws PortalException, SystemException {
1249
1250 emailAddress = emailAddress.trim().toLowerCase();
1251
1252 User user = userPersistence.findByC_EA(companyId, emailAddress);
1253
1254 return user.getUserId();
1255 }
1256
1257 public long getUserIdByScreenName(long companyId, String screenName)
1258 throws PortalException, SystemException {
1259
1260 screenName = getScreenName(screenName);
1261
1262 User user = userPersistence.findByC_SN(companyId, screenName);
1263
1264 return user.getUserId();
1265 }
1266
1267 public boolean hasGroupUser(long groupId, long userId)
1268 throws SystemException {
1269
1270 return groupPersistence.containsUser(groupId, userId);
1271 }
1272
1273 public boolean hasOrganizationUser(long organizationId, long userId)
1274 throws SystemException {
1275
1276 return organizationPersistence.containsUser(organizationId, userId);
1277 }
1278
1279 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1280 throws SystemException {
1281
1282 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1283 passwordPolicyId, User.class.getName(), userId);
1284 }
1285
1286 public boolean hasRoleUser(long roleId, long userId)
1287 throws SystemException {
1288
1289 return rolePersistence.containsUser(roleId, userId);
1290 }
1291
1292
1302 public boolean hasRoleUser(
1303 long companyId, String name, long userId, boolean inherited)
1304 throws PortalException, SystemException {
1305
1306 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
1307 }
1308
1309 public boolean hasUserGroupUser(long userGroupId, long userId)
1310 throws SystemException {
1311
1312 return userGroupPersistence.containsUser(userGroupId, userId);
1313 }
1314
1315 public boolean isPasswordExpired(User user)
1316 throws PortalException, SystemException {
1317
1318 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1319
1320 if (passwordPolicy.getExpireable()) {
1321 Date now = new Date();
1322
1323 if (user.getPasswordModifiedDate() == null) {
1324 user.setPasswordModifiedDate(now);
1325
1326 userLocalService.updateUser(user, false);
1327 }
1328
1329 long passwordStartTime = user.getPasswordModifiedDate().getTime();
1330 long elapsedTime = now.getTime() - passwordStartTime;
1331
1332 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1333 return true;
1334 }
1335 else {
1336 return false;
1337 }
1338 }
1339
1340 return false;
1341 }
1342
1343 public boolean isPasswordExpiringSoon(User user)
1344 throws PortalException, SystemException {
1345
1346 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1347
1348 if (passwordPolicy.isExpireable()) {
1349 Date now = new Date();
1350
1351 if (user.getPasswordModifiedDate() == null) {
1352 user.setPasswordModifiedDate(now);
1353
1354 userLocalService.updateUser(user, false);
1355 }
1356
1357 long timeModified = user.getPasswordModifiedDate().getTime();
1358 long passwordExpiresOn =
1359 (passwordPolicy.getMaxAge() * 1000) + timeModified;
1360
1361 long timeStartWarning =
1362 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1363
1364 if (now.getTime() > timeStartWarning) {
1365 return true;
1366 }
1367 else {
1368 return false;
1369 }
1370 }
1371
1372 return false;
1373 }
1374
1375 public List<User> search(
1376 long companyId, String keywords, Boolean active,
1377 LinkedHashMap<String, Object> params, int start, int end,
1378 OrderByComparator obc)
1379 throws SystemException {
1380
1381 return userFinder.findByKeywords(
1382 companyId, keywords, active, params, start, end, obc);
1383 }
1384
1385 public List<User> search(
1386 long companyId, String firstName, String middleName,
1387 String lastName, String screenName, String emailAddress,
1388 Boolean active, LinkedHashMap<String, Object> params,
1389 boolean andSearch, int start, int end, OrderByComparator obc)
1390 throws SystemException {
1391
1392 return userFinder.findByC_FN_MN_LN_SN_EA_A(
1393 companyId, firstName, middleName, lastName, screenName,
1394 emailAddress, active, params, andSearch, start, end, obc);
1395 }
1396
1397 public int searchCount(
1398 long companyId, String keywords, Boolean active,
1399 LinkedHashMap<String, Object> params)
1400 throws SystemException {
1401
1402 return userFinder.countByKeywords(companyId, keywords, active, params);
1403 }
1404
1405 public int searchCount(
1406 long companyId, String firstName, String middleName,
1407 String lastName, String screenName, String emailAddress,
1408 Boolean active, LinkedHashMap<String, Object> params,
1409 boolean andSearch)
1410 throws SystemException {
1411
1412 return userFinder.countByC_FN_MN_LN_SN_EA_A(
1413 companyId, firstName, middleName, lastName, screenName,
1414 emailAddress, active, params, andSearch);
1415 }
1416
1417 public void sendPassword(
1418 long companyId, String emailAddress, String remoteAddr,
1419 String remoteHost, String userAgent)
1420 throws PortalException, SystemException {
1421
1422 try {
1423 doSendPassword(
1424 companyId, emailAddress, remoteAddr, remoteHost, userAgent);
1425 }
1426 catch (IOException ioe) {
1427 throw new SystemException(ioe);
1428 }
1429 }
1430
1431 public void setRoleUsers(long roleId, long[] userIds)
1432 throws SystemException {
1433
1434 rolePersistence.setUsers(roleId, userIds);
1435
1436 PermissionCacheUtil.clearCache();
1437 }
1438
1439 public void setUserGroupUsers(long userGroupId, long[] userIds)
1440 throws PortalException, SystemException {
1441
1442 copyUserGroupLayouts(userGroupId, userIds);
1443
1444 userGroupPersistence.setUsers(userGroupId, userIds);
1445
1446 PermissionCacheUtil.clearCache();
1447 }
1448
1449 public void unsetGroupUsers(long groupId, long[] userIds)
1450 throws SystemException {
1451
1452 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1453
1454 groupPersistence.removeUsers(groupId, userIds);
1455
1456 PermissionCacheUtil.clearCache();
1457 }
1458
1459 public void unsetOrganizationUsers(long organizationId, long[] userIds)
1460 throws PortalException, SystemException {
1461
1462 Organization organization = organizationPersistence.findByPrimaryKey(
1463 organizationId);
1464
1465 Group group = organization.getGroup();
1466
1467 long groupId = group.getGroupId();
1468
1469 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1470
1471 organizationPersistence.removeUsers(organizationId, userIds);
1472
1473 PermissionCacheUtil.clearCache();
1474 }
1475
1476 public void unsetPasswordPolicyUsers(
1477 long passwordPolicyId, long[] userIds)
1478 throws SystemException {
1479
1480 passwordPolicyRelLocalService.deletePasswordPolicyRels(
1481 passwordPolicyId, User.class.getName(), userIds);
1482 }
1483
1484 public void unsetRoleUsers(long roleId, long[] userIds)
1485 throws SystemException {
1486
1487 rolePersistence.removeUsers(roleId, userIds);
1488
1489 PermissionCacheUtil.clearCache();
1490 }
1491
1492 public void unsetRoleUsers(long roleId, List<User> users)
1493 throws SystemException {
1494
1495 rolePersistence.removeUsers(roleId, users);
1496
1497 PermissionCacheUtil.clearCache();
1498 }
1499
1500 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1501 throws SystemException {
1502
1503 userGroupPersistence.removeUsers(userGroupId, userIds);
1504
1505 PermissionCacheUtil.clearCache();
1506 }
1507
1508 public User updateActive(long userId, boolean active)
1509 throws PortalException, SystemException {
1510
1511 User user = userPersistence.findByPrimaryKey(userId);
1512
1513 user.setActive(active);
1514
1515 userPersistence.update(user, false);
1516
1517 return user;
1518 }
1519
1520 public User updateAgreedToTermsOfUse(
1521 long userId, boolean agreedToTermsOfUse)
1522 throws PortalException, SystemException {
1523
1524 User user = userPersistence.findByPrimaryKey(userId);
1525
1526 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1527
1528 userPersistence.update(user, false);
1529
1530 return user;
1531 }
1532
1533 public User updateCreateDate(long userId, Date createDate)
1534 throws PortalException, SystemException {
1535
1536 User user = userPersistence.findByPrimaryKey(userId);
1537
1538 user.setCreateDate(createDate);
1539
1540 userPersistence.update(user, false);
1541
1542 return user;
1543 }
1544
1545 public User updateLastLogin(long userId, String loginIP)
1546 throws PortalException, SystemException {
1547
1548 User user = userPersistence.findByPrimaryKey(userId);
1549
1550 Date lastLoginDate = user.getLoginDate();
1551
1552 if (lastLoginDate == null) {
1553 lastLoginDate = new Date();
1554 }
1555
1556 user.setLoginDate(new Date());
1557 user.setLoginIP(loginIP);
1558 user.setLastLoginDate(lastLoginDate);
1559 user.setLastLoginIP(user.getLoginIP());
1560 user.setLastFailedLoginDate(null);
1561 user.setFailedLoginAttempts(0);
1562
1563 userPersistence.update(user, false);
1564
1565 return user;
1566 }
1567
1568 public User updateLockout(User user, boolean lockout)
1569 throws PortalException, SystemException {
1570
1571 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1572
1573 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1574 return user;
1575 }
1576
1577 Date lockoutDate = null;
1578
1579 if (lockout) {
1580 lockoutDate = new Date();
1581 }
1582
1583 user.setLockout(lockout);
1584 user.setLockoutDate(lockoutDate);
1585
1586 if (!lockout) {
1587 user.setLastFailedLoginDate(lockoutDate);
1588 user.setFailedLoginAttempts(0);
1589 }
1590
1591 userPersistence.update(user, false);
1592
1593 return user;
1594 }
1595
1596 public User updateLockoutByEmailAddress(
1597 long companyId, String emailAddress, boolean lockout)
1598 throws PortalException, SystemException {
1599
1600 User user = getUserByEmailAddress(companyId, emailAddress);
1601
1602 return updateLockout(user, lockout);
1603 }
1604
1605 public User updateLockoutById(long userId, boolean lockout)
1606 throws PortalException, SystemException {
1607
1608 User user = userPersistence.findByPrimaryKey(userId);
1609
1610 return updateLockout(user, lockout);
1611 }
1612
1613 public User updateLockoutByScreenName(
1614 long companyId, String screenName, boolean lockout)
1615 throws PortalException, SystemException {
1616
1617 User user = getUserByScreenName(companyId, screenName);
1618
1619 return updateLockout(user, lockout);
1620 }
1621
1622 public User updateModifiedDate(long userId, Date modifiedDate)
1623 throws PortalException, SystemException {
1624
1625 User user = userPersistence.findByPrimaryKey(userId);
1626
1627 user.setModifiedDate(modifiedDate);
1628
1629 userPersistence.update(user, false);
1630
1631 return user;
1632 }
1633
1634 public void updateOpenId(long userId, String openId)
1635 throws PortalException, SystemException {
1636
1637 User user = userPersistence.findByPrimaryKey(userId);
1638
1639 user.setOpenId(openId);
1640
1641 userPersistence.update(user, false);
1642 }
1643
1644 public void updateOrganizations(long userId, long[] newOrganizationIds)
1645 throws PortalException, SystemException {
1646
1647 List<Organization> oldOrganizations = userPersistence.getOrganizations(
1648 userId);
1649
1650 List<Long> oldOrganizationIds = new ArrayList<Long>(
1651 oldOrganizations.size());
1652
1653 for (int i = 0; i < oldOrganizations.size(); i++) {
1654 Organization oldOrganization = oldOrganizations.get(i);
1655
1656 long oldOrganizationId = oldOrganization.getOrganizationId();
1657
1658 oldOrganizationIds.add(oldOrganizationId);
1659
1660 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1661 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1662 }
1663 }
1664
1665 for (int i = 0; i < newOrganizationIds.length; i++) {
1666 long newOrganizationId = newOrganizationIds[i];
1667
1668 if (!oldOrganizationIds.contains(newOrganizationId)) {
1669 addOrganizationUsers(newOrganizationId, new long[] {userId});
1670 }
1671 }
1672
1673 PermissionCacheUtil.clearCache();
1674 }
1675
1676 public User updatePassword(
1677 long userId, String password1, String password2,
1678 boolean passwordReset)
1679 throws PortalException, SystemException {
1680
1681 return updatePassword(
1682 userId, password1, password2, passwordReset, false);
1683 }
1684
1685 public User updatePassword(
1686 long userId, String password1, String password2,
1687 boolean passwordReset, boolean silentUpdate)
1688 throws PortalException, SystemException {
1689
1690 User user = userPersistence.findByPrimaryKey(userId);
1691
1692
1695 if (!silentUpdate) {
1696 validatePassword(user.getCompanyId(), userId, password1, password2);
1697 }
1698
1699 String oldEncPwd = user.getPassword();
1700
1701 if (!user.isPasswordEncrypted()) {
1702 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1703 }
1704
1705 String newEncPwd = PwdEncryptor.encrypt(password1);
1706
1707 if (user.hasCompanyMx()) {
1708 mailService.updatePassword(user.getCompanyId(), userId, password1);
1709 }
1710
1711 user.setPassword(newEncPwd);
1712 user.setPasswordUnencrypted(password1);
1713 user.setPasswordEncrypted(true);
1714 user.setPasswordReset(passwordReset);
1715 user.setPasswordModifiedDate(new Date());
1716 user.setGraceLoginCount(0);
1717
1718 if (!silentUpdate) {
1719 user.setPasswordModified(true);
1720 }
1721
1722 try {
1723 userPersistence.update(user, false);
1724 }
1725 catch (ModelListenerException mle) {
1726 String msg = GetterUtil.getString(mle.getCause().getMessage());
1727
1728 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1729 String passwordHistory = PrefsPropsUtil.getString(
1730 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
1731
1732 if (msg.indexOf(passwordHistory) != -1) {
1733 throw new UserPasswordException(
1734 UserPasswordException.PASSWORD_ALREADY_USED);
1735 }
1736 }
1737
1738 throw new UserPasswordException(
1739 UserPasswordException.PASSWORD_INVALID);
1740 }
1741
1742 if (!silentUpdate) {
1743 user.setPasswordModified(false);
1744
1745 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
1746 }
1747
1748 return user;
1749 }
1750
1751 public User updatePasswordManually(
1752 long userId, String password, boolean passwordEncrypted,
1753 boolean passwordReset, Date passwordModifiedDate)
1754 throws PortalException, SystemException {
1755
1756
1758 User user = userPersistence.findByPrimaryKey(userId);
1759
1760 user.setPassword(password);
1761 user.setPasswordEncrypted(passwordEncrypted);
1762 user.setPasswordReset(passwordReset);
1763 user.setPasswordModifiedDate(passwordModifiedDate);
1764
1765 userPersistence.update(user, false);
1766
1767 return user;
1768 }
1769
1770 public void updatePasswordReset(long userId, boolean passwordReset)
1771 throws PortalException, SystemException {
1772
1773 User user = userPersistence.findByPrimaryKey(userId);
1774
1775 user.setPasswordReset(passwordReset);
1776
1777 userPersistence.update(user, false);
1778 }
1779
1780 public void updatePortrait(long userId, byte[] bytes)
1781 throws PortalException, SystemException {
1782
1783 User user = userPersistence.findByPrimaryKey(userId);
1784
1785 long imageMaxSize = PrefsPropsUtil.getLong(
1786 PropsKeys.USERS_IMAGE_MAX_SIZE);
1787
1788 if ((imageMaxSize > 0) &&
1789 ((bytes == null) || (bytes.length > imageMaxSize))) {
1790
1791 throw new UserPortraitException();
1792 }
1793
1794 long portraitId = user.getPortraitId();
1795
1796 if (portraitId <= 0) {
1797 portraitId = counterLocalService.increment();
1798
1799 user.setPortraitId(portraitId);
1800
1801 userPersistence.update(user, false);
1802 }
1803
1804 imageLocalService.updateImage(portraitId, bytes);
1805 }
1806
1807 public void updateScreenName(long userId, String screenName)
1808 throws PortalException, SystemException {
1809
1810
1812 User user = userPersistence.findByPrimaryKey(userId);
1813
1814 screenName = getScreenName(screenName);
1815
1816 validateScreenName(user.getCompanyId(), userId, screenName);
1817
1818 user.setScreenName(screenName);
1819
1820 userPersistence.update(user, false);
1821
1822
1824 Group group = groupLocalService.getUserGroup(
1825 user.getCompanyId(), userId);
1826
1827 group.setFriendlyURL(StringPool.SLASH + screenName);
1828
1829 groupPersistence.update(group, false);
1830 }
1831
1832 public User updateUser(
1833 long userId, String oldPassword, boolean passwordReset,
1834 String screenName, String emailAddress, String languageId,
1835 String timeZoneId, String greeting, String comments,
1836 String firstName, String middleName, String lastName, int prefixId,
1837 int suffixId, boolean male, int birthdayMonth, int birthdayDay,
1838 int birthdayYear, String smsSn, String aimSn, String facebookSn,
1839 String icqSn, String jabberSn, String msnSn, String mySpaceSn,
1840 String skypeSn, String twitterSn, String ymSn, String jobTitle,
1841 long[] organizationIds)
1842 throws PortalException, SystemException {
1843
1844 String newPassword1 = StringPool.BLANK;
1845 String newPassword2 = StringPool.BLANK;
1846
1847 return updateUser(
1848 userId, oldPassword, newPassword1, newPassword2, passwordReset,
1849 screenName, emailAddress, languageId, timeZoneId, greeting,
1850 comments, firstName, middleName, lastName, prefixId, suffixId, male,
1851 birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn,
1852 icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn,
1853 jobTitle, organizationIds);
1854 }
1855
1856 public User updateUser(
1857 long userId, String oldPassword, String newPassword1,
1858 String newPassword2, boolean passwordReset, String screenName,
1859 String emailAddress, String languageId, String timeZoneId,
1860 String greeting, String comments, String firstName,
1861 String middleName, String lastName, int prefixId, int suffixId,
1862 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1863 String smsSn, String aimSn, String facebookSn, String icqSn,
1864 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
1865 String twitterSn, String ymSn, String jobTitle,
1866 long[] organizationIds)
1867 throws PortalException, SystemException {
1868
1869
1871 String password = oldPassword;
1872 screenName = getScreenName(screenName);
1873 emailAddress = emailAddress.trim().toLowerCase();
1874 aimSn = aimSn.trim().toLowerCase();
1875 facebookSn = facebookSn.trim().toLowerCase();
1876 icqSn = icqSn.trim().toLowerCase();
1877 jabberSn = jabberSn.trim().toLowerCase();
1878 msnSn = msnSn.trim().toLowerCase();
1879 mySpaceSn = mySpaceSn.trim().toLowerCase();
1880 skypeSn = skypeSn.trim().toLowerCase();
1881 twitterSn = twitterSn.trim().toLowerCase();
1882 ymSn = ymSn.trim().toLowerCase();
1883 Date now = new Date();
1884
1885 validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1886
1887 if (Validator.isNotNull(newPassword1) ||
1888 Validator.isNotNull(newPassword2)) {
1889
1890 updatePassword(userId, newPassword1, newPassword2, passwordReset);
1891
1892 password = newPassword1;
1893 }
1894
1895 User user = userPersistence.findByPrimaryKey(userId);
1896 Company company = companyPersistence.findByPrimaryKey(
1897 user.getCompanyId());
1898
1899 user.setModifiedDate(now);
1900
1901 if (user.getContactId() <= 0) {
1902 user.setContactId(counterLocalService.increment());
1903 }
1904
1905 user.setPasswordReset(passwordReset);
1906 user.setScreenName(screenName);
1907
1908 if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1909
1910
1912 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1913 mailService.addUser(
1914 user.getCompanyId(), userId, password, firstName,
1915 middleName, lastName, emailAddress);
1916 }
1917
1918
1920 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1921 mailService.updateEmailAddress(
1922 user.getCompanyId(), userId, emailAddress);
1923 }
1924
1925
1927 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
1928 mailService.deleteEmailAddress(user.getCompanyId(), userId);
1929 }
1930
1931 user.setEmailAddress(emailAddress);
1932 }
1933
1934 user.setLanguageId(languageId);
1935 user.setTimeZoneId(timeZoneId);
1936 user.setGreeting(greeting);
1937 user.setComments(comments);
1938 user.setFirstName(firstName);
1939 user.setMiddleName(middleName);
1940 user.setLastName(lastName);
1941 user.setJobTitle(jobTitle);
1942
1943 userPersistence.update(user, false);
1944
1945
1947 Date birthday = PortalUtil.getDate(
1948 birthdayMonth, birthdayDay, birthdayYear,
1949 new ContactBirthdayException());
1950
1951 long contactId = user.getContactId();
1952
1953 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
1954
1955 if (contact == null) {
1956 contact = contactPersistence.create(contactId);
1957
1958 contact.setCompanyId(user.getCompanyId());
1959 contact.setUserName(StringPool.BLANK);
1960 contact.setCreateDate(now);
1961 contact.setAccountId(company.getAccountId());
1962 contact.setParentContactId(
1963 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
1964 }
1965
1966 contact.setModifiedDate(now);
1967 contact.setFirstName(firstName);
1968 contact.setMiddleName(middleName);
1969 contact.setLastName(lastName);
1970 contact.setPrefixId(prefixId);
1971 contact.setSuffixId(suffixId);
1972 contact.setMale(male);
1973 contact.setBirthday(birthday);
1974 contact.setSmsSn(smsSn);
1975 contact.setAimSn(aimSn);
1976 contact.setFacebookSn(facebookSn);
1977 contact.setIcqSn(icqSn);
1978 contact.setJabberSn(jabberSn);
1979 contact.setMsnSn(msnSn);
1980 contact.setMySpaceSn(mySpaceSn);
1981 contact.setSkypeSn(skypeSn);
1982 contact.setTwitterSn(twitterSn);
1983 contact.setYmSn(ymSn);
1984 contact.setJobTitle(jobTitle);
1985
1986 contactPersistence.update(contact, false);
1987
1988
1990 updateOrganizations(userId, organizationIds);
1991
1992
1994 Group group = groupLocalService.getUserGroup(
1995 user.getCompanyId(), userId);
1996
1997 group.setFriendlyURL(StringPool.SLASH + screenName);
1998
1999 groupPersistence.update(group, false);
2000
2001
2003 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
2004
2005
2007 PermissionCacheUtil.clearCache();
2008
2009 return user;
2010 }
2011
2012 protected int authenticate(
2013 long companyId, String login, String password, String authType,
2014 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2015 throws PortalException, SystemException {
2016
2017 login = login.trim().toLowerCase();
2018
2019 long userId = GetterUtil.getLong(login);
2020
2021
2023 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2024 if (!Validator.isEmailAddress(login)) {
2025 throw new UserEmailAddressException();
2026 }
2027 }
2028 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2029 if (Validator.isNull(login)) {
2030 throw new UserScreenNameException();
2031 }
2032 }
2033 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2034 if (Validator.isNull(login)) {
2035 throw new UserIdException();
2036 }
2037 }
2038
2039 if (Validator.isNull(password)) {
2040 throw new UserPasswordException(
2041 UserPasswordException.PASSWORD_INVALID);
2042 }
2043
2044 int authResult = Authenticator.FAILURE;
2045
2046
2048 String[] authPipelinePre =
2049 PropsUtil.getArray(PropsKeys.AUTH_PIPELINE_PRE);
2050
2051 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2052 authResult = AuthPipeline.authenticateByEmailAddress(
2053 authPipelinePre, companyId, login, password, headerMap,
2054 parameterMap);
2055 }
2056 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2057 authResult = AuthPipeline.authenticateByScreenName(
2058 authPipelinePre, companyId, login, password, headerMap,
2059 parameterMap);
2060 }
2061 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2062 authResult = AuthPipeline.authenticateByUserId(
2063 authPipelinePre, companyId, userId, password, headerMap,
2064 parameterMap);
2065 }
2066
2067
2069 User user = null;
2070
2071 try {
2072 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2073 user = userPersistence.findByC_EA(companyId, login);
2074 }
2075 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2076 user = userPersistence.findByC_SN(companyId, login);
2077 }
2078 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2079 user = userPersistence.findByC_U(
2080 companyId, GetterUtil.getLong(login));
2081 }
2082 }
2083 catch (NoSuchUserException nsue) {
2084 return Authenticator.DNE;
2085 }
2086
2087 if (user.isDefaultUser()) {
2088 _log.error(
2089 "The default user should never be allowed to authenticate");
2090
2091 return Authenticator.DNE;
2092 }
2093
2094 if (!user.isPasswordEncrypted()) {
2095 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2096 user.setPasswordEncrypted(true);
2097
2098 userPersistence.update(user, false);
2099 }
2100
2101
2104 checkLockout(user);
2105
2106 checkPasswordExpired(user);
2107
2108
2110 if (authResult == Authenticator.SUCCESS) {
2111 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2112 String encPassword = PwdEncryptor.encrypt(
2113 password, user.getPassword());
2114
2115 if (user.getPassword().equals(encPassword)) {
2116 authResult = Authenticator.SUCCESS;
2117 }
2118 else if (GetterUtil.getBoolean(PropsUtil.get(
2119 PropsKeys.AUTH_MAC_ALLOW))) {
2120
2121 try {
2122 MessageDigest digester = MessageDigest.getInstance(
2123 PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2124
2125 digester.update(login.getBytes("UTF8"));
2126
2127 String shardKey =
2128 PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2129
2130 encPassword = Base64.encode(
2131 digester.digest(shardKey.getBytes("UTF8")));
2132
2133 if (password.equals(encPassword)) {
2134 authResult = Authenticator.SUCCESS;
2135 }
2136 else {
2137 authResult = Authenticator.FAILURE;
2138 }
2139 }
2140 catch (NoSuchAlgorithmException nsae) {
2141 throw new SystemException(nsae);
2142 }
2143 catch (UnsupportedEncodingException uee) {
2144 throw new SystemException(uee);
2145 }
2146 }
2147 else {
2148 authResult = Authenticator.FAILURE;
2149 }
2150 }
2151 }
2152
2153
2155 if (authResult == Authenticator.SUCCESS) {
2156 String[] authPipelinePost =
2157 PropsUtil.getArray(PropsKeys.AUTH_PIPELINE_POST);
2158
2159 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2160 authResult = AuthPipeline.authenticateByEmailAddress(
2161 authPipelinePost, companyId, login, password, headerMap,
2162 parameterMap);
2163 }
2164 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2165 authResult = AuthPipeline.authenticateByScreenName(
2166 authPipelinePost, companyId, login, password, headerMap,
2167 parameterMap);
2168 }
2169 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2170 authResult = AuthPipeline.authenticateByUserId(
2171 authPipelinePost, companyId, userId, password, headerMap,
2172 parameterMap);
2173 }
2174 }
2175
2176
2178 if (authResult == Authenticator.FAILURE) {
2179 try {
2180 String[] authFailure =
2181 PropsUtil.getArray(PropsKeys.AUTH_FAILURE);
2182
2183 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2184 AuthPipeline.onFailureByEmailAddress(
2185 authFailure, companyId, login, headerMap, parameterMap);
2186 }
2187 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2188 AuthPipeline.onFailureByScreenName(
2189 authFailure, companyId, login, headerMap, parameterMap);
2190 }
2191 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2192 AuthPipeline.onFailureByUserId(
2193 authFailure, companyId, userId, headerMap,
2194 parameterMap);
2195 }
2196
2197
2199 if (!PortalLDAPUtil.isPasswordPolicyEnabled(
2200 user.getCompanyId())) {
2201
2202 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2203
2204 int failedLoginAttempts = user.getFailedLoginAttempts();
2205 int maxFailures = passwordPolicy.getMaxFailure();
2206
2207 if ((failedLoginAttempts >= maxFailures) &&
2208 (maxFailures != 0)) {
2209
2210 String[] authMaxFailures =
2211 PropsUtil.getArray(PropsKeys.AUTH_MAX_FAILURES);
2212
2213 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2214 AuthPipeline.onMaxFailuresByEmailAddress(
2215 authMaxFailures, companyId, login, headerMap,
2216 parameterMap);
2217 }
2218 else if (authType.equals(
2219 CompanyConstants.AUTH_TYPE_SN)) {
2220
2221 AuthPipeline.onMaxFailuresByScreenName(
2222 authMaxFailures, companyId, login, headerMap,
2223 parameterMap);
2224 }
2225 else if (authType.equals(
2226 CompanyConstants.AUTH_TYPE_ID)) {
2227
2228 AuthPipeline.onMaxFailuresByUserId(
2229 authMaxFailures, companyId, userId, headerMap,
2230 parameterMap);
2231 }
2232 }
2233 }
2234 }
2235 catch (Exception e) {
2236 _log.error(e, e);
2237 }
2238 }
2239
2240 return authResult;
2241 }
2242
2243 protected void copyUserGroupLayouts(long userGroupId, long userId)
2244 throws PortalException, SystemException {
2245
2246 UserGroup userGroup = userGroupLocalService.getUserGroup(userGroupId);
2247 User user = getUserById(userId);
2248
2249 Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
2250
2251 if (userGroup.hasPrivateLayouts()) {
2252 long sourceGroupId = userGroup.getGroup().getGroupId();
2253 long targetGroupId = user.getGroup().getGroupId();
2254
2255 byte[] bytes = layoutLocalService.exportLayouts(
2256 sourceGroupId, true, parameterMap, null, null);
2257
2258 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2259
2260 layoutLocalService.importLayouts(
2261 userId, targetGroupId, true, parameterMap, bais);
2262 }
2263
2264 if (userGroup.hasPublicLayouts()) {
2265 long sourceGroupId = userGroup.getGroup().getGroupId();
2266 long targetGroupId = user.getGroup().getGroupId();
2267
2268 byte[] bytes = layoutLocalService.exportLayouts(
2269 sourceGroupId, false, parameterMap, null, null);
2270
2271 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2272
2273 layoutLocalService.importLayouts(
2274 userId, targetGroupId, false, parameterMap, bais);
2275 }
2276 }
2277
2278 protected void copyUserGroupLayouts(long userGroupId, long userIds[])
2279 throws PortalException, SystemException {
2280
2281 for (long userId : userIds) {
2282 if (!userGroupPersistence.containsUser(userGroupId, userId)) {
2283 copyUserGroupLayouts(userGroupId, userId);
2284 }
2285 }
2286 }
2287
2288 protected void doSendPassword(
2289 long companyId, String emailAddress, String remoteAddr,
2290 String remoteHost, String userAgent)
2291 throws IOException, PortalException, SystemException {
2292
2293 if (!PrefsPropsUtil.getBoolean(
2294 companyId, PropsKeys.COMPANY_SECURITY_SEND_PASSWORD) ||
2295 !PrefsPropsUtil.getBoolean(
2296 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2297
2298 return;
2299 }
2300
2301 emailAddress = emailAddress.trim().toLowerCase();
2302
2303 if (!Validator.isEmailAddress(emailAddress)) {
2304 throw new UserEmailAddressException();
2305 }
2306
2307 Company company = companyPersistence.findByPrimaryKey(companyId);
2308
2309 User user = userPersistence.findByC_EA(companyId, emailAddress);
2310
2311 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2312
2313
2316
2317 String newPassword = null;
2318
2319 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2320 PwdEncryptor.TYPE_NONE)) {
2321
2322 newPassword = PwdToolkitUtil.generate();
2323
2324 boolean passwordReset = false;
2325
2326 if (passwordPolicy.getChangeable() &&
2327 passwordPolicy.getChangeRequired()) {
2328
2329 passwordReset = true;
2330 }
2331
2332 user.setPassword(PwdEncryptor.encrypt(newPassword));
2333 user.setPasswordUnencrypted(newPassword);
2334 user.setPasswordEncrypted(true);
2335 user.setPasswordReset(passwordReset);
2336 user.setPasswordModified(true);
2337 user.setPasswordModifiedDate(new Date());
2338
2339 userPersistence.update(user, false);
2340
2341 user.setPasswordModified(false);
2342 }
2343 else {
2344 newPassword = user.getPassword();
2345 }
2346
2347 String fromName = PrefsPropsUtil.getString(
2348 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2349 String fromAddress = PrefsPropsUtil.getString(
2350 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2351
2352 String toName = user.getFullName();
2353 String toAddress = user.getEmailAddress();
2354
2355 String subject = PrefsPropsUtil.getContent(
2356 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2357 String body = PrefsPropsUtil.getContent(
2358 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2359
2360 subject = StringUtil.replace(
2361 subject,
2362 new String[] {
2363 "[$FROM_ADDRESS$]",
2364 "[$FROM_NAME$]",
2365 "[$PORTAL_URL$]",
2366 "[$REMOTE_ADDRESS$]",
2367 "[$REMOTE_HOST$]",
2368 "[$TO_ADDRESS$]",
2369 "[$TO_NAME$]",
2370 "[$USER_AGENT$]",
2371 "[$USER_ID$]",
2372 "[$USER_PASSWORD$]",
2373 "[$USER_SCREENNAME$]"
2374 },
2375 new String[] {
2376 fromAddress,
2377 fromName,
2378 company.getVirtualHost(),
2379 remoteAddr,
2380 remoteHost,
2381 toAddress,
2382 toName,
2383 HtmlUtil.escape(userAgent),
2384 String.valueOf(user.getUserId()),
2385 newPassword,
2386 user.getScreenName()
2387 });
2388
2389 body = StringUtil.replace(
2390 body,
2391 new String[] {
2392 "[$FROM_ADDRESS$]",
2393 "[$FROM_NAME$]",
2394 "[$PORTAL_URL$]",
2395 "[$REMOTE_ADDRESS$]",
2396 "[$REMOTE_HOST$]",
2397 "[$TO_ADDRESS$]",
2398 "[$TO_NAME$]",
2399 "[$USER_AGENT$]",
2400 "[$USER_ID$]",
2401 "[$USER_PASSWORD$]",
2402 "[$USER_SCREENNAME$]"
2403 },
2404 new String[] {
2405 fromAddress,
2406 fromName,
2407 company.getVirtualHost(),
2408 remoteAddr,
2409 remoteHost,
2410 toAddress,
2411 toName,
2412 HtmlUtil.escape(userAgent),
2413 String.valueOf(user.getUserId()),
2414 newPassword,
2415 user.getScreenName()
2416 });
2417
2418 InternetAddress from = new InternetAddress(fromAddress, fromName);
2419
2420 InternetAddress to = new InternetAddress(toAddress, toName);
2421
2422 MailMessage message = new MailMessage(from, to, subject, body, true);
2423
2424 mailService.sendEmail(message);
2425 }
2426
2427 protected Map<String, String[]> getLayoutTemplatesParameters() {
2428 Map<String, String[]> parameterMap =
2429 new LinkedHashMap<String, String[]>();
2430
2431 parameterMap.put(
2432 PortletDataHandlerKeys.DATA_STRATEGY,
2433 new String[] {PortletDataHandlerKeys.DATA_STRATEGY_MIRROR});
2434 parameterMap.put(
2435 PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
2436 new String[] {Boolean.FALSE.toString()});
2437 parameterMap.put(
2438 PortletDataHandlerKeys.DELETE_PORTLET_DATA,
2439 new String[] {Boolean.FALSE.toString()});
2440 parameterMap.put(
2441 PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
2442 new String[] {PortletDataHandlerKeys.
2443 LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME});
2444 parameterMap.put(
2445 PortletDataHandlerKeys.PERMISSIONS,
2446 new String[] {Boolean.TRUE.toString()});
2447 parameterMap.put(
2448 PortletDataHandlerKeys.PORTLET_DATA,
2449 new String[] {Boolean.TRUE.toString()});
2450 parameterMap.put(
2451 PortletDataHandlerKeys.PORTLET_DATA_ALL,
2452 new String[] {Boolean.TRUE.toString()});
2453 parameterMap.put(
2454 PortletDataHandlerKeys.PORTLET_SETUP,
2455 new String[] {Boolean.TRUE.toString()});
2456 parameterMap.put(
2457 PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2458 new String[] {Boolean.TRUE.toString()});
2459 parameterMap.put(
2460 PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
2461 new String[] {PortletDataHandlerKeys.
2462 PORTLETS_MERGE_MODE_ADD_TO_BOTTOM});
2463 parameterMap.put(
2464 PortletDataHandlerKeys.THEME,
2465 new String[] {Boolean.FALSE.toString()});
2466 parameterMap.put(
2467 PortletDataHandlerKeys.USER_ID_STRATEGY,
2468 new String[] {UserIdStrategy.CURRENT_USER_ID});
2469 parameterMap.put(
2470 PortletDataHandlerKeys.USER_PERMISSIONS,
2471 new String[] {Boolean.FALSE.toString()});
2472
2473 return parameterMap;
2474 }
2475
2476 protected String getScreenName(String screenName) {
2477 return StringUtil.lowerCase(StringUtil.trim(screenName));
2478 }
2479
2480 protected long[] getUserIds(List<User> users) {
2481 long[] userIds = new long[users.size()];
2482
2483 for (int i = 0; i < users.size(); i++) {
2484 User user = users.get(i);
2485
2486 userIds[i] = user.getUserId();
2487 }
2488
2489 return userIds;
2490 }
2491
2492 protected void sendEmail(User user, String password)
2493 throws IOException, PortalException, SystemException {
2494
2495 if (!PrefsPropsUtil.getBoolean(
2496 user.getCompanyId(),
2497 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2498
2499 return;
2500 }
2501
2502 long companyId = user.getCompanyId();
2503
2504 Company company = companyPersistence.findByPrimaryKey(companyId);
2505
2506 String fromName = PrefsPropsUtil.getString(
2507 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2508 String fromAddress = PrefsPropsUtil.getString(
2509 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2510
2511 String toName = user.getFullName();
2512 String toAddress = user.getEmailAddress();
2513
2514 String subject = PrefsPropsUtil.getContent(
2515 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2516 String body = PrefsPropsUtil.getContent(
2517 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
2518
2519 subject = StringUtil.replace(
2520 subject,
2521 new String[] {
2522 "[$FROM_ADDRESS$]",
2523 "[$FROM_NAME$]",
2524 "[$PORTAL_URL$]",
2525 "[$TO_ADDRESS$]",
2526 "[$TO_NAME$]",
2527 "[$USER_ID$]",
2528 "[$USER_PASSWORD$]",
2529 "[$USER_SCREENNAME$]"
2530 },
2531 new String[] {
2532 fromAddress,
2533 fromName,
2534 company.getVirtualHost(),
2535 toAddress,
2536 toName,
2537 String.valueOf(user.getUserId()),
2538 password,
2539 user.getScreenName()
2540 });
2541
2542 body = StringUtil.replace(
2543 body,
2544 new String[] {
2545 "[$FROM_ADDRESS$]",
2546 "[$FROM_NAME$]",
2547 "[$PORTAL_URL$]",
2548 "[$TO_ADDRESS$]",
2549 "[$TO_NAME$]",
2550 "[$USER_ID$]",
2551 "[$USER_PASSWORD$]",
2552 "[$USER_SCREENNAME$]"
2553 },
2554 new String[] {
2555 fromAddress,
2556 fromName,
2557 company.getVirtualHost(),
2558 toAddress,
2559 toName,
2560 String.valueOf(user.getUserId()),
2561 password,
2562 user.getScreenName()
2563 });
2564
2565 InternetAddress from = new InternetAddress(fromAddress, fromName);
2566
2567 InternetAddress to = new InternetAddress(toAddress, toName);
2568
2569 MailMessage message = new MailMessage(from, to, subject, body, true);
2570
2571 mailService.sendEmail(message);
2572 }
2573
2574 protected void validate(
2575 long userId, String screenName, String emailAddress,
2576 String firstName, String lastName, String smsSn)
2577 throws PortalException, SystemException {
2578
2579 User user = userPersistence.findByPrimaryKey(userId);
2580
2581 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
2582 validateScreenName(user.getCompanyId(), userId, screenName);
2583 }
2584
2585 validateEmailAddress(emailAddress);
2586
2587 if (!user.isDefaultUser()) {
2588 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
2589 if (userPersistence.fetchByC_EA(
2590 user.getCompanyId(), emailAddress) != null) {
2591
2592 throw new DuplicateUserEmailAddressException();
2593 }
2594 }
2595
2596 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2597 user.getCompanyId(), PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2598 StringPool.NEW_LINE,
2599 PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2600
2601 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2602 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2603 throw new ReservedUserEmailAddressException();
2604 }
2605 }
2606
2607 if (Validator.isNull(firstName)) {
2608 throw new ContactFirstNameException();
2609 }
2610 else if (Validator.isNull(lastName)) {
2611 throw new ContactLastNameException();
2612 }
2613 }
2614
2615 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2616 throw new UserSmsException();
2617 }
2618 }
2619
2620 protected void validate(
2621 long companyId, long userId, boolean autoPassword, String password1,
2622 String password2, boolean autoScreenName, String screenName,
2623 String emailAddress, String firstName, String lastName,
2624 long[] organizationIds)
2625 throws PortalException, SystemException {
2626
2627 Company company = companyPersistence.findByPrimaryKey(companyId);
2628
2629 if (company.isSystem()) {
2630 return;
2631 }
2632
2633 if (!autoScreenName) {
2634 validateScreenName(companyId, userId, screenName);
2635 }
2636
2637 if (!autoPassword) {
2638 PasswordPolicy passwordPolicy =
2639 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
2640
2641 PwdToolkitUtil.validate(
2642 companyId, 0, password1, password2, passwordPolicy);
2643 }
2644
2645 validateEmailAddress(emailAddress);
2646
2647 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
2648
2649 if (user != null) {
2650 throw new DuplicateUserEmailAddressException();
2651 }
2652
2653 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2654 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2655 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2656
2657 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2658 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2659 throw new ReservedUserEmailAddressException();
2660 }
2661 }
2662
2663 if (Validator.isNull(firstName)) {
2664 throw new ContactFirstNameException();
2665 }
2666 else if (Validator.isNull(lastName)) {
2667 throw new ContactLastNameException();
2668 }
2669 }
2670
2671 protected void validateEmailAddress(String emailAddress)
2672 throws PortalException {
2673
2674 if (!Validator.isEmailAddress(emailAddress) ||
2675 emailAddress.startsWith("root@") ||
2676 emailAddress.startsWith("postmaster@")) {
2677
2678 throw new UserEmailAddressException();
2679 }
2680 }
2681
2682 protected void validatePassword(
2683 long companyId, long userId, String password1, String password2)
2684 throws PortalException, SystemException {
2685
2686 if (Validator.isNull(password1) || Validator.isNull(password2)) {
2687 throw new UserPasswordException(
2688 UserPasswordException.PASSWORD_INVALID);
2689 }
2690
2691 if (!password1.equals(password2)) {
2692 throw new UserPasswordException(
2693 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2694 }
2695
2696 PasswordPolicy passwordPolicy =
2697 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
2698
2699 PwdToolkitUtil.validate(
2700 companyId, userId, password1, password2, passwordPolicy);
2701 }
2702
2703 protected void validateScreenName(
2704 long companyId, long userId, String screenName)
2705 throws PortalException, SystemException {
2706
2707 if (Validator.isNull(screenName)) {
2708 throw new UserScreenNameException();
2709 }
2710
2711 ScreenNameValidator screenNameValidator =
2712 (ScreenNameValidator)InstancePool.get(
2713 PropsValues.USERS_SCREEN_NAME_VALIDATOR);
2714
2715 if (screenNameValidator != null) {
2716 if (!screenNameValidator.validate(companyId, screenName)) {
2717 throw new UserScreenNameException();
2718 }
2719 }
2720
2721 if (Validator.isNumber(screenName) &&
2722 !screenName.equals(String.valueOf(userId))) {
2723
2724 throw new UserScreenNameException();
2725 }
2726
2727 for (char c : screenName.toCharArray()) {
2728 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
2729 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
2730 (c != CharPool.UNDERLINE)) {
2731
2732 throw new UserScreenNameException();
2733 }
2734 }
2735
2736 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2737
2738 for (int i = 0; i < anonymousNames.length; i++) {
2739 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2740 throw new UserScreenNameException();
2741 }
2742 }
2743
2744 User user = userPersistence.fetchByC_SN(companyId, screenName);
2745
2746 if (user != null) {
2747 throw new DuplicateUserScreenNameException();
2748 }
2749
2750 String friendlyURL = StringPool.SLASH + screenName;
2751
2752 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
2753
2754 if (group != null) {
2755 throw new DuplicateUserScreenNameException();
2756 }
2757
2758 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
2759
2760 if (exceptionType != -1) {
2761 throw new UserScreenNameException(
2762 new GroupFriendlyURLException(exceptionType));
2763 }
2764
2765 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2766 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
2767 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
2768
2769 for (int i = 0; i < reservedScreenNames.length; i++) {
2770 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2771 throw new ReservedUserScreenNameException();
2772 }
2773 }
2774 }
2775
2776 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
2777
2778 private static Map<Long, User> _defaultUsers =
2779 new ConcurrentHashMap<Long, User>();
2780
2781}