001    /**
002     * Copyright (c) 2000-2010 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.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    }