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.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(
047                                    UserPasswordException.PASSWORDS_DO_NOT_MATCH);
048                    }
049    
050                    if (!LDAPSettingsUtil.isPasswordPolicyEnabled(companyId) &&
051                            PwdToolkitUtilThreadLocal.isValidate()) {
052    
053                            Toolkit toolkit = getToolkit();
054    
055                            toolkit.validate(userId, password1, password2, passwordPolicy);
056                    }
057            }
058    
059            private PwdToolkitUtil() {
060                    Registry registry = RegistryUtil.getRegistry();
061    
062                    _serviceTracker = registry.trackServices(Toolkit.class);
063    
064                    _serviceTracker.open();
065            }
066    
067            private static final PwdToolkitUtil _instance = new PwdToolkitUtil();
068    
069            private final ServiceTracker<Toolkit, Toolkit> _serviceTracker;
070    
071    }