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