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