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 = PwdToolkitUtil.generate();
1098
1099 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
1100 PwdEncryptor.TYPE_NONE)) {
1101
1102 user.setPassword(PwdEncryptor.encrypt(newPassword));
1103 user.setPasswordUnencrypted(newPassword);
1104 user.setPasswordEncrypted(true);
1105 user.setPasswordReset(
1106 passwordPolicy.getChangeable() &&
1107 passwordPolicy.getChangeRequired());
1108
1109 UserUtil.update(user);
1110 }
1111
1112 try {
1113 String fromName = PrefsPropsUtil.getString(
1114 companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
1115 String fromAddress = PrefsPropsUtil.getString(
1116 companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
1117
1118 String toName = user.getFullName();
1119 String toAddress = user.getEmailAddress();
1120
1121 String subject = PrefsPropsUtil.getContent(
1122 companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
1123 String body = PrefsPropsUtil.getContent(
1124 companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_BODY);
1125
1126 subject = StringUtil.replace(
1127 subject,
1128 new String[] {
1129 "[$FROM_ADDRESS$]",
1130 "[$FROM_NAME$]",
1131 "[$PORTAL_URL$]",
1132 "[$REMOTE_ADDRESS$]",
1133 "[$REMOTE_HOST$]",
1134 "[$TO_ADDRESS$]",
1135 "[$TO_NAME$]",
1136 "[$USER_AGENT$]",
1137 "[$USER_ID$]",
1138 "[$USER_PASSWORD$]"
1139 },
1140 new String[] {
1141 fromAddress,
1142 fromName,
1143 company.getVirtualHost(),
1144 remoteAddr,
1145 remoteHost,
1146 toAddress,
1147 toName,
1148 userAgent,
1149 String.valueOf(user.getUserId()),
1150 newPassword
1151 });
1152
1153 body = StringUtil.replace(
1154 body,
1155 new String[] {
1156 "[$FROM_ADDRESS$]",
1157 "[$FROM_NAME$]",
1158 "[$PORTAL_URL$]",
1159 "[$REMOTE_ADDRESS$]",
1160 "[$REMOTE_HOST$]",
1161 "[$TO_ADDRESS$]",
1162 "[$TO_NAME$]",
1163 "[$USER_AGENT$]",
1164 "[$USER_ID$]",
1165 "[$USER_PASSWORD$]"
1166 },
1167 new String[] {
1168 fromAddress,
1169 fromName,
1170 company.getVirtualHost(),
1171 remoteAddr,
1172 remoteHost,
1173 toAddress,
1174 toName,
1175 userAgent,
1176 String.valueOf(user.getUserId()),
1177 newPassword
1178 });
1179
1180 InternetAddress from = new InternetAddress(fromAddress, fromName);
1181
1182 InternetAddress to = new InternetAddress(toAddress, toName);
1183
1184 MailMessage message = new MailMessage(
1185 from, to, subject, body, true);
1186
1187 MailServiceUtil.sendEmail(message);
1188 }
1189 catch (IOException ioe) {
1190 throw new SystemException(ioe);
1191 }
1192 }
1193
1194 public void setGroupUsers(long groupId, long[] userIds)
1195 throws PortalException, SystemException {
1196
1197 GroupUtil.setUsers(groupId, userIds);
1198
1199 PermissionCacheUtil.clearCache();
1200 }
1201
1202 public void setRoleUsers(long roleId, long[] userIds)
1203 throws PortalException, SystemException {
1204
1205 RoleUtil.setUsers(roleId, userIds);
1206
1207 PermissionCacheUtil.clearCache();
1208 }
1209
1210 public void setUserGroupUsers(long userGroupId, long[] userIds)
1211 throws PortalException, SystemException {
1212
1213 UserGroupUtil.setUsers(userGroupId, userIds);
1214
1215 PermissionCacheUtil.clearCache();
1216 }
1217
1218 public void unsetGroupUsers(long groupId, long[] userIds)
1219 throws PortalException, SystemException {
1220
1221 UserGroupRoleLocalServiceUtil.deleteUserGroupRoles(userIds, groupId);
1222
1223 GroupUtil.removeUsers(groupId, userIds);
1224
1225 PermissionCacheUtil.clearCache();
1226 }
1227
1228 public void unsetPasswordPolicyUsers(
1229 long passwordPolicyId, long[] userIds)
1230 throws PortalException, SystemException {
1231
1232 PasswordPolicyRelLocalServiceUtil.deletePasswordPolicyRels(
1233 passwordPolicyId, User.class.getName(), userIds);
1234 }
1235
1236 public void unsetRoleUsers(long roleId, long[] userIds)
1237 throws PortalException, SystemException {
1238
1239 RoleUtil.removeUsers(roleId, userIds);
1240
1241 PermissionCacheUtil.clearCache();
1242 }
1243
1244 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1245 throws PortalException, SystemException {
1246
1247 UserGroupUtil.removeUsers(userGroupId, userIds);
1248
1249 PermissionCacheUtil.clearCache();
1250 }
1251
1252 public User updateActive(long userId, boolean active)
1253 throws PortalException, SystemException {
1254
1255 User user = UserUtil.findByPrimaryKey(userId);
1256
1257 user.setActive(active);
1258
1259 UserUtil.update(user);
1260
1261 return user;
1262 }
1263
1264 public User updateAgreedToTermsOfUse(
1265 long userId, boolean agreedToTermsOfUse)
1266 throws PortalException, SystemException {
1267
1268 User user = UserUtil.findByPrimaryKey(userId);
1269
1270 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1271
1272 UserUtil.update(user);
1273
1274 return user;
1275 }
1276
1277 public User updateCreateDate(long userId, Date createDate)
1278 throws PortalException, SystemException {
1279
1280 User user = UserUtil.findByPrimaryKey(userId);
1281
1282 user.setCreateDate(createDate);
1283
1284 UserUtil.update(user);
1285
1286 return user;
1287 }
1288
1289 public User updateLastLogin(long userId, String loginIP)
1290 throws PortalException, SystemException {
1291
1292 User user = UserUtil.findByPrimaryKey(userId);
1293
1294 Date lastLoginDate = user.getLoginDate();
1295
1296 if (lastLoginDate == null) {
1297 lastLoginDate = new Date();
1298 }
1299
1300 user.setLoginDate(new Date());
1301 user.setLoginIP(loginIP);
1302 user.setLastLoginDate(lastLoginDate);
1303 user.setLastLoginIP(user.getLoginIP());
1304 user.setLastFailedLoginDate(null);
1305 user.setFailedLoginAttempts(0);
1306
1307 UserUtil.update(user);
1308
1309 return user;
1310 }
1311
1312 public User updateLockout(User user, boolean lockout)
1313 throws PortalException, SystemException {
1314
1315 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1316
1317 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1318 return user;
1319 }
1320
1321 Date lockoutDate = null;
1322
1323 if (lockout) {
1324 lockoutDate = new Date();
1325 }
1326
1327 user.setLockout(lockout);
1328 user.setLockoutDate(lockoutDate);
1329
1330 if (!lockout) {
1331 user.setLastFailedLoginDate(lockoutDate);
1332 user.setFailedLoginAttempts(0);
1333 }
1334
1335 UserUtil.update(user);
1336
1337 return user;
1338 }
1339
1340 public User updateLockoutByEmailAddress(
1341 long companyId, String emailAddress, boolean lockout)
1342 throws PortalException, SystemException {
1343
1344 User user = getUserByEmailAddress(companyId, emailAddress);
1345
1346 return updateLockout(user, lockout);
1347 }
1348
1349 public User updateLockoutById(long userId, boolean lockout)
1350 throws PortalException, SystemException {
1351
1352 User user = getUserById(userId);
1353
1354 return updateLockout(user, lockout);
1355 }
1356
1357 public User updateLockoutByScreenName(
1358 long companyId, String screenName, boolean lockout)
1359 throws PortalException, SystemException {
1360
1361 User user = getUserByScreenName(companyId, screenName);
1362
1363 return updateLockout(user, lockout);
1364 }
1365
1366 public User updateModifiedDate(long userId, Date modifiedDate)
1367 throws PortalException, SystemException {
1368
1369 User user = UserUtil.findByPrimaryKey(userId);
1370
1371 user.setModifiedDate(modifiedDate);
1372
1373 UserUtil.update(user);
1374
1375 return user;
1376 }
1377
1378 public void updateOrganizations(
1379 long userId, long organizationId, long locationId)
1380 throws PortalException, SystemException {
1381
1382 UserUtil.clearOrganizations(userId);
1383
1384 if (organizationId > 0) {
1385 UserUtil.addOrganization(userId, organizationId);
1386 }
1387
1388 if (locationId > 0) {
1389 UserUtil.addOrganization(userId, locationId);
1390 }
1391
1392 PermissionCacheUtil.clearCache();
1393 }
1394
1395 public User updatePassword(
1396 long userId, String password1, String password2,
1397 boolean passwordReset)
1398 throws PortalException, SystemException {
1399
1400 return updatePassword(
1401 userId, password1, password2, passwordReset, false);
1402 }
1403
1404 public User updatePassword(
1405 long userId, String password1, String password2,
1406 boolean passwordReset, boolean silentUpdate)
1407 throws PortalException, SystemException {
1408
1409 User user = UserUtil.findByPrimaryKey(userId);
1410
1411
1414 if (!silentUpdate) {
1415 validatePassword(user.getCompanyId(), userId, password1, password2);
1416 }
1417
1418 String oldEncPwd = user.getPassword();
1419
1420 if (!user.isPasswordEncrypted()) {
1421 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1422 }
1423
1424 String newEncPwd = PwdEncryptor.encrypt(password1);
1425
1426 if (user.hasCompanyMx()) {
1427 try {
1428 MailServiceUtil.updatePassword(userId, password1);
1429 }
1430 catch (RemoteException re) {
1431 throw new SystemException(re);
1432 }
1433 }
1434
1435 user.setPassword(newEncPwd);
1436 user.setPasswordUnencrypted(password1);
1437 user.setPasswordEncrypted(true);
1438 user.setPasswordReset(passwordReset);
1439 user.setPasswordModifiedDate(new Date());
1440 user.setGraceLoginCount(0);
1441
1442 if (!silentUpdate) {
1443 user.setPasswordModified(true);
1444 }
1445
1446 try {
1447 UserUtil.update(user);
1448 }
1449 catch (ModelListenerException mle) {
1450 String msg = GetterUtil.getString(mle.getCause().getMessage());
1451
1452 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1453 String passwordHistory = PrefsPropsUtil.getString(
1454 user.getCompanyId(), PropsUtil.LDAP_ERROR_PASSWORD_HISTORY);
1455
1456 if (msg.indexOf(passwordHistory) != -1) {
1457 throw new UserPasswordException(
1458 UserPasswordException.PASSWORD_ALREADY_USED);
1459 }
1460 }
1461
1462 throw new UserPasswordException(
1463 UserPasswordException.PASSWORD_INVALID);
1464 }
1465
1466 if (!silentUpdate) {
1467 user.setPasswordModified(false);
1468 }
1469
1470 PasswordTrackerLocalServiceUtil.trackPassword(userId, oldEncPwd);
1471
1472 return user;
1473 }
1474
1475 public User updatePasswordManually(
1476 long userId, String password, boolean passwordEncrypted,
1477 boolean passwordReset, Date passwordModifiedDate)
1478 throws PortalException, SystemException {
1479
1480
1482 User user = UserUtil.findByPrimaryKey(userId);
1483
1484 user.setPassword(password);
1485 user.setPasswordEncrypted(passwordEncrypted);
1486 user.setPasswordReset(passwordReset);
1487 user.setPasswordModifiedDate(passwordModifiedDate);
1488
1489 UserUtil.update(user);
1490
1491 return user;
1492 }
1493
1494 public void updatePasswordReset(long userId, boolean passwordReset)
1495 throws PortalException, SystemException {
1496
1497 User user = getUserById(userId);
1498
1499 user.setPasswordReset(passwordReset);
1500
1501 UserUtil.update(user);
1502 }
1503
1504 public void updatePortrait(long userId, byte[] bytes)
1505 throws PortalException, SystemException {
1506
1507 User user = UserUtil.findByPrimaryKey(userId);
1508
1509 long imageMaxSize = GetterUtil.getLong(
1510 PropsUtil.get(PropsUtil.USERS_IMAGE_MAX_SIZE));
1511
1512 if ((imageMaxSize > 0) &&
1513 ((bytes == null) || (bytes.length > imageMaxSize))) {
1514
1515 throw new UserPortraitException();
1516 }
1517
1518 long portraitId = user.getPortraitId();
1519
1520 if (portraitId <= 0) {
1521 portraitId = CounterLocalServiceUtil.increment();
1522
1523 user.setPortraitId(portraitId);
1524 }
1525
1526 ImageLocalUtil.updateImage(portraitId, bytes);
1527 }
1528
1529 public User updateUser(
1530 long userId, String password, String screenName,
1531 String emailAddress, String languageId, String timeZoneId,
1532 String greeting, String comments, String firstName,
1533 String middleName, String lastName, int prefixId, int suffixId,
1534 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1535 String smsSn, String aimSn, String icqSn, String jabberSn,
1536 String msnSn, String skypeSn, String ymSn, String jobTitle,
1537 long organizationId, long locationId)
1538 throws PortalException, SystemException {
1539
1540
1542 screenName = screenName.trim().toLowerCase();
1543 emailAddress = emailAddress.trim().toLowerCase();
1544 Date now = new Date();
1545
1546 validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1547
1548 User user = UserUtil.findByPrimaryKey(userId);
1549 Company company = CompanyUtil.findByPrimaryKey(user.getCompanyId());
1550
1551 validateOrganizations(user.getCompanyId(), organizationId, locationId);
1552
1553 user.setModifiedDate(now);
1554
1555 if (user.getContactId() <= 0) {
1556 user.setContactId(CounterLocalServiceUtil.increment());
1557 }
1558
1559 user.setScreenName(screenName);
1560
1561 if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1562
1563
1565 try {
1566 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1567 MailServiceUtil.addUser(
1568 userId, password, firstName, middleName, lastName,
1569 emailAddress);
1570 }
1571
1572
1574 else if (user.hasCompanyMx() &&
1575 user.hasCompanyMx(emailAddress)) {
1576
1577 MailServiceUtil.updateEmailAddress(userId, emailAddress);
1578 }
1579
1580
1582 else if (user.hasCompanyMx() &&
1583 !user.hasCompanyMx(emailAddress)) {
1584
1585 MailServiceUtil.deleteEmailAddress(userId);
1586 }
1587 }
1588 catch (RemoteException re) {
1589 throw new SystemException(re);
1590 }
1591
1592 user.setEmailAddress(emailAddress);
1593 }
1594
1595 user.setLanguageId(languageId);
1596 user.setTimeZoneId(timeZoneId);
1597 user.setGreeting(greeting);
1598 user.setComments(comments);
1599
1600 UserUtil.update(user);
1601
1602
1604 Date birthday = PortalUtil.getDate(
1605 birthdayMonth, birthdayDay, birthdayYear,
1606 new ContactBirthdayException());
1607
1608 long contactId = user.getContactId();
1609
1610 Contact contact = null;
1611
1612 try {
1613 contact = ContactUtil.findByPrimaryKey(contactId);
1614 }
1615 catch (NoSuchContactException nsce) {
1616 contact = ContactUtil.create(contactId);
1617
1618 contact.setCompanyId(user.getCompanyId());
1619 contact.setUserName(StringPool.BLANK);
1620 contact.setCreateDate(now);
1621 contact.setAccountId(company.getAccountId());
1622 contact.setParentContactId(ContactImpl.DEFAULT_PARENT_CONTACT_ID);
1623 }
1624
1625 contact.setModifiedDate(now);
1626 contact.setFirstName(firstName);
1627 contact.setMiddleName(middleName);
1628 contact.setLastName(lastName);
1629 contact.setPrefixId(prefixId);
1630 contact.setSuffixId(suffixId);
1631 contact.setMale(male);
1632 contact.setBirthday(birthday);
1633 contact.setSmsSn(smsSn);
1634 contact.setAimSn(aimSn);
1635 contact.setIcqSn(icqSn);
1636 contact.setJabberSn(jabberSn);
1637 contact.setMsnSn(msnSn);
1638 contact.setSkypeSn(skypeSn);
1639 contact.setYmSn(ymSn);
1640 contact.setJobTitle(jobTitle);
1641
1642 ContactUtil.update(contact);
1643
1644
1646 updateOrganizations(userId, organizationId, locationId);
1647
1648
1650 PermissionCacheUtil.clearCache();
1651
1652 return user;
1653 }
1654
1655 protected int authenticate(
1656 long companyId, String login, String password, String authType,
1657 Map headerMap, Map parameterMap)
1658 throws PortalException, SystemException {
1659
1660 login = login.trim().toLowerCase();
1661
1662 long userId = GetterUtil.getLong(login);
1663
1664
1666 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1667 if (!Validator.isEmailAddress(login)) {
1668 throw new UserEmailAddressException();
1669 }
1670 }
1671 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1672 if (Validator.isNull(login)) {
1673 throw new UserScreenNameException();
1674 }
1675 }
1676 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1677 if (Validator.isNull(login)) {
1678 throw new UserIdException();
1679 }
1680 }
1681
1682 if (Validator.isNull(password)) {
1683 throw new UserPasswordException(
1684 UserPasswordException.PASSWORD_INVALID);
1685 }
1686
1687 int authResult = Authenticator.FAILURE;
1688
1689
1691 String[] authPipelinePre =
1692 PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE);
1693
1694 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1695 authResult = AuthPipeline.authenticateByEmailAddress(
1696 authPipelinePre, companyId, login, password, headerMap,
1697 parameterMap);
1698 }
1699 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1700 authResult = AuthPipeline.authenticateByScreenName(
1701 authPipelinePre, companyId, login, password, headerMap,
1702 parameterMap);
1703 }
1704 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1705 authResult = AuthPipeline.authenticateByUserId(
1706 authPipelinePre, companyId, userId, password, headerMap,
1707 parameterMap);
1708 }
1709
1710
1712 User user = null;
1713
1714 try {
1715 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1716 user = UserUtil.findByC_EA(companyId, login);
1717 }
1718 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1719 user = UserUtil.findByC_SN(companyId, login);
1720 }
1721 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1722 user = UserUtil.findByC_U(companyId, GetterUtil.getLong(login));
1723 }
1724 }
1725 catch (NoSuchUserException nsue) {
1726 return Authenticator.DNE;
1727 }
1728
1729 if (user.isDefaultUser()) {
1730 _log.error(
1731 "The default user should never be allowed to authenticate");
1732
1733 return Authenticator.DNE;
1734 }
1735
1736 if (!user.isPasswordEncrypted()) {
1737 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
1738 user.setPasswordEncrypted(true);
1739
1740 UserUtil.update(user);
1741 }
1742
1743
1746 checkLockout(user);
1747
1748 checkPasswordExpired(user);
1749
1750
1752 if (authResult == Authenticator.SUCCESS) {
1753 if (GetterUtil.getBoolean(PropsUtil.get(
1754 PropsUtil.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK))) {
1755
1756 String encPwd = PwdEncryptor.encrypt(
1757 password, user.getPassword());
1758
1759 if (user.getPassword().equals(encPwd)) {
1760 authResult = Authenticator.SUCCESS;
1761 }
1762 else if (GetterUtil.getBoolean(PropsUtil.get(
1763 PropsUtil.AUTH_MAC_ALLOW))) {
1764
1765 try {
1766 MessageDigest digester = MessageDigest.getInstance(
1767 PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM));
1768
1769 digester.update(login.getBytes("UTF8"));
1770
1771 String shardKey =
1772 PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY);
1773
1774 encPwd = Base64.encode(
1775 digester.digest(shardKey.getBytes("UTF8")));
1776
1777 if (password.equals(encPwd)) {
1778 authResult = Authenticator.SUCCESS;
1779 }
1780 else {
1781 authResult = Authenticator.FAILURE;
1782 }
1783 }
1784 catch (NoSuchAlgorithmException nsae) {
1785 throw new SystemException(nsae);
1786 }
1787 catch (UnsupportedEncodingException uee) {
1788 throw new SystemException(uee);
1789 }
1790 }
1791 else {
1792 authResult = Authenticator.FAILURE;
1793 }
1794 }
1795 }
1796
1797
1799 if (authResult == Authenticator.SUCCESS) {
1800 String[] authPipelinePost =
1801 PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST);
1802
1803 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1804 authResult = AuthPipeline.authenticateByEmailAddress(
1805 authPipelinePost, companyId, login, password, headerMap,
1806 parameterMap);
1807 }
1808 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1809 authResult = AuthPipeline.authenticateByScreenName(
1810 authPipelinePost, companyId, login, password, headerMap,
1811 parameterMap);
1812 }
1813 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1814 authResult = AuthPipeline.authenticateByUserId(
1815 authPipelinePost, companyId, userId, password, headerMap,
1816 parameterMap);
1817 }
1818 }
1819
1820
1822 if (authResult == Authenticator.FAILURE) {
1823 try {
1824 String[] authFailure =
1825 PropsUtil.getArray(PropsUtil.AUTH_FAILURE);
1826
1827 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1828 AuthPipeline.onFailureByEmailAddress(
1829 authFailure, companyId, login, headerMap, parameterMap);
1830 }
1831 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1832 AuthPipeline.onFailureByScreenName(
1833 authFailure, companyId, login, headerMap, parameterMap);
1834 }
1835 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1836 AuthPipeline.onFailureByUserId(
1837 authFailure, companyId, userId, headerMap,
1838 parameterMap);
1839 }
1840
1841
1843 if (!PortalLDAPUtil.isPasswordPolicyEnabled(
1844 user.getCompanyId())) {
1845
1846 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1847
1848 int failedLoginAttempts = user.getFailedLoginAttempts();
1849 int maxFailures = passwordPolicy.getMaxFailure();
1850
1851 if ((failedLoginAttempts >= maxFailures) &&
1852 (maxFailures != 0)) {
1853
1854 String[] authMaxFailures =
1855 PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES);
1856
1857 if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) {
1858 AuthPipeline.onMaxFailuresByEmailAddress(
1859 authMaxFailures, companyId, login, headerMap,
1860 parameterMap);
1861 }
1862 else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
1863 AuthPipeline.onMaxFailuresByScreenName(
1864 authMaxFailures, companyId, login, headerMap,
1865 parameterMap);
1866 }
1867 else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) {
1868 AuthPipeline.onMaxFailuresByUserId(
1869 authMaxFailures, companyId, userId, headerMap,
1870 parameterMap);
1871 }
1872 }
1873 }
1874 }
1875 catch (Exception e) {
1876 _log.error(e, e);
1877 }
1878 }
1879
1880 return authResult;
1881 }
1882
1883 protected void sendEmail(User user, String password)
1884 throws PortalException, SystemException {
1885
1886 if (!PrefsPropsUtil.getBoolean(
1887 user.getCompanyId(),
1888 PropsUtil.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
1889
1890 return;
1891 }
1892
1893 try {
1894 long companyId = user.getCompanyId();
1895
1896 Company company = CompanyUtil.findByPrimaryKey(companyId);
1897
1898 String fromName = PrefsPropsUtil.getString(
1899 companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
1900 String fromAddress = PrefsPropsUtil.getString(
1901 companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
1902
1903 String toName = user.getFullName();
1904 String toAddress = user.getEmailAddress();
1905
1906 String subject = PrefsPropsUtil.getContent(
1907 companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_SUBJECT);
1908 String body = PrefsPropsUtil.getContent(
1909 companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_BODY);
1910
1911 subject = StringUtil.replace(
1912 subject,
1913 new String[] {
1914 "[$FROM_ADDRESS$]",
1915 "[$FROM_NAME$]",
1916 "[$PORTAL_URL$]",
1917 "[$TO_ADDRESS$]",
1918 "[$TO_NAME$]",
1919 "[$USER_ID$]",
1920 "[$USER_PASSWORD$]"
1921 },
1922 new String[] {
1923 fromAddress,
1924 fromName,
1925 company.getVirtualHost(),
1926 toAddress,
1927 toName,
1928 String.valueOf(user.getUserId()),
1929 password
1930 });
1931
1932 body = StringUtil.replace(
1933 body,
1934 new String[] {
1935 "[$FROM_ADDRESS$]",
1936 "[$FROM_NAME$]",
1937 "[$PORTAL_URL$]",
1938 "[$TO_ADDRESS$]",
1939 "[$TO_NAME$]",
1940 "[$USER_ID$]",
1941 "[$USER_PASSWORD$]"
1942 },
1943 new String[] {
1944 fromAddress,
1945 fromName,
1946 company.getVirtualHost(),
1947 toAddress,
1948 toName,
1949 String.valueOf(user.getUserId()),
1950 password
1951 });
1952
1953 InternetAddress from = new InternetAddress(fromAddress, fromName);
1954
1955 InternetAddress to = new InternetAddress(toAddress, toName);
1956
1957 MailMessage message = new MailMessage(
1958 from, to, subject, body, true);
1959
1960 MailServiceUtil.sendEmail(message);
1961 }
1962 catch (IOException ioe) {
1963 throw new SystemException(ioe);
1964 }
1965 }
1966
1967 protected void validate(
1968 long userId, String screenName, String emailAddress,
1969 String firstName, String lastName, String smsSn)
1970 throws PortalException, SystemException {
1971
1972 User user = UserUtil.findByPrimaryKey(userId);
1973
1974 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
1975 validateScreenName(user.getCompanyId(), screenName);
1976 }
1977
1978 validateEmailAddress(emailAddress);
1979
1980 if (!user.isDefaultUser()) {
1981 try {
1982 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
1983 if (UserUtil.findByC_EA(
1984 user.getCompanyId(), emailAddress) != null) {
1985
1986 throw new DuplicateUserEmailAddressException();
1987 }
1988 }
1989 }
1990 catch (NoSuchUserException nsue) {
1991 }
1992
1993 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
1994 user.getCompanyId(), PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES);
1995
1996 for (int i = 0; i < reservedEmailAddresses.length; i++) {
1997 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
1998 throw new ReservedUserEmailAddressException();
1999 }
2000 }
2001
2002 if (Validator.isNull(firstName)) {
2003 throw new ContactFirstNameException();
2004 }
2005 else if (Validator.isNull(lastName)) {
2006 throw new ContactLastNameException();
2007 }
2008 }
2009
2010 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2011 throw new UserSmsException();
2012 }
2013 }
2014
2015 protected void validate(
2016 long companyId, boolean autoPassword, String password1,
2017 String password2, boolean autoScreenName, String screenName,
2018 String emailAddress, String firstName, String lastName,
2019 long organizationId, long locationId)
2020 throws PortalException, SystemException {
2021
2022 if (!autoScreenName) {
2023 validateScreenName(companyId, screenName);
2024 }
2025
2026 if (!autoPassword) {
2027 PasswordPolicy passwordPolicy =
2028 PasswordPolicyLocalServiceUtil.getDefaultPasswordPolicy(
2029 companyId);
2030
2031 PwdToolkitUtil.validate(
2032 companyId, 0, password1, password2, passwordPolicy);
2033 }
2034
2035 validateEmailAddress(emailAddress);
2036
2037 try {
2038 User user = UserUtil.findByC_EA(companyId, emailAddress);
2039
2040 if (user != null) {
2041 throw new DuplicateUserEmailAddressException();
2042 }
2043 }
2044 catch (NoSuchUserException nsue) {
2045 }
2046
2047 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2048 companyId, PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES);
2049
2050 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2051 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2052 throw new ReservedUserEmailAddressException();
2053 }
2054 }
2055
2056 if (Validator.isNull(firstName)) {
2057 throw new ContactFirstNameException();
2058 }
2059 else if (Validator.isNull(lastName)) {
2060 throw new ContactLastNameException();
2061 }
2062 }
2063
2064 protected void validateEmailAddress(String emailAddress)
2065 throws PortalException {
2066
2067 if (!Validator.isEmailAddress(emailAddress) ||
2068 emailAddress.startsWith("root@") ||
2069 emailAddress.startsWith("postmaster@")) {
2070
2071 throw new UserEmailAddressException();
2072 }
2073 }
2074
2075 protected void validateOrganizations(
2076 long companyId, long organizationId, long locationId)
2077 throws PortalException, SystemException {
2078
2079 boolean organizationRequired = GetterUtil.getBoolean(PropsUtil.get(
2080 PropsUtil.ORGANIZATIONS_PARENT_ORGANIZATION_REQUIRED));
2081
2082 boolean locationRequired = GetterUtil.getBoolean(PropsUtil.get(
2083 PropsUtil.ORGANIZATIONS_LOCATION_REQUIRED));
2084
2085 if (locationRequired) {
2086 organizationRequired = true;
2087 }
2088
2089 Organization organization = null;
2090
2091 if (organizationRequired || (organizationId > 0)) {
2092 organization = OrganizationUtil.findByPrimaryKey(organizationId);
2093 }
2094
2095 Organization location = null;
2096
2097 if (locationRequired || (locationId > 0)) {
2098 location = OrganizationUtil.findByPrimaryKey(locationId);
2099 }
2100
2101 if ((organization != null) && (location != null)) {
2102
2103
2105 if (!OrganizationLocalServiceUtil.isAncestor(
2106 locationId, organizationId)) {
2107
2108 throw new OrganizationParentException();
2109 }
2110 }
2111 }
2112
2113 protected void validatePassword(
2114 long companyId, long userId, String password1, String password2)
2115 throws PortalException, SystemException {
2116
2117 if (Validator.isNull(password1) || Validator.isNull(password2)) {
2118 throw new UserPasswordException(
2119 UserPasswordException.PASSWORD_INVALID);
2120 }
2121
2122 if (!password1.equals(password2)) {
2123 throw new UserPasswordException(
2124 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2125 }
2126
2127 PasswordPolicy passwordPolicy =
2128 PasswordPolicyLocalServiceUtil.getPasswordPolicyByUserId(
2129 userId);
2130
2131 PwdToolkitUtil.validate(
2132 companyId, userId, password1, password2, passwordPolicy);
2133 }
2134
2135 protected void validateScreenName(long companyId, String screenName)
2136 throws PortalException, SystemException {
2137
2138 if (Validator.isNull(screenName)) {
2139 throw new UserScreenNameException();
2140 }
2141
2142 ScreenNameValidator screenNameValidator =
2143 (ScreenNameValidator)InstancePool.get(
2144 PropsUtil.get(PropsUtil.USERS_SCREEN_NAME_VALIDATOR));
2145
2146 if (screenNameValidator != null) {
2147 if (!screenNameValidator.validate(companyId, screenName)) {
2148 throw new UserScreenNameException();
2149 }
2150 }
2151
2152 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2153
2154 for (int i = 0; i < anonymousNames.length; i++) {
2155 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2156 throw new UserScreenNameException();
2157 }
2158 }
2159
2160 User user = UserUtil.fetchByC_SN(companyId, screenName);
2161
2162 if (user != null) {
2163 throw new DuplicateUserScreenNameException();
2164 }
2165
2166 String friendlyURL = StringPool.SLASH + screenName;
2167
2168 Group group = GroupUtil.fetchByC_F(companyId, friendlyURL);
2169
2170 if (group != null) {
2171 throw new DuplicateUserScreenNameException();
2172 }
2173
2174 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2175 companyId, PropsUtil.ADMIN_RESERVED_SCREEN_NAMES);
2176
2177 for (int i = 0; i < reservedScreenNames.length; i++) {
2178 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2179 throw new ReservedUserScreenNameException();
2180 }
2181 }
2182 }
2183
2184 private static Log _log = LogFactory.getLog(UserLocalServiceImpl.class);
2185
2186}