001    /**
002     * Copyright (c) 2000-2011 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            @Override
040            public String generate(PasswordPolicy passwordPolicy) {
041                    return PwdGenerator.getPassword(_charset, _length);
042            }
043    
044            @Override
045            public void validate(
046                            long userId, String password1, String password2,
047                            PasswordPolicy passwordPolicy)
048                    throws PortalException {
049    
050                    boolean value = password1.matches(_pattern);
051    
052                    if (!value) {
053                            if (_log.isWarnEnabled()) {
054                                    _log.warn("User " + userId + " attempted an invalid password");
055                            }
056    
057                            throw new UserPasswordException(
058                                    UserPasswordException.PASSWORD_INVALID);
059                    }
060            }
061    
062            private static Log _log = LogFactoryUtil.getLog(RegExpToolkit.class);
063    
064            private String _pattern;
065            private String _charset;
066            private int _length;
067    
068    }