001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.util.GetterUtil;
022    import com.liferay.portal.kernel.util.PropsKeys;
023    import com.liferay.portal.model.PasswordPolicy;
024    import com.liferay.portal.util.PropsUtil;
025    import com.liferay.util.PwdGenerator;
026    
027    /**
028     * @author Brian Wing Shun Chan
029     */
030    public class RegExpToolkit extends BasicToolkit {
031    
032            public RegExpToolkit() {
033                    _pattern = PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_PATTERN);
034                    _charset = PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_CHARSET);
035                    _length = GetterUtil.getInteger(
036                            PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_LENGTH));
037            }
038    
039            public String generate(PasswordPolicy passwordPolicy) {
040                    return PwdGenerator.getPassword(_charset, _length);
041            }
042    
043            public void validate(
044                            long userId, String password1, String password2,
045                            PasswordPolicy passwordPolicy)
046                    throws PortalException {
047    
048                    boolean value = password1.matches(_pattern);
049    
050                    if (!value) {
051                            if (_log.isWarnEnabled()) {
052                                    _log.warn("User " + userId + " attempted an invalid password");
053                            }
054    
055                            throw new UserPasswordException(
056                                    UserPasswordException.PASSWORD_INVALID);
057                    }
058            }
059    
060            private static Log _log = LogFactoryUtil.getLog(RegExpToolkit.class);
061    
062            private String _pattern;
063            private String _charset;
064            private int _length;
065    
066    }