001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.security.pwd;
016    
017    import com.liferay.portal.exception.UserPasswordException;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.model.PasswordPolicy;
020    import com.liferay.portal.security.ldap.LDAPSettingsUtil;
021    import com.liferay.registry.Registry;
022    import com.liferay.registry.RegistryUtil;
023    import com.liferay.registry.ServiceTracker;
024    
025    /**
026     * @author Brian Wing Shun Chan
027     */
028    public class PwdToolkitUtil {
029    
030            public static String generate(PasswordPolicy passwordPolicy) {
031                    Toolkit toolkit = getToolkit();
032    
033                    return toolkit.generate(passwordPolicy);
034            }
035    
036            public static Toolkit getToolkit() {
037                    return _instance._serviceTracker.getService();
038            }
039    
040            public static void validate(
041                            long companyId, long userId, String password1, String password2,
042                            PasswordPolicy passwordPolicy)
043                    throws PortalException {
044    
045                    if (!password1.equals(password2)) {
046                            throw new UserPasswordException.MustMatch(userId);
047                    }
048    
049                    if (!LDAPSettingsUtil.isPasswordPolicyEnabled(companyId) &&
050                            PwdToolkitUtilThreadLocal.isValidate()) {
051    
052                            Toolkit toolkit = getToolkit();
053    
054                            toolkit.validate(userId, password1, password2, passwordPolicy);
055                    }
056            }
057    
058            private PwdToolkitUtil() {
059                    Registry registry = RegistryUtil.getRegistry();
060    
061                    _serviceTracker = registry.trackServices(Toolkit.class);
062    
063                    _serviceTracker.open();
064            }
065    
066            private static final PwdToolkitUtil _instance = new PwdToolkitUtil();
067    
068            private final ServiceTracker<Toolkit, Toolkit> _serviceTracker;
069    
070    }