1
22
23 package com.liferay.portal.service.impl;
24
25 import com.liferay.counter.service.CounterLocalServiceUtil;
26 import com.liferay.mail.service.MailServiceUtil;
27 import com.liferay.portal.ContactBirthdayException;
28 import com.liferay.portal.ContactFirstNameException;
29 import com.liferay.portal.ContactLastNameException;
30 import com.liferay.portal.DuplicateUserEmailAddressException;
31 import com.liferay.portal.DuplicateUserScreenNameException;
32 import com.liferay.portal.ModelListenerException;
33 import com.liferay.portal.NoSuchContactException;
34 import com.liferay.portal.NoSuchGroupException;
35 import com.liferay.portal.NoSuchRoleException;
36 import com.liferay.portal.NoSuchUserException;
37 import com.liferay.portal.NoSuchUserGroupException;
38 import com.liferay.portal.OrganizationParentException;
39 import com.liferay.portal.PasswordExpiredException;
40 import com.liferay.portal.PortalException;
41 import com.liferay.portal.RequiredUserException;
42 import com.liferay.portal.ReservedUserEmailAddressException;
43 import com.liferay.portal.ReservedUserScreenNameException;
44 import com.liferay.portal.SystemException;
45 import com.liferay.portal.UserEmailAddressException;
46 import com.liferay.portal.UserIdException;
47 import com.liferay.portal.UserLockoutException;
48 import com.liferay.portal.UserPasswordException;
49 import com.liferay.portal.UserPortraitException;
50 import com.liferay.portal.UserScreenNameException;
51 import com.liferay.portal.UserSmsException;
52 import com.liferay.portal.kernel.language.LanguageUtil;
53 import com.liferay.portal.kernel.mail.MailMessage;
54 import com.liferay.portal.kernel.util.Base64;
55 import com.liferay.portal.kernel.util.GetterUtil;
56 import com.liferay.portal.kernel.util.InstancePool;
57 import com.liferay.portal.kernel.util.KeyValuePair;
58 import com.liferay.portal.kernel.util.OrderByComparator;
59 import com.liferay.portal.kernel.util.StringPool;
60 import com.liferay.portal.kernel.util.StringUtil;
61 import com.liferay.portal.kernel.util.Validator;
62 import com.liferay.portal.model.Company;
63 import com.liferay.portal.model.Contact;
64 import com.liferay.portal.model.Group;
65 import com.liferay.portal.model.Organization;
66 import com.liferay.portal.model.PasswordPolicy;
67 import com.liferay.portal.model.Role;
68 import com.liferay.portal.model.User;
69 import com.liferay.portal.model.UserGroup;
70 import com.liferay.portal.model.impl.CompanyImpl;
71 import com.liferay.portal.model.impl.ContactImpl;
72 import com.liferay.portal.model.impl.ResourceImpl;
73 import com.liferay.portal.model.impl.RoleImpl;
74 import com.liferay.portal.model.impl.UserImpl;
75 import com.liferay.portal.security.auth.AuthPipeline;
76 import com.liferay.portal.security.auth.Authenticator;
77 import com.liferay.portal.security.auth.PrincipalException;
78 import com.liferay.portal.security.auth.ScreenNameGenerator;
79 import com.liferay.portal.security.auth.ScreenNameValidator;
80 import com.liferay.portal.security.ldap.PortalLDAPUtil;
81 import com.liferay.portal.security.permission.PermissionCacheUtil;
82 import com.liferay.portal.security.pwd.PwdEncryptor;
83 import com.liferay.portal.security.pwd.PwdToolkitUtil;
84 import com.liferay.portal.service.ContactLocalServiceUtil;
85 import com.liferay.portal.service.GroupLocalServiceUtil;
86 import com.liferay.portal.service.OrganizationLocalServiceUtil;
87 import com.liferay.portal.service.PasswordPolicyLocalServiceUtil;
88 import com.liferay.portal.service.PasswordPolicyRelLocalServiceUtil;
89 import com.liferay.portal.service.PasswordTrackerLocalServiceUtil;
90 import com.liferay.portal.service.ResourceLocalServiceUtil;
91 import com.liferay.portal.service.RoleLocalServiceUtil;
92 import com.liferay.portal.service.SubscriptionLocalServiceUtil;
93 import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
94 import com.liferay.portal.service.UserIdMapperLocalServiceUtil;
95 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
96 import com.liferay.portal.service.persistence.CompanyUtil;
97 import com.liferay.portal.service.persistence.ContactUtil;
98 import com.liferay.portal.service.persistence.GroupFinder;
99 import com.liferay.portal.service.persistence.GroupUtil;
100 import com.liferay.portal.service.persistence.OrganizationUtil;
101 import com.liferay.portal.service.persistence.PermissionUserFinder;
102 import com.liferay.portal.service.persistence.RoleFinder;
103 import com.liferay.portal.service.persistence.RoleUtil;
104 import com.liferay.portal.service.persistence.UserFinder;
105 import com.liferay.portal.service.persistence.UserGroupFinder;
106 import com.liferay.portal.service.persistence.UserGroupUtil;
107 import com.liferay.portal.service.persistence.UserUtil;
108 import com.liferay.portal.util.PortalUtil;
109 import com.liferay.portal.util.PrefsPropsUtil;
110 import com.liferay.portal.util.PropsUtil;
111 import com.liferay.portlet.blogs.service.BlogsStatsUserLocalServiceUtil;
112 import com.liferay.portlet.documentlibrary.service.DLFileRankLocalServiceUtil;
113 import com.liferay.portlet.messageboards.service.MBBanLocalServiceUtil;
114 import com.liferay.portlet.messageboards.service.MBMessageFlagLocalServiceUtil;
115 import com.liferay.portlet.messageboards.service.MBStatsUserLocalServiceUtil;
116 import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
117 import com.liferay.util.Encryptor;
118 import com.liferay.util.EncryptorException;
119
120 import java.io.IOException;
121 import java.io.UnsupportedEncodingException;
122
123 import java.rmi.RemoteException;
124
125 import java.security.MessageDigest;
126 import java.security.NoSuchAlgorithmException;
127
128 import java.util.ArrayList;
129 import java.util.Date;
130 import java.util.LinkedHashMap;
131 import java.util.List;
132 import java.util.Locale;
133 import java.util.Map;
134
135 import javax.mail.internet.InternetAddress;
136
137 import org.apache.commons.logging.Log;
138 import org.apache.commons.logging.LogFactory;
139
140
147 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
148
149 public void addGroupUsers(long groupId, long[] userIds)
150 throws PortalException, SystemException {
151
152 GroupUtil.addUsers(groupId, userIds);
153
154
156 Group group = GroupLocalServiceUtil.getGroup(groupId);
157
158 Role role = RoleLocalServiceUtil.getRole(
159 group.getCompanyId(), RoleImpl.COMMUNITY_MEMBER);
160
161 for (int i = 0; i < userIds.length; i++) {
162 long userId = userIds[i];
163
164 UserGroupRoleLocalServiceUtil.addUserGroupRoles(
165 userId, groupId, new long[] {role.getRoleId()});
166 }
167
168
170 PermissionCacheUtil.clearCache();
171 }
172
173 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
174 throws PortalException, SystemException {
175
176 PasswordPolicyRelLocalServiceUtil.addPasswordPolicyRels(
177 passwordPolicyId, User.class.getName(), userIds);
178 }
179
180 public void addRoleUsers(long roleId, long[] userIds)
181 throws PortalException, SystemException {
182
183 RoleUtil.addUsers(roleId, userIds);
184
185 PermissionCacheUtil.clearCache();
186 }
187
188 public void addUserGroupUsers(long userGroupId, long[] userIds)
189 throws PortalException, SystemException {
190
191 UserGroupUtil.addUsers(userGroupId, userIds);
192
193 PermissionCacheUtil.clearCache();
194 }
195
196 public User addUser(
197 long creatorUserId, long companyId, boolean autoPassword,
198 String password1, String password2, boolean autoScreenName,
199 String screenName, String emailAddress, Locale locale,
200 String firstName, String middleName, String lastName, int prefixId,
201 int suffixId, boolean male, int birthdayMonth, int birthdayDay,
202 int birthdayYear, String jobTitle, long organizationId,
203 long locationId, boolean sendEmail)
204 throws PortalException, SystemException {
205
206
208 Company company = CompanyUtil.findByPrimaryKey(companyId);
209 screenName = screenName.trim().toLowerCase();
210 emailAddress = emailAddress.trim().toLowerCase();
211 Date now = new Date();
212
213 boolean alwaysAutoScreenName = GetterUtil.getBoolean(
214 PropsUtil.get(PropsUtil.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE));
215
216 if (alwaysAutoScreenName) {
217 autoScreenName = true;
218 }
219
220 validate(
221 companyId, autoPassword, password1, password2, autoScreenName,
222 screenName, emailAddress, firstName, lastName, organizationId,
223 locationId);
224
225 validateOrganizations(companyId, organizationId, locationId);
226
227 if (autoPassword) {
228 password1 = PwdToolkitUtil.generate();
229 }
230
231 long userId = CounterLocalServiceUtil.increment();
232
233 if (autoScreenName) {
234 ScreenNameGenerator screenNameGenerator =
235 (ScreenNameGenerator)InstancePool.get(
236 PropsUtil.get(PropsUtil.USERS_SCREEN_NAME_GENERATOR));
237
238 try {
239 screenName = screenNameGenerator.generate(companyId, userId);
240 }
241 catch (Exception e) {
242 throw new SystemException(e);
243 }
244 }
245
246 User defaultUser = getDefaultUser(companyId);
247
248 String fullName = UserImpl.getFullName(firstName, middleName, lastName);
249
250 String greeting =
251 LanguageUtil.get(companyId, locale, "welcome") + ", " + fullName +
252 "!";
253
254 User user = UserUtil.create(userId);
255
256 user.setCompanyId(companyId);
257 user.setCreateDate(now);
258 user.setModifiedDate(now);
259 user.setDefaultUser(false);
260 user.setContactId(CounterLocalServiceUtil.increment());
261 user.setPassword(PwdEncryptor.encrypt(password1));
262 user.setPasswordUnencrypted(password1);
263 user.setPasswordEncrypted(true);
264 user.setPasswordReset(false);
265 user.setScreenName(screenName);
266 user.setEmailAddress(emailAddress);
267 user.setLanguageId(locale.toString());
268 user.setTimeZoneId(defaultUser.getTimeZoneId());
269 user.setGreeting(greeting);
270 user.setActive(true);
271
272 UserUtil.update(user);
273
274
276 String creatorUserName = StringPool.BLANK;
277
278 if (creatorUserId <= 0) {
279 creatorUserId = user.getUserId();
280
281
284 }
286 else {
287 User creatorUser = UserUtil.findByPrimaryKey(creatorUserId);
288
289 creatorUserName = creatorUser.getFullName();
290 }
291
292 ResourceLocalServiceUtil.addResources(
293 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
294 false, false, false);
295
296
298 if (user.hasCompanyMx()) {
299 try {
300 MailServiceUtil.addUser(
301 userId, password1, firstName, middleName, lastName,
302 emailAddress);
303 }
304 catch (RemoteException re) {
305 throw new SystemException(re);
306 }
307 }
308
309
311 Date birthday = PortalUtil.getDate(
312 birthdayMonth, birthdayDay, birthdayYear,
313 new ContactBirthdayException());
314
315 Contact contact = ContactUtil.create(user.getContactId());
316
317 contact.setCompanyId(user.getCompanyId());
318 contact.setUserId(creatorUserId);
319 contact.setUserName(creatorUserName);
320 contact.setCreateDate(now);
321 contact.setModifiedDate(now);
322 contact.setAccountId(company.getAccountId());
323 contact.setParentContactId(ContactImpl.DEFAULT_PARENT_CONTACT_ID);
324 contact.setFirstName(firstName);
325 contact.setMiddleName(middleName);
326 contact.setLastName(lastName);
327 contact.setPrefixId(prefixId);
328 contact.setSuffixId(suffixId);
329 contact.setMale(male);
330 contact.setBirthday(birthday);
331 contact.setJobTitle(jobTitle);
332
333 ContactUtil.update(contact);
334
335
337 updateOrganizations(userId, organizationId, locationId);
338
339
341 GroupLocalServiceUtil.addGroup(
342 user.getUserId(), User.class.getName(), user.getUserId(), null,
343 null, null, null, true);
344
345
347 List groups = new ArrayList();
348
349 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
350 companyId, PropsUtil.ADMIN_DEFAULT_GROUP_NAMES);
351
352 for (int i = 0; i < defaultGroupNames.length; i++) {
353 try {
354 Group group = GroupFinder.findByC_N(
355 companyId, defaultGroupNames[i]);
356
357 groups.add(group);
358 }
359 catch (NoSuchGroupException nsge) {
360 }
361 }
362
363 UserUtil.setGroups(userId, groups);
364
365
367 List roles = new ArrayList();
368
369 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
370 companyId, PropsUtil.ADMIN_DEFAULT_ROLE_NAMES);
371
372 for (int i = 0; i < defaultRoleNames.length; i++) {
373 try {
374 Role role = RoleFinder.findByC_N(
375 companyId, defaultRoleNames[i]);
376
377 roles.add(role);
378 }
379 catch (NoSuchRoleException nsge) {
380 }
381 }
382
383 UserUtil.setRoles(userId, roles);
384
385
387 List userGroups = new ArrayList();
388
389 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
390 companyId, PropsUtil.ADMIN_DEFAULT_USER_GROUP_NAMES);
391
392 for (int i = 0; i < defaultUserGroupNames.length; i++) {
393 try {
394 UserGroup userGroup = UserGroupFinder.findByC_N(
395 companyId, defaultUserGroupNames[i]);
396
397 userGroups.add(userGroup);
398 }
399 catch (NoSuchUserGroupException nsuge) {
400 }
401 }
402
403 UserUtil.setUserGroups(userId, userGroups);
404
405
407 if (sendEmail) {
408 sendEmail(user, password1);
409 }
410
411 return user;
412 }
413
414 public int authenticateByEmailAddress(
415 long companyId, String emailAddress, String password,
416 Map headerMap, Map parameterMap)
417 throws PortalException, SystemException {
418
419 return authenticate(
420 companyId, emailAddress, password, CompanyImpl.AUTH_TYPE_EA,
421 headerMap, parameterMap);
422 }
423
424 public int authenticateByScreenName(
425 long companyId, String screenName, String password, Map headerMap,
426 Map parameterMap)
427 throws PortalException, SystemException {
428
429 return authenticate(
430 companyId, screenName, password, CompanyImpl.AUTH_TYPE_SN,
431 headerMap, parameterMap);
432 }
433
434 public int authenticateByUserId(
435 long companyId, long userId, String password, Map headerMap,
436 Map parameterMap)
437 throws PortalException, SystemException {
438
439 return authenticate(
440 companyId, String.valueOf(userId), password,
441 CompanyImpl.AUTH_TYPE_ID, headerMap, parameterMap);
442 }
443
444 public boolean authenticateForJAAS(long userId, String encPwd)
445 throws PortalException, SystemException {
446
447 try {
448 User user = UserUtil.findByPrimaryKey(userId);
449
450 if (user.isDefaultUser()) {
451 _log.error(
452 "The default user should never be allowed to authenticate");
453
454 return false;
455 }
456
457 String password = user.getPassword();
458
459 if (user.isPasswordEncrypted()) {
460 if (password.equals(encPwd)) {
461 return true;
462 }
463
464 if (!GetterUtil.getBoolean(PropsUtil.get(
465 PropsUtil.PORTAL_JAAS_STRICT_PASSWORD))) {
466
467 encPwd = PwdEncryptor.encrypt(encPwd, password);
468
469 if (password.equals(encPwd)) {
470 return true;
471 }
472 }
473 }
474 else {
475 if (!GetterUtil.getBoolean(PropsUtil.get(
476 PropsUtil.PORTAL_JAAS_STRICT_PASSWORD))) {
477
478 if (password.equals(encPwd)) {
479 return true;
480 }
481 }
482
483 password = PwdEncryptor.encrypt(password);
484
485 if (password.equals(encPwd)) {
486 return true;
487 }
488 }
489 }
490 catch (Exception e) {
491 _log.error(e);
492 }
493
494 return false;
495 }
496
497 public void checkLockout(User user)
498 throws PortalException, SystemException {
499
500 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
501 return;
502 }
503
504 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
505
506 if (passwordPolicy.isLockout()) {
507
508
510 Date now = new Date();
511 int failedLoginAttempts = user.getFailedLoginAttempts();
512
513 if (failedLoginAttempts > 0) {
514 long failedLoginTime = user.getLastFailedLoginDate().getTime();
515 long elapsedTime = now.getTime() - failedLoginTime;
516 long requiredElapsedTime =
517 passwordPolicy.getResetFailureCount() * 1000;
518
519 if ((requiredElapsedTime != 0) &&
520 (elapsedTime > requiredElapsedTime)) {
521
522 user.setLastFailedLoginDate(null);
523 user.setFailedLoginAttempts(0);
524 }
525 }
526
527
529 if (user.isLockout()) {
530 long lockoutTime = user.getLockoutDate().getTime();
531 long elapsedTime = now.getTime() - lockoutTime;
532 long requiredElapsedTime =
533 passwordPolicy.getLockoutDuration() * 1000;
534
535 if ((requiredElapsedTime != 0) &&
536 (elapsedTime > requiredElapsedTime)) {
537
538 user.setLockout(false);
539 user.setLockoutDate(null);
540 }
541 }
542
543 if (user.isLockout()) {
544 throw new UserLockoutException();
545 }
546 }
547 }
548
549 public void checkLoginFailure(User user)
550 throws PortalException, SystemException {
551
552 Date now = new Date();
553
554 int failedLoginAttempts = user.getFailedLoginAttempts();
555
556 user.setLastFailedLoginDate(now);
557 user.setFailedLoginAttempts(++failedLoginAttempts);
558
559 UserUtil.update(user);
560 }
561
562 public void checkLoginFailureByEmailAddress(
563 long companyId, String emailAddress)
564 throws PortalException, SystemException {
565
566 User user = getUserByEmailAddress(companyId, emailAddress);
567
568 checkLoginFailure(user);
569 }
570
571 public void checkLoginFailureById(long userId)
572 throws PortalException, SystemException {
573
574 User user = getUserById(userId);
575
576 checkLoginFailure(user);
577 }
578
579 public void checkLoginFailureByScreenName(long companyId, String screenName)
580 throws PortalException, SystemException {
581
582 User user = getUserByScreenName(companyId, screenName);
583
584 checkLoginFailure(user);
585 }
586
587 public void checkPasswordExpired(User user)
588 throws PortalException, SystemException {
589
590 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
591 return;
592 }
593
594 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
595
596
598 if (isPasswordExpired(user)) {
599 int graceLoginCount = user.getGraceLoginCount();
600
601 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
602 user.setGraceLoginCount(++graceLoginCount);
603
604 UserUtil.update(user);
605 }
606 else {
607 throw new PasswordExpiredException();
608 }
609 }
610
611
613 if (isPasswordExpiringSoon(user)) {
614 user.setPasswordReset(true);
615
616 UserUtil.update(user);
617 }
618
619
621 if (passwordPolicy.isChangeable() &&
622 passwordPolicy.isChangeRequired()) {
623
624 if (user.getLastLoginDate() == null) {
625 boolean passwordReset = false;
626
627 if (passwordPolicy.isChangeable() &&
628 passwordPolicy.isChangeRequired()) {
629
630 passwordReset = true;
631 }
632
633 user.setPasswordReset(passwordReset);
634
635 UserUtil.update(user);
636 }
637 }
638 }
639
640 public void clearUserGroupUsers(long userGroupId)
641 throws PortalException, SystemException {
642
643 UserGroupUtil.clearUsers(userGroupId);
644
645 PermissionCacheUtil.clearCache();
646 }
647
648 public KeyValuePair decryptUserId(
649 long companyId, String name, String password)
650 throws PortalException, SystemException {
651
652 Company company = CompanyUtil.findByPrimaryKey(companyId);
653
654 try {
655 name = Encryptor.decrypt(company.getKeyObj(), name);
656 }
657 catch (EncryptorException ee) {
658 throw new SystemException(ee);
659 }
660
661 long userId = GetterUtil.getLong(name);
662
663 User user = UserUtil.findByPrimaryKey(userId);
664
665 try {
666 password = Encryptor.decrypt(company.getKeyObj(), password);
667 }
668 catch (EncryptorException ee) {
669 throw new SystemException(ee);
670 }
671
672 String encPwd = PwdEncryptor.encrypt(password);
673
674 if (user.getPassword().equals(encPwd)) {
675 if (isPasswordExpired(user)) {
676 user.setPasswordReset(true);
677
678 UserUtil.update(user);
679 }
680
681 return new KeyValuePair(name, password);
682 }
683 else {
684 throw new PrincipalException();
685 }
686 }
687
688 public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
689 throws PortalException, SystemException {
690
691 PasswordPolicyRelLocalServiceUtil.deletePasswordPolicyRel(
692 passwordPolicyId, User.class.getName(), userId);
693 }
694
695 public void deleteRoleUser(long roleId, long userId)
696 throws PortalException, SystemException {
697
698 RoleUtil.removeUser(roleId, userId);
699
700 PermissionCacheUtil.clearCache();
701 }
702
703 public void deleteUser(long userId)
704 throws PortalException, SystemException {
705
706 if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.USERS_DELETE))) {
707 throw new RequiredUserException();
708 }
709
710 User user = UserUtil.findByPrimaryKey(userId);
711
712
714 Group group = user.getGroup();
715
716 GroupLocalServiceUtil.deleteGroup(group.getGroupId());
717
718
720 ImageLocalUtil.deleteImage(user.getPortraitId());
721
722
724 PasswordPolicyRelLocalServiceUtil.deletePasswordPolicyRel(
725 User.class.getName(), userId);
726
727
729 PasswordTrackerLocalServiceUtil.deletePasswordTrackers(userId);
730
731
733 SubscriptionLocalServiceUtil.deleteSubscriptions(userId);
734
735
737 UserIdMapperLocalServiceUtil.deleteUserIdMappers(userId);
738
739
741 BlogsStatsUserLocalServiceUtil.deleteStatsUserByUserId(userId);
742
743
745 DLFileRankLocalServiceUtil.deleteFileRanks(userId);
746
747
749 MBBanLocalServiceUtil.deleteBansByBanUserId(userId);
750 MBMessageFlagLocalServiceUtil.deleteFlags(userId);
751 MBStatsUserLocalServiceUtil.deleteStatsUserByUserId(userId);
752
753
755 ShoppingCartLocalServiceUtil.deleteUserCarts(userId);
756
757
759 try {
760 MailServiceUtil.deleteUser(userId);
761 }
762 catch (RemoteException re) {
763 throw new SystemException(re);
764 }
765
766
768 ContactLocalServiceUtil.deleteContact(user.getContactId());
769
770
772 ResourceLocalServiceUtil.deleteResource(
773 user.getCompanyId(), User.class.getName(),
774 ResourceImpl.SCOPE_INDIVIDUAL, user.getUserId());
775
776
778 UserGroupRoleLocalServiceUtil.deleteUserGroupRolesByUserId(userId);
779
780
782 UserUtil.remove(userId);
783
784
786 PermissionCacheUtil.clearCache();
787 }
788
789 public String encryptUserId(String name)
790 throws PortalException, SystemException {
791
792 long userId = GetterUtil.getLong(name);
793
794 User user = UserUtil.findByPrimaryKey(userId);
795
796 Company company = CompanyUtil.findByPrimaryKey(user.getCompanyId());
797
798 try {
799 return Encryptor.encrypt(company.getKeyObj(), name);
800 }
801 catch (EncryptorException ee) {
802 throw new SystemException(ee);
803 }
804 }
805
806 public User getDefaultUser(long companyId)
807 throws PortalException, SystemException {
808
809 return UserUtil.findByC_DU(companyId, true);
810 }
811
812 public long getDefaultUserId(long companyId)
813 throws PortalException, SystemException {
814
815 User user = UserUtil.findByC_DU(companyId, true);
816
817 return user.getUserId();
818 }
819
820 public List getGroupUsers(long groupId)
821 throws PortalException, SystemException {
822
823 return GroupUtil.getUsers(groupId);
824 }
825
826 public List getPermissionUsers(
827 long companyId, long groupId, String name, String primKey,
828 String actionId, String firstName, String middleName,
829 String lastName, String emailAddress, boolean andOperator,
830 int begin, int end)
831 throws PortalException, SystemException {
832
833 int orgGroupPermissionsCount =
834 PermissionUserFinder.countByOrgGroupPermissions(
835 companyId, name, primKey, actionId);
836
837 if (orgGroupPermissionsCount > 0) {
838 return PermissionUserFinder.findByUserAndOrgGroupPermission(
839 companyId, name, primKey, actionId, firstName, middleName,
840 lastName, emailAddress, andOperator, begin, end);
841 }
842 else {
843 return PermissionUserFinder.findByPermissionAndRole(
844 companyId, groupId, name, primKey, actionId, firstName,
845 middleName, lastName, emailAddress, andOperator, begin, end);
846 }
847 }
848
849 public int getPermissionUsersCount(
850 long companyId, long groupId, String name, String primKey,
851 String actionId, String firstName, String middleName,
852 String lastName, String emailAddress, boolean andOperator)
853 throws PortalException, SystemException {
854
855 int orgGroupPermissionsCount =
856 PermissionUserFinder.countByOrgGroupPermissions(
857 companyId, name, primKey, actionId);
858
859 if (orgGroupPermissionsCount > 0) {
860 return PermissionUserFinder.countByUserAndOrgGroupPermission(
861 companyId, name, primKey, actionId, firstName, middleName,
862 lastName, emailAddress, andOperator);
863 }
864 else {
865 return PermissionUserFinder.countByPermissionAndRole(
866 companyId, groupId, name, primKey, actionId, firstName,
867 middleName, lastName, emailAddress, andOperator);
868 }
869 }
870
871 public List getRoleUsers(long roleId)
872 throws PortalException, SystemException {
873
874 return RoleUtil.getUsers(roleId);
875 }
876
877 public List getUserGroupUsers(long userGroupId)
878 throws PortalException, SystemException {
879
880 return UserGroupUtil.getUsers(userGroupId);
881 }
882
883 public User getUserByContactId(long contactId)
884 throws PortalException, SystemException {
885
886 return UserUtil.findByContactId(contactId);
887 }
888
889 public User getUserByEmailAddress(long companyId, String emailAddress)
890 throws PortalException, SystemException {
891
892 emailAddress = emailAddress.trim().toLowerCase();
893
894 return UserUtil.findByC_EA(companyId, emailAddress);
895 }
896
897 public User getUserById(long userId)
898 throws PortalException, SystemException {
899
900 return UserUtil.findByPrimaryKey(userId);
901 }
902
903 public User getUserById(long companyId, long userId)
904 throws PortalException, SystemException {
905
906 return UserUtil.findByC_U(companyId, userId);
907 }
908
909 public User getUserByPortraitId(long portraitId)
910 throws PortalException, SystemException {
911
912 return UserUtil.findByPortraitId(portraitId);
913 }
914
915 public User getUserByScreenName(long companyId, String screenName)
916 throws PortalException, SystemException {
917
918 screenName = screenName.trim().toLowerCase();
919
920 return UserUtil.findByC_SN(companyId, screenName);
921 }
922
923 public long getUserIdByEmailAddress(long companyId, String emailAddress)
924 throws PortalException, SystemException {
925
926 emailAddress = emailAddress.trim().toLowerCase();
927
928 User user = UserUtil.findByC_EA(companyId, emailAddress);
929
930 return user.getUserId();
931 }
932
933 public long getUserIdByScreenName(long companyId, String screenName)
934 throws PortalException, SystemException {
935
936 screenName = screenName.trim().toLowerCase();
937
938 User user = UserUtil.findByC_SN(companyId, screenName);
939
940 return user.getUserId();
941 }
942
943 public boolean hasGroupUser(long groupId, long userId)
944 throws PortalException, SystemException {
945
946 return GroupUtil.containsUser(groupId, userId);
947 }
948
949 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
950 throws PortalException, SystemException {
951
952 return PasswordPolicyRelLocalServiceUtil.hasPasswordPolicyRel(
953 passwordPolicyId, User.class.getName(), userId);
954 }
955
956 public boolean hasRoleUser(long roleId, long userId)
957 throws PortalException, SystemException {
958
959 return RoleUtil.containsUser(roleId, userId);
960 }
961
962 public boolean hasUserGroupUser(long userGroupId, long userId)
963 throws PortalException, SystemException {
964
965 return UserGroupUtil.containsUser(userGroupId, userId);
966 }
967
968 public boolean isPasswordExpired(User user)
969 throws PortalException, SystemException {
970
971 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
972
973 if (passwordPolicy.getExpireable()) {
974 Date now = new Date();
975
976 if (user.getPasswordModifiedDate() == null) {
977 user.setPasswordModifiedDate(now);
978
979 UserUtil.update(user);
980 }
981
982 long passwordStartTime = user.getPasswordModifiedDate().getTime();
983 long elapsedTime = now.getTime() - passwordStartTime;
984
985 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
986 return true;
987 }
988 else {
989 return false;
990 }
991 }
992
993 return false;
994 }
995
996 public boolean isPasswordExpiringSoon(User user)
997 throws PortalException, SystemException {
998
999 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1000
1001 if (passwordPolicy.isExpireable()) {
1002 Date now = new Date();
1003
1004 if (user.getPasswordModifiedDate() == null) {
1005 user.setPasswordModifiedDate(now);
1006
1007 UserUtil.update(user);
1008 }
1009
1010 long timeModified = user.getPasswordModifiedDate().getTime();
1011 long passwordExpiresOn =
1012 (passwordPolicy.getMaxAge() * 1000) + timeModified;
1013
1014 long timeStartWarning =
1015 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1016
1017 if (now.getTime() > timeStartWarning) {
1018 return true;
1019 }
1020 else {
1021 return false;
1022 }
1023 }
1024
1025 return false;
1026 }
1027
1028 public List search(
1029 long companyId, String keywords, Boolean active,
1030 LinkedHashMap params, int begin, int end, OrderByComparator obc)
1031 throws SystemException {
1032
1033 return UserFinder.findByKeywords(
1034 companyId, keywords, active, params, begin, end, obc);
1035 }
1036
1037 public List search(
1038 long companyId, String firstName, String middleName,
1039 String lastName, String screenName, String emailAddress,
1040 Boolean active, LinkedHashMap params, boolean andSearch, int begin,
1041 int end, OrderByComparator obc)
1042 throws SystemException {
1043
1044 return UserFinder.findByC_FN_MN_LN_SN_EA_A(
1045 companyId, firstName, middleName, lastName, screenName,
1046 emailAddress, active, params, andSearch, begin, end, obc);
1047 }
1048
1049 public int searchCount(
1050 long companyId, String keywords, Boolean active,
1051 LinkedHashMap params)
1052 throws SystemException {
1053
1054 return UserFinder.countByKeywords(companyId, keywords, active, params);
1055 }
1056
1057 public int searchCount(
1058 long companyId, String firstName, String middleName,
1059 String lastName, String screenName, String emailAddress,
1060 Boolean active, LinkedHashMap params, boolean andSearch)
1061 throws SystemException {
1062
1063 return UserFinder.countByC_FN_MN_LN_SN_EA_A(
1064 companyId, firstName, middleName, lastName, screenName,
1065 emailAddress, active, params, andSearch);
1066 }
1067
1068 public void sendPassword(
1069 long companyId, String emailAddress, String remoteAddr,
1070 String remoteHost, String userAgent)
1071 throws PortalException, SystemException {
1072
1073 if (!PrefsPropsUtil.getBoolean(
1074 companyId, PropsUtil.COMPANY_SECURITY_SEND_PASSWORD) ||
1075 !PrefsPropsUtil.getBoolean(
1076 companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
1077
1078 return;
1079 }
1080
1081 emailAddress = emailAddress.trim().toLowerCase();
1082
1083 if (!Validator.isEmailAddress(emailAddress)) {
1084 throw new UserEmailAddressException();
1085 }
1086
1087 Company company = CompanyUtil.findByPrimaryKey(companyId);
1088
1089 User user = UserUtil.findByC_EA(companyId, emailAddress);
1090
1091 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1092
1093
1096
1097 String newPassword = null;
1098
1099 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
1100 PwdEncryptor.TYPE_NONE)) {
1101
1102 newPassword = PwdToolkitUtil.generate();
1103
1104 boolean passwordReset = false;
1105
1106 if (passwordPolicy.getChangeable() &&
1107 passwordPolicy.getChangeRequired()) {
1108
1109 passwordReset = true;
1110 }
1111
1112 user.setPassword(PwdEncryptor.encrypt(newPassword));
1113 user.setPasswordUnencrypted(newPassword);
1114 user.setPasswordEncrypted(true);
1115 user.setPasswordReset(passwordReset);
1116
1117 UserUtil.update(user);
1118 }
1119 else {
1120 newPassword = user.getPassword();
1121 }
1122
1123 try {
1124 String fromName = PrefsPropsUtil.getString(
1125 companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
1126 String fromAddress = PrefsPropsUtil.getString(
1127 companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
1128
1129 String toName = user.getFullName();
1130 String toAddress = user.getEmailAddress();
1131
1132 String subject = PrefsPropsUtil.getContent(
1133 companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
1134 String body = PrefsPropsUtil.getContent(
1135 companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_BODY);
1136
1137 subject = StringUtil.replace(
1138 subject,
1139 new String[] {
1140 "[$FROM_ADDRESS$]",
1141 "[$FROM_NAME$]",
1142 "[$PORTAL_URL$]",
1143 "[$REMOTE_ADDRESS$]",
1144 "[$REMOTE_HOST$]",
1145 "[$TO_ADDRESS$]",
1146 "[$TO_NAME$]",
1147 "[$USER_AGENT$]",
1148 "[$USER_ID$]",
1149 "[$USER_PASSWORD$]"
1150 },
1151 new String[] {
1152 fromAddress,
1153 fromName,
1154 company.getVirtualHost(),
1155 remoteAddr,
1156 remoteHost,
1157 toAddress,
1158 toName,
1159 userAgent,
1160 String.valueOf(user.getUserId()),
1161 newPassword
1162 });
1163
1164 body = StringUtil.replace(
1165 body,
1166 new String[] {
1167 "[$FROM_ADDRESS$]",
1168 "[$FROM_NAME$]",
1169 "[$PORTAL_URL$]",
1170 "[$REMOTE_ADDRESS$]",
1171 "[$REMOTE_HOST$]",
1172 "[$TO_ADDRESS$]",
1173 "[$TO_NAME$]",
1174 "[$USER_AGENT$]",
1175 "[$USER_ID$]",
1176 "[$USER_PASSWORD$]"
1177 },
1178 new String[] {
1179 fromAddress,
1180 fromName,
1181 company.getVirtualHost(),
1182 remoteAddr,
1183 remoteHost,
1184 toAddress,
1185 toName,
1186 userAgent,
1187 String.valueOf(user.getUserId()),
1188 newPassword
1189 });
1190
1191 InternetAddress from = new InternetAddress(fromAddress, fromName);
1192
1193 InternetAddress to = new InternetAddress(toAddress, toName);
1194
1195 MailMessage message = new MailMessage(
1196 from, to, subject, body, true);
1197
1198 MailServiceUtil.sendEmail(message);
1199 }
1200 catch (IOException ioe) {
1201 throw new SystemException(ioe);
1202 }
1203 }
1204
1205 public void setGroupUsers(long groupId, long[] userIds)
1206 throws PortalException, SystemException {
1207
1208 GroupUtil.setUsers(groupId, userIds);
1209
1210 PermissionCacheUtil.clearCache();
1211 }
1212
1213 public void setRoleUsers(long roleId, long[] userIds)
1214 throws PortalException, SystemException {
1215
1216 RoleUtil.setUsers(roleId, userIds);
1217
1218 PermissionCacheUtil.clearCache();
1219 }
1220
1221 public void setUserGroupUsers(long userGroupId, long[] userIds)
1222 throws PortalException, SystemException {
1223
1224 UserGroupUtil.setUsers(userGroupId, userIds);
1225
1226 PermissionCacheUtil.clearCache();
1227 }
1228
1229 public void unsetGroupUsers(long groupId, long[] userIds)
1230 throws PortalException, SystemException {
1231
1232 UserGroupRoleLocalServiceUtil.deleteUserGroupRoles(userIds, groupId);
1233
1234 GroupUtil.removeUsers(groupId, userIds);
1235
1236 PermissionCacheUtil.clearCache();
1237 }
1238
1239 public void unsetPasswordPolicyUsers(
1240 long passwordPolicyId, long[] userIds)
1241 throws PortalException, SystemException {
1242
1243 PasswordPolicyRelLocalServiceUtil.deletePasswordPolicyRels(
1244 passwordPolicyId, User.class.getName(), userIds);
1245 }
1246
1247 public void unsetRoleUsers(long roleId, long[] userIds)
1248 throws PortalException, SystemException {
1249
1250 RoleUtil.removeUsers(roleId, userIds);
1251
1252 PermissionCacheUtil.clearCache();
1253 }
1254
1255 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1256 throws PortalException, SystemException {
1257
1258 UserGroupUtil.removeUsers(userGroupId, userIds);
1259
1260 PermissionCacheUtil.clearCache();
1261 }
1262
1263 public User updateActive(long userId, boolean active)
1264 throws PortalException, SystemException {
1265
1266 User user = UserUtil.findByPrimaryKey(userId);
1267
1268 user.setActive(active);
1269
1270 UserUtil.update(user);
1271
1272 return user;
1273 }
1274
1275 public User updateAgreedToTermsOfUse(
1276 long userId, boolean agreedToTermsOfUse)
1277 throws PortalException, SystemException {
1278
1279 User user = UserUtil.findByPrimaryKey(userId);
1280
1281 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1282
1283 UserUtil.update(user);
1284
1285 return user;
1286 }
1287
1288 public User updateCreateDate(long userId, Date createDate)
1289 throws PortalException, SystemException {
1290
1291 User user = UserUtil.findByPrimaryKey(userId);
1292
1293 user.setCreateDate(createDate);
1294
1295 UserUtil.update(user);
1296
1297 return user;
1298 }
1299
1300 public User updateLastLogin(long userId, String loginIP)
1301 throws PortalException, SystemException {
1302
1303 User user = UserUtil.findByPrimaryKey(userId);
1304
1305 Date lastLoginDate = user.getLoginDate();
1306
1307 if (lastLoginDate == null) {
1308 lastLoginDate = new Date();
1309 }
1310
1311 user.setLoginDate(new Date());
1312 user.setLoginIP(loginIP);
1313 user.setLastLoginDate(lastLoginDate);
1314 user.setLastLoginIP(user.getLoginIP());
1315 user.setLastFailedLoginDate(null);
1316 user.setFailedLoginAttempts(0);
1317
1318 UserUtil.update(user);
1319
1320 return user;
1321 }
1322
1323 public User updateLockout(User user, boolean lockout)
1324 throws PortalException, SystemException {
1325
1326 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1327
1328 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1329 return user;
1330 }
1331
1332 Date lockoutDate = null;
1333
1334 if (lockout) {
1335 lockoutDate = new Date();
1336 }
1337
1338 user.setLockout(lockout);
1339 user.setLockoutDate(lockoutDate);
1340
1341 if (!lockout) {
1342 user.setLastFailedLoginDate(lockoutDate);
1343 user.setFailedLoginAttempts(0);
1344 }
1345
1346 UserUtil.update(user);
1347
1348 return user;
1349 }
1350
1351 public User updateLockoutByEmailAddress(
1352 long companyId, String emailAddress, boolean lockout)
1353 throws PortalException, SystemException {
1354
1355 User user = getUserByEmailAddress(companyId, emailAddress);
1356
1357 return updateLockout(user, lockout);
1358 }
1359
1360 public User updateLockoutById(long userId, boolean lockout)
1361 throws PortalException, SystemException {
1362
1363 User user = getUserById(userId);
1364
1365 return updateLockout(user, lockout);
1366 }
1367
1368 public User updateLockoutByScreenName(
1369 long companyId, String screenName, boolean lockout)
1370 throws PortalException, SystemException {
1371
1372 User user = getUserByScreenName(companyId, screenName);
1373
1374 return updateLockout(user, lockout);
1375 }
1376
1377 public User updateModifiedDate(long userId, Date modifiedDate)
1378 throws PortalException, SystemException {
1379
1380 User user = UserUtil.findByPrimaryKey(userId);
1381
1382 user.setModifiedDate(modifiedDate);
1383
1384 UserUtil.update(user);
1385
1386 return user;
1387 }
1388
1389 public void updateOrganizations(
1390 long userId, long organizationId, long locationId)
1391 throws PortalException, SystemException {
1392
1393 UserUtil.clearOrganizations(userId);
1394
1395 if (organizationId > 0) {
1396 UserUtil.addOrganization(userId, organizationId);
1397 }
1398
1399 if (locationId > 0) {
1400 UserUtil.addOrganization(userId, locationId);
1401 }
1402
1403 PermissionCacheUtil.clearCache();
1404 }
1405
1406 public User updatePassword(
1407 long userId, String password1, String password2,
1408 boolean passwordReset)
1409 throws PortalException, SystemException {
1410
1411 return updatePassword(
1412 userId, password1, password2, passwordReset, false);
1413 }
1414
1415 public User updatePassword(
1416 long userId, String password1, String password2,
1417 boolean passwordReset, boolean silentUpdate)
1418 throws PortalException, SystemException {
1419
1420 User user = UserUtil.findByPrimaryKey(userId);
1421
1422
1425 if (!silentUpdate) {
1426 validatePassword(user.getCompanyId(), userId, password1, password2);
1427 }
1428
1429 String oldEncPwd = user.getPassword();
1430
1431 if (!user.isPasswordEncrypted()) {
1432 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1433 }
1434
1435 String newEncPwd = PwdEncryptor.encrypt(password1);
1436
1437 if (user.hasCompanyMx()) {
1438 try {
1439 MailServiceUtil.updatePassword(userId, password1);
1440 }
1441 catch (RemoteException re) {
1442 throw new SystemException(re);
1443 }
1444 }
1445
1446 user.setPassword(newEncPwd);
1447 user.setPasswordUnencrypted(password1);
1448 user.setPasswordEncrypted(true);
1449 user.setPasswordReset(passwordReset);
1450 user.setPasswordModifiedDate(new Date());
1451 user.setGraceLoginCount(0);
1452
1453 if (!silentUpdate) {
1454 user.setPasswordModified(true);
1455 }
1456
1457 try {
1458 UserUtil.update(user);
1459 }
1460 catch (ModelListenerException mle) {
1461 String msg = GetterUtil.getString(mle.getCause().getMessage());
1462
1463 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1464 String passwordHistory = PrefsPropsUtil.getString(
1465 user.getCompanyId(), PropsUtil.LDAP_ERROR_PASSWORD_HISTORY);
1466
1467 if (msg.indexOf(passwordHistory) != -1) {
1468 throw new UserPasswordException(
1469 UserPasswordException.PASSWORD_ALREADY_USED);
1470 }
1471 }
1472
1473 throw new UserPasswordException(
1474 UserPasswordException.PASSWORD_INVALID);
1475 }
1476
1477 if (!silentUpdate) {
1478 user.setPasswordModified(false);
1479 }
1480
1481 PasswordTrackerLocalServiceUtil.trackPassword(userId, oldEncPwd);
1482
1483 return user;
1484 }
1485
1486 public User updatePasswordManually(
1487 long userId, String password, boolean passwordEncrypted,
1488 boolean passwordReset, Date passwordModifiedDate)
1489 throws PortalException, SystemException {
1490
1491
1493 User user = UserUtil.findByPrimaryKey(userId);
1494
1495 user.setPassword(password);
1496 user.setPasswordEncrypted(passwordEncrypted);
1497 user.setPasswordReset(passwordReset);
1498 user.setPasswordModifiedDate(passwordModifiedDate);
1499
1500 UserUtil.update(user);
1501
1502 return user;
1503 }
1504
1505 public void updatePasswordReset(long userId, boolean passwordReset)
1506 throws PortalException, SystemException {
1507
1508 User user = getUserById(userId);
1509
1510 user.setPasswordReset(passwordReset);
1511
1512 UserUtil.update(user);
1513 }
1514
1515 public void updatePortrait(long userId, byte[] bytes)
1516 throws PortalException, SystemException {
1517
1518 User user = UserUtil.findByPrimaryKey(userId);
1519
1520 long imageMaxSize = GetterUtil.getLong(
1521 PropsUtil.get(PropsUtil.USERS_IMAGE_MAX_SIZE));
1522
1523 if ((imageMaxSize > 0) &&
1524 ((bytes == null) || (bytes.length > imageMaxSize))) {
1525
1526 throw new UserPortraitException();
1527 }
1528
1529 long portraitId = user.getPortraitId();
1530
1531 if (portraitId <= 0) {
1532 portraitId = CounterLocalServiceUtil.increment();
1533
1534 user.setPortraitId(portraitId);
1535 }
1536
1537 ImageLocalUtil.updateImage(portraitId, bytes);
1538 }
1539
1540 public User updateUser(
1541 long userId, String password, String screenName,
1542 String emailAddress, String languageId, String timeZoneId,
1543 String greeting, String comments, String firstName,
1544 String middleName, String lastName, int prefixId, int suffixId,
1545 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1546 String smsSn, String aimSn, String icqSn, String jabberSn,
1547 String msnSn, String skypeSn, String ymSn, String jobTitle,
1548 long organizationId, long locationId)
1549 throws PortalException, SystemException {
1550
1551
1553 screenName = screenName.trim().toLowerCase();
1554 emailAddress = emailAddress.trim().toLowerCase();
1555 Date now = new Date();
1556
1557 validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1558
1559 User user = UserUtil.findByPrimaryKey(userId);
1560 Company company = CompanyUtil.findByPrimaryKey(user.getCompanyId());
1561
1562 validateOrganizations(user.getCompanyId(), organizationId, locationId);
1563
1564 user.setModifiedDate(now);
1565
1566 if (user.getContactId() <= 0) {
1567 user.setContactId(CounterLocalServiceUtil.increment());
1568 }
1569
1570 user.setScreenName(screenName);
1571
1572 if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1573
1574
1576 try {
1577 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1578 MailServiceUtil.addUser(
1579 userId, password, firstName, middleName, lastName,
1580 emailAddress);
1581 }
1582
1583
1585 else if (user.hasCompanyMx() &&
1586 user.hasCompanyMx(emailAddress)) {
1587
1588 MailServiceUtil.updateEmailAddress(userId, emailAddress);
1589 }
1590
1591
1593 else if (user.hasCompanyMx() &&
1594 !user.hasCompanyMx(emailAddress)) {
1595
1596 MailServiceUtil.deleteEmailAddress(userId);
1597 }
1598 }
1599 catch (RemoteException re) {
1600 throw new SystemException(re);
1601 }
1602
1603 user.setEmailAddress(emailAddress);
1604 }
1605
1606 user.setLanguageId(languageId);
1607 user.setTimeZoneId(timeZoneId);
1608 user.setGreeting(greeting);
1609 user.setComments(comments);
1610
1611 UserUtil.update(user);
1612
1613
1615 Date birthday = PortalUtil.getDate(
1616 birthdayMonth, birthdayDay, birthdayYear,
1617 new ContactBirthdayException());
1618
1619 long contactId = user.getContactId();
1620
1621 Contact contact = null;
1622
1623 try {
1624 contact = ContactUtil.findByPrimaryKey(contactId);
1625 }
1626 catch (NoSuchContactException nsce) {
1627 contact = ContactUtil.create(contactId);
1628
1629 contact.setCompanyId(user.getCompanyId());
1630 contact.setUserName(StringPool.BLANK);
1631 contact.setCreateDate(now);
1632 contact.setAccountId(company.getAccountId());
1633 contact.setParentContactId(ContactImpl.DEFAULT_PARENT_CONTACT_ID);
1634 }
1635
1636 contact.setModifiedDate(now);
1637 contact.setFirstName(firstName);
1638 contact.setMiddleName(middleName);
1639 contact.setLastName(lastName);
1640 contact.setPrefixId(prefixId);
1641 contact.setSuffixId(suffixId);
1642 contact.setMale(male);
1643 contact.setBirthday(birthday);
1644 contact.setSmsSn(smsSn);
1645 contact.setAimSn(aimSn);
1646 contact.setIcqSn(icqSn);
1647 contact.setJabberSn(jabberSn);
1648 contact.setMsnSn(msnSn);
1649 contact.setSkypeSn(skypeSn);
1650 contact.setYmSn(ymSn);
1651 contact.setJobTitle(jobTitle);
1652
1653 ContactUtil.update(contact);
1654
1655
1657 updateOrganizations(userId, organizationId, locationId);
1658
1659
1661 PermissionCacheUtil.clearCache();
1662
1663 return user;
1664 }
1665
1666 protected int authenticate(
1667 long companyId, String login, String password, String authType,
1668 Map headerMap, Map parameterMap)
1669 throws PortalException, SystemException {
1670
1671 login = login.trim().toLowerCase();
1672
1673 long userId = GetterUtil.getLong(login);
1674
1675
1677 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1678 if (!Validator.isEmailAddress(login)) {
1679 throw new UserEmailAddressException();
1680 }
1681 }
1682 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1683 if (Validator.isNull(login)) {
1684 throw new UserScreenNameException();
1685 }
1686 }
1687 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1688 if (Validator.isNull(login)) {
1689 throw new UserIdException();
1690 }
1691 }
1692
1693 if (Validator.isNull(password)) {
1694 throw new UserPasswordException(
1695 UserPasswordException.PASSWORD_INVALID);
1696 }
1697
1698 int authResult = Authenticator.FAILURE;
1699
1700
1702 String[] authPipelinePre =
1703 PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE);
1704
1705 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1706 authResult = AuthPipeline.authenticateByEmailAddress(
1707 authPipelinePre, companyId, login, password, headerMap,
1708 parameterMap);
1709 }
1710 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1711 authResult = AuthPipeline.authenticateByScreenName(
1712 authPipelinePre, companyId, login, password, headerMap,
1713 parameterMap);
1714 }
1715 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1716 authResult = AuthPipeline.authenticateByUserId(
1717 authPipelinePre, companyId, userId, password, headerMap,
1718 parameterMap);
1719 }
1720
1721
1723 User user = null;
1724
1725 try {
1726 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1727 user = UserUtil.findByC_EA(companyId, login);
1728 }
1729 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1730 user = UserUtil.findByC_SN(companyId, login);
1731 }
1732 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1733 user = UserUtil.findByC_U(companyId, GetterUtil.getLong(login));
1734 }
1735 }
1736 catch (NoSuchUserException nsue) {
1737 return Authenticator.DNE;
1738 }
1739
1740 if (user.isDefaultUser()) {
1741 _log.error(
1742 "The default user should never be allowed to authenticate");
1743
1744 return Authenticator.DNE;
1745 }
1746
1747 if (!user.isPasswordEncrypted()) {
1748 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
1749 user.setPasswordEncrypted(true);
1750
1751 UserUtil.update(user);
1752 }
1753
1754
1757 checkLockout(user);
1758
1759 checkPasswordExpired(user);
1760
1761
1763 if (authResult == Authenticator.SUCCESS) {
1764 if (GetterUtil.getBoolean(PropsUtil.get(
1765 PropsUtil.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK))) {
1766
1767 String encPwd = PwdEncryptor.encrypt(
1768 password, user.getPassword());
1769
1770 if (user.getPassword().equals(encPwd)) {
1771 authResult = Authenticator.SUCCESS;
1772 }
1773 else if (GetterUtil.getBoolean(PropsUtil.get(
1774 PropsUtil.AUTH_MAC_ALLOW))) {
1775
1776 try {
1777 MessageDigest digester = MessageDigest.getInstance(
1778 PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM));
1779
1780 digester.update(login.getBytes("UTF8"));
1781
1782 String shardKey =
1783 PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY);
1784
1785 encPwd = Base64.encode(
1786 digester.digest(shardKey.getBytes("UTF8")));
1787
1788 if (password.equals(encPwd)) {
1789 authResult = Authenticator.SUCCESS;
1790 }
1791 else {
1792 authResult = Authenticator.FAILURE;
1793 }
1794 }
1795 catch (NoSuchAlgorithmException nsae) {
1796 throw new SystemException(nsae);
1797 }
1798 catch (UnsupportedEncodingException uee) {
1799 throw new SystemException(uee);
1800 }
1801 }
1802 else {
1803 authResult = Authenticator.FAILURE;
1804 }
1805 }
1806 }
1807
1808
1810 if (authResult == Authenticator.SUCCESS) {
1811 String[] authPipelinePost =
1812 PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST);
1813
1814 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1815 authResult = AuthPipeline.authenticateByEmailAddress(
1816 authPipelinePost, companyId, login, password, headerMap,
1817 parameterMap);
1818 }
1819 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1820 authResult = AuthPipeline.authenticateByScreenName(
1821 authPipelinePost, companyId, login, password, headerMap,
1822 parameterMap);
1823 }
1824 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1825 authResult = AuthPipeline.authenticateByUserId(
1826 authPipelinePost, companyId, userId, password, headerMap,
1827 parameterMap);
1828 }
1829 }
1830
1831
1833 if (authResult == Authenticator.FAILURE) {
1834 try {
1835 String[] authFailure =
1836 PropsUtil.getArray(PropsUtil.AUTH_FAILURE);
1837
1838 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1839 AuthPipeline.onFailureByEmailAddress(
1840 authFailure, companyId, login, headerMap, parameterMap);
1841 }
1842 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1843 AuthPipeline.onFailureByScreenName(
1844 authFailure, companyId, login, headerMap, parameterMap);
1845 }
1846 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1847 AuthPipeline.onFailureByUserId(
1848 authFailure, companyId, userId, headerMap,
1849 parameterMap);
1850 }
1851
1852
1854 if (!PortalLDAPUtil.isPasswordPolicyEnabled(
1855 user.getCompanyId())) {
1856
1857 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1858
1859 int failedLoginAttempts = user.getFailedLoginAttempts();
1860 int maxFailures = passwordPolicy.getMaxFailure();
1861
1862 if ((failedLoginAttempts >= maxFailures) &&
1863 (maxFailures != 0)) {
1864
1865 String[] authMaxFailures =
1866 PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES);
1867
1868 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1869 AuthPipeline.onMaxFailuresByEmailAddress(
1870 authMaxFailures, companyId, login, headerMap,
1871 parameterMap);
1872 }
1873 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1874 AuthPipeline.onMaxFailuresByScreenName(
1875 authMaxFailures, companyId, login, headerMap,
1876 parameterMap);
1877 }
1878 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1879 AuthPipeline.onMaxFailuresByUserId(
1880 authMaxFailures, companyId, userId, headerMap,
1881 parameterMap);
1882 }
1883 }
1884 }
1885 }
1886 catch (Exception e) {
1887 _log.error(e, e);
1888 }
1889 }
1890
1891 return authResult;
1892 }
1893
1894 protected void sendEmail(User user, String password)
1895 throws PortalException, SystemException {
1896
1897 if (!PrefsPropsUtil.getBoolean(
1898 user.getCompanyId(),
1899 PropsUtil.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
1900
1901 return;
1902 }
1903
1904 try {
1905 long companyId = user.getCompanyId();
1906
1907 Company company = CompanyUtil.findByPrimaryKey(companyId);
1908
1909 String fromName = PrefsPropsUtil.getString(
1910 companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
1911 String fromAddress = PrefsPropsUtil.getString(
1912 companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
1913
1914 String toName = user.getFullName();
1915 String toAddress = user.getEmailAddress();
1916
1917 String subject = PrefsPropsUtil.getContent(
1918 companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_SUBJECT);
1919 String body = PrefsPropsUtil.getContent(
1920 companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_BODY);
1921
1922 subject = StringUtil.replace(
1923 subject,
1924 new String[] {
1925 "[$FROM_ADDRESS$]",
1926 "[$FROM_NAME$]",
1927 "[$PORTAL_URL$]",
1928 "[$TO_ADDRESS$]",
1929 "[$TO_NAME$]",
1930 "[$USER_ID$]",
1931 "[$USER_PASSWORD$]"
1932 },
1933 new String[] {
1934 fromAddress,
1935 fromName,
1936 company.getVirtualHost(),
1937 toAddress,
1938 toName,
1939 String.valueOf(user.getUserId()),
1940 password
1941 });
1942
1943 body = StringUtil.replace(
1944 body,
1945 new String[] {
1946 "[$FROM_ADDRESS$]",
1947 "[$FROM_NAME$]",
1948 "[$PORTAL_URL$]",
1949 "[$TO_ADDRESS$]",
1950 "[$TO_NAME$]",
1951 "[$USER_ID$]",
1952 "[$USER_PASSWORD$]"
1953 },
1954 new String[] {
1955 fromAddress,
1956 fromName,
1957 company.getVirtualHost(),
1958 toAddress,
1959 toName,
1960 String.valueOf(user.getUserId()),
1961 password
1962 });
1963
1964 InternetAddress from = new InternetAddress(fromAddress, fromName);
1965
1966 InternetAddress to = new InternetAddress(toAddress, toName);
1967
1968 MailMessage message = new MailMessage(
1969 from, to, subject, body, true);
1970
1971 MailServiceUtil.sendEmail(message);
1972 }
1973 catch (IOException ioe) {
1974 throw new SystemException(ioe);
1975 }
1976 }
1977
1978 protected void validate(
1979 long userId, String screenName, String emailAddress,
1980 String firstName, String lastName, String smsSn)
1981 throws PortalException, SystemException {
1982
1983 User user = UserUtil.findByPrimaryKey(userId);
1984
1985 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
1986 validateScreenName(user.getCompanyId(), screenName);
1987 }
1988
1989 validateEmailAddress(emailAddress);
1990
1991 if (!user.isDefaultUser()) {
1992 try {
1993 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
1994 if (UserUtil.findByC_EA(
1995 user.getCompanyId(), emailAddress) != null) {
1996
1997 throw new DuplicateUserEmailAddressException();
1998 }
1999 }
2000 }
2001 catch (NoSuchUserException nsue) {
2002 }
2003
2004 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2005 user.getCompanyId(), PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES);
2006
2007 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2008 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2009 throw new ReservedUserEmailAddressException();
2010 }
2011 }
2012
2013 if (Validator.isNull(firstName)) {
2014 throw new ContactFirstNameException();
2015 }
2016 else if (Validator.isNull(lastName)) {
2017 throw new ContactLastNameException();
2018 }
2019 }
2020
2021 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2022 throw new UserSmsException();
2023 }
2024 }
2025
2026 protected void validate(
2027 long companyId, boolean autoPassword, String password1,
2028 String password2, boolean autoScreenName, String screenName,
2029 String emailAddress, String firstName, String lastName,
2030 long organizationId, long locationId)
2031 throws PortalException, SystemException {
2032
2033 if (!autoScreenName) {
2034 validateScreenName(companyId, screenName);
2035 }
2036
2037 if (!autoPassword) {
2038 PasswordPolicy passwordPolicy =
2039 PasswordPolicyLocalServiceUtil.getDefaultPasswordPolicy(
2040 companyId);
2041
2042 PwdToolkitUtil.validate(
2043 companyId, 0, password1, password2, passwordPolicy);
2044 }
2045
2046 validateEmailAddress(emailAddress);
2047
2048 try {
2049 User user = UserUtil.findByC_EA(companyId, emailAddress);
2050
2051 if (user != null) {
2052 throw new DuplicateUserEmailAddressException();
2053 }
2054 }
2055 catch (NoSuchUserException nsue) {
2056 }
2057
2058 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2059 companyId, PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES);
2060
2061 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2062 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2063 throw new ReservedUserEmailAddressException();
2064 }
2065 }
2066
2067 if (Validator.isNull(firstName)) {
2068 throw new ContactFirstNameException();
2069 }
2070 else if (Validator.isNull(lastName)) {
2071 throw new ContactLastNameException();
2072 }
2073 }
2074
2075 protected void validateEmailAddress(String emailAddress)
2076 throws PortalException {
2077
2078 if (!Validator.isEmailAddress(emailAddress) ||
2079 emailAddress.startsWith("root@") ||
2080 emailAddress.startsWith("postmaster@")) {
2081
2082 throw new UserEmailAddressException();
2083 }
2084 }
2085
2086 protected void validateOrganizations(
2087 long companyId, long organizationId, long locationId)
2088 throws PortalException, SystemException {
2089
2090 boolean organizationRequired = GetterUtil.getBoolean(PropsUtil.get(
2091 PropsUtil.ORGANIZATIONS_PARENT_ORGANIZATION_REQUIRED));
2092
2093 boolean locationRequired = GetterUtil.getBoolean(PropsUtil.get(
2094 PropsUtil.ORGANIZATIONS_LOCATION_REQUIRED));
2095
2096 if (locationRequired) {
2097 organizationRequired = true;
2098 }
2099
2100 Organization organization = null;
2101
2102 if (organizationRequired || (organizationId > 0)) {
2103 organization = OrganizationUtil.findByPrimaryKey(organizationId);
2104 }
2105
2106 Organization location = null;
2107
2108 if (locationRequired || (locationId > 0)) {
2109 location = OrganizationUtil.findByPrimaryKey(locationId);
2110 }
2111
2112 if ((organization != null) && (location != null)) {
2113
2114
2116 if (!OrganizationLocalServiceUtil.isAncestor(
2117 locationId, organizationId)) {
2118
2119 throw new OrganizationParentException();
2120 }
2121 }
2122 }
2123
2124 protected void validatePassword(
2125 long companyId, long userId, String password1, String password2)
2126 throws PortalException, SystemException {
2127
2128 if (Validator.isNull(password1) || Validator.isNull(password2)) {
2129 throw new UserPasswordException(
2130 UserPasswordException.PASSWORD_INVALID);
2131 }
2132
2133 if (!password1.equals(password2)) {
2134 throw new UserPasswordException(
2135 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2136 }
2137
2138 PasswordPolicy passwordPolicy =
2139 PasswordPolicyLocalServiceUtil.getPasswordPolicyByUserId(
2140 userId);
2141
2142 PwdToolkitUtil.validate(
2143 companyId, userId, password1, password2, passwordPolicy);
2144 }
2145
2146 protected void validateScreenName(long companyId, String screenName)
2147 throws PortalException, SystemException {
2148
2149 if (Validator.isNull(screenName)) {
2150 throw new UserScreenNameException();
2151 }
2152
2153 ScreenNameValidator screenNameValidator =
2154 (ScreenNameValidator)InstancePool.get(
2155 PropsUtil.get(PropsUtil.USERS_SCREEN_NAME_VALIDATOR));
2156
2157 if (screenNameValidator != null) {
2158 if (!screenNameValidator.validate(companyId, screenName)) {
2159 throw new UserScreenNameException();
2160 }
2161 }
2162
2163 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2164
2165 for (int i = 0; i < anonymousNames.length; i++) {
2166 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2167 throw new UserScreenNameException();
2168 }
2169 }
2170
2171 User user = UserUtil.fetchByC_SN(companyId, screenName);
2172
2173 if (user != null) {
2174 throw new DuplicateUserScreenNameException();
2175 }
2176
2177 String friendlyURL = StringPool.SLASH + screenName;
2178
2179 Group group = GroupUtil.fetchByC_F(companyId, friendlyURL);
2180
2181 if (group != null) {
2182 throw new DuplicateUserScreenNameException();
2183 }
2184
2185 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2186 companyId, PropsUtil.ADMIN_RESERVED_SCREEN_NAMES);
2187
2188 for (int i = 0; i < reservedScreenNames.length; i++) {
2189 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2190 throw new ReservedUserScreenNameException();
2191 }
2192 }
2193 }
2194
2195 private static Log _log = LogFactory.getLog(UserLocalServiceImpl.class);
2196
2197}